BreakCriticalEdges.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. //===- BreakCriticalEdges.cpp - Critical Edge Elimination Pass ------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // BreakCriticalEdges pass - Break all of the critical edges in the CFG by
  11. // inserting a dummy basic block. This pass may be "required" by passes that
  12. // cannot deal with critical edges. For this usage, the structure type is
  13. // forward declared. This pass obviously invalidates the CFG, but can update
  14. // dominator trees.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #define DEBUG_TYPE "break-crit-edges"
  18. #include "llvm/Transforms/Scalar.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/Analysis/CFG.h"
  22. #include "llvm/Analysis/Dominators.h"
  23. #include "llvm/Analysis/LoopInfo.h"
  24. #include "llvm/IR/Function.h"
  25. #include "llvm/IR/Instructions.h"
  26. #include "llvm/IR/Type.h"
  27. #include "llvm/Support/CFG.h"
  28. #include "llvm/Support/ErrorHandling.h"
  29. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  30. using namespace llvm;
  31. STATISTIC(NumBroken, "Number of blocks inserted");
  32. namespace {
  33. struct BreakCriticalEdges : public FunctionPass {
  34. static char ID; // Pass identification, replacement for typeid
  35. BreakCriticalEdges() : FunctionPass(ID) {
  36. initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry());
  37. }
  38. virtual bool runOnFunction(Function &F);
  39. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  40. AU.addPreserved<DominatorTree>();
  41. AU.addPreserved<LoopInfo>();
  42. // No loop canonicalization guarantees are broken by this pass.
  43. AU.addPreservedID(LoopSimplifyID);
  44. }
  45. };
  46. }
  47. char BreakCriticalEdges::ID = 0;
  48. INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges",
  49. "Break critical edges in CFG", false, false)
  50. // Publicly exposed interface to pass...
  51. char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID;
  52. FunctionPass *llvm::createBreakCriticalEdgesPass() {
  53. return new BreakCriticalEdges();
  54. }
  55. // runOnFunction - Loop over all of the edges in the CFG, breaking critical
  56. // edges as they are found.
  57. //
  58. bool BreakCriticalEdges::runOnFunction(Function &F) {
  59. bool Changed = false;
  60. for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
  61. TerminatorInst *TI = I->getTerminator();
  62. if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
  63. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  64. if (SplitCriticalEdge(TI, i, this)) {
  65. ++NumBroken;
  66. Changed = true;
  67. }
  68. }
  69. return Changed;
  70. }
  71. //===----------------------------------------------------------------------===//
  72. // Implementation of the external critical edge manipulation functions
  73. //===----------------------------------------------------------------------===//
  74. /// createPHIsForSplitLoopExit - When a loop exit edge is split, LCSSA form
  75. /// may require new PHIs in the new exit block. This function inserts the
  76. /// new PHIs, as needed. Preds is a list of preds inside the loop, SplitBB
  77. /// is the new loop exit block, and DestBB is the old loop exit, now the
  78. /// successor of SplitBB.
  79. static void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
  80. BasicBlock *SplitBB,
  81. BasicBlock *DestBB) {
  82. // SplitBB shouldn't have anything non-trivial in it yet.
  83. assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
  84. SplitBB->isLandingPad()) && "SplitBB has non-PHI nodes!");
  85. // For each PHI in the destination block.
  86. for (BasicBlock::iterator I = DestBB->begin();
  87. PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  88. unsigned Idx = PN->getBasicBlockIndex(SplitBB);
  89. Value *V = PN->getIncomingValue(Idx);
  90. // If the input is a PHI which already satisfies LCSSA, don't create
  91. // a new one.
  92. if (const PHINode *VP = dyn_cast<PHINode>(V))
  93. if (VP->getParent() == SplitBB)
  94. continue;
  95. // Otherwise a new PHI is needed. Create one and populate it.
  96. PHINode *NewPN =
  97. PHINode::Create(PN->getType(), Preds.size(), "split",
  98. SplitBB->isLandingPad() ?
  99. SplitBB->begin() : SplitBB->getTerminator());
  100. for (unsigned i = 0, e = Preds.size(); i != e; ++i)
  101. NewPN->addIncoming(V, Preds[i]);
  102. // Update the original PHI.
  103. PN->setIncomingValue(Idx, NewPN);
  104. }
  105. }
  106. /// SplitCriticalEdge - If this edge is a critical edge, insert a new node to
  107. /// split the critical edge. This will update DominatorTree information if it
  108. /// is available, thus calling this pass will not invalidate either of them.
  109. /// This returns the new block if the edge was split, null otherwise.
  110. ///
  111. /// If MergeIdenticalEdges is true (not the default), *all* edges from TI to the
  112. /// specified successor will be merged into the same critical edge block.
  113. /// This is most commonly interesting with switch instructions, which may
  114. /// have many edges to any one destination. This ensures that all edges to that
  115. /// dest go to one block instead of each going to a different block, but isn't
  116. /// the standard definition of a "critical edge".
  117. ///
  118. /// It is invalid to call this function on a critical edge that starts at an
  119. /// IndirectBrInst. Splitting these edges will almost always create an invalid
  120. /// program because the address of the new block won't be the one that is jumped
  121. /// to.
  122. ///
  123. BasicBlock *llvm::SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum,
  124. Pass *P, bool MergeIdenticalEdges,
  125. bool DontDeleteUselessPhis,
  126. bool SplitLandingPads) {
  127. if (!isCriticalEdge(TI, SuccNum, MergeIdenticalEdges)) return 0;
  128. assert(!isa<IndirectBrInst>(TI) &&
  129. "Cannot split critical edge from IndirectBrInst");
  130. BasicBlock *TIBB = TI->getParent();
  131. BasicBlock *DestBB = TI->getSuccessor(SuccNum);
  132. // Splitting the critical edge to a landing pad block is non-trivial. Don't do
  133. // it in this generic function.
  134. if (DestBB->isLandingPad()) return 0;
  135. // Create a new basic block, linking it into the CFG.
  136. BasicBlock *NewBB = BasicBlock::Create(TI->getContext(),
  137. TIBB->getName() + "." + DestBB->getName() + "_crit_edge");
  138. // Create our unconditional branch.
  139. BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
  140. NewBI->setDebugLoc(TI->getDebugLoc());
  141. // Branch to the new block, breaking the edge.
  142. TI->setSuccessor(SuccNum, NewBB);
  143. // Insert the block into the function... right after the block TI lives in.
  144. Function &F = *TIBB->getParent();
  145. Function::iterator FBBI = TIBB;
  146. F.getBasicBlockList().insert(++FBBI, NewBB);
  147. // If there are any PHI nodes in DestBB, we need to update them so that they
  148. // merge incoming values from NewBB instead of from TIBB.
  149. {
  150. unsigned BBIdx = 0;
  151. for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
  152. // We no longer enter through TIBB, now we come in through NewBB.
  153. // Revector exactly one entry in the PHI node that used to come from
  154. // TIBB to come from NewBB.
  155. PHINode *PN = cast<PHINode>(I);
  156. // Reuse the previous value of BBIdx if it lines up. In cases where we
  157. // have multiple phi nodes with *lots* of predecessors, this is a speed
  158. // win because we don't have to scan the PHI looking for TIBB. This
  159. // happens because the BB list of PHI nodes are usually in the same
  160. // order.
  161. if (PN->getIncomingBlock(BBIdx) != TIBB)
  162. BBIdx = PN->getBasicBlockIndex(TIBB);
  163. PN->setIncomingBlock(BBIdx, NewBB);
  164. }
  165. }
  166. // If there are any other edges from TIBB to DestBB, update those to go
  167. // through the split block, making those edges non-critical as well (and
  168. // reducing the number of phi entries in the DestBB if relevant).
  169. if (MergeIdenticalEdges) {
  170. for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
  171. if (TI->getSuccessor(i) != DestBB) continue;
  172. // Remove an entry for TIBB from DestBB phi nodes.
  173. DestBB->removePredecessor(TIBB, DontDeleteUselessPhis);
  174. // We found another edge to DestBB, go to NewBB instead.
  175. TI->setSuccessor(i, NewBB);
  176. }
  177. }
  178. // If we don't have a pass object, we can't update anything...
  179. if (P == 0) return NewBB;
  180. DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>();
  181. LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>();
  182. // If we have nothing to update, just return.
  183. if (DT == 0 && LI == 0)
  184. return NewBB;
  185. // Now update analysis information. Since the only predecessor of NewBB is
  186. // the TIBB, TIBB clearly dominates NewBB. TIBB usually doesn't dominate
  187. // anything, as there are other successors of DestBB. However, if all other
  188. // predecessors of DestBB are already dominated by DestBB (e.g. DestBB is a
  189. // loop header) then NewBB dominates DestBB.
  190. SmallVector<BasicBlock*, 8> OtherPreds;
  191. // If there is a PHI in the block, loop over predecessors with it, which is
  192. // faster than iterating pred_begin/end.
  193. if (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
  194. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  195. if (PN->getIncomingBlock(i) != NewBB)
  196. OtherPreds.push_back(PN->getIncomingBlock(i));
  197. } else {
  198. for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB);
  199. I != E; ++I) {
  200. BasicBlock *P = *I;
  201. if (P != NewBB)
  202. OtherPreds.push_back(P);
  203. }
  204. }
  205. bool NewBBDominatesDestBB = true;
  206. // Should we update DominatorTree information?
  207. if (DT) {
  208. DomTreeNode *TINode = DT->getNode(TIBB);
  209. // The new block is not the immediate dominator for any other nodes, but
  210. // TINode is the immediate dominator for the new node.
  211. //
  212. if (TINode) { // Don't break unreachable code!
  213. DomTreeNode *NewBBNode = DT->addNewBlock(NewBB, TIBB);
  214. DomTreeNode *DestBBNode = 0;
  215. // If NewBBDominatesDestBB hasn't been computed yet, do so with DT.
  216. if (!OtherPreds.empty()) {
  217. DestBBNode = DT->getNode(DestBB);
  218. while (!OtherPreds.empty() && NewBBDominatesDestBB) {
  219. if (DomTreeNode *OPNode = DT->getNode(OtherPreds.back()))
  220. NewBBDominatesDestBB = DT->dominates(DestBBNode, OPNode);
  221. OtherPreds.pop_back();
  222. }
  223. OtherPreds.clear();
  224. }
  225. // If NewBBDominatesDestBB, then NewBB dominates DestBB, otherwise it
  226. // doesn't dominate anything.
  227. if (NewBBDominatesDestBB) {
  228. if (!DestBBNode) DestBBNode = DT->getNode(DestBB);
  229. DT->changeImmediateDominator(DestBBNode, NewBBNode);
  230. }
  231. }
  232. }
  233. // Update LoopInfo if it is around.
  234. if (LI) {
  235. if (Loop *TIL = LI->getLoopFor(TIBB)) {
  236. // If one or the other blocks were not in a loop, the new block is not
  237. // either, and thus LI doesn't need to be updated.
  238. if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
  239. if (TIL == DestLoop) {
  240. // Both in the same loop, the NewBB joins loop.
  241. DestLoop->addBasicBlockToLoop(NewBB, LI->getBase());
  242. } else if (TIL->contains(DestLoop)) {
  243. // Edge from an outer loop to an inner loop. Add to the outer loop.
  244. TIL->addBasicBlockToLoop(NewBB, LI->getBase());
  245. } else if (DestLoop->contains(TIL)) {
  246. // Edge from an inner loop to an outer loop. Add to the outer loop.
  247. DestLoop->addBasicBlockToLoop(NewBB, LI->getBase());
  248. } else {
  249. // Edge from two loops with no containment relation. Because these
  250. // are natural loops, we know that the destination block must be the
  251. // header of its loop (adding a branch into a loop elsewhere would
  252. // create an irreducible loop).
  253. assert(DestLoop->getHeader() == DestBB &&
  254. "Should not create irreducible loops!");
  255. if (Loop *P = DestLoop->getParentLoop())
  256. P->addBasicBlockToLoop(NewBB, LI->getBase());
  257. }
  258. }
  259. // If TIBB is in a loop and DestBB is outside of that loop, split the
  260. // other exit blocks of the loop that also have predecessors outside
  261. // the loop, to maintain a LoopSimplify guarantee.
  262. if (!TIL->contains(DestBB) &&
  263. P->mustPreserveAnalysisID(LoopSimplifyID)) {
  264. assert(!TIL->contains(NewBB) &&
  265. "Split point for loop exit is contained in loop!");
  266. // Update LCSSA form in the newly created exit block.
  267. if (P->mustPreserveAnalysisID(LCSSAID))
  268. createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
  269. // For each unique exit block...
  270. // FIXME: This code is functionally equivalent to the corresponding
  271. // loop in LoopSimplify.
  272. SmallVector<BasicBlock *, 4> ExitBlocks;
  273. TIL->getExitBlocks(ExitBlocks);
  274. for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
  275. // Collect all the preds that are inside the loop, and note
  276. // whether there are any preds outside the loop.
  277. SmallVector<BasicBlock *, 4> Preds;
  278. bool HasPredOutsideOfLoop = false;
  279. BasicBlock *Exit = ExitBlocks[i];
  280. for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit);
  281. I != E; ++I) {
  282. BasicBlock *P = *I;
  283. if (TIL->contains(P)) {
  284. if (isa<IndirectBrInst>(P->getTerminator())) {
  285. Preds.clear();
  286. break;
  287. }
  288. Preds.push_back(P);
  289. } else {
  290. HasPredOutsideOfLoop = true;
  291. }
  292. }
  293. // If there are any preds not in the loop, we'll need to split
  294. // the edges. The Preds.empty() check is needed because a block
  295. // may appear multiple times in the list. We can't use
  296. // getUniqueExitBlocks above because that depends on LoopSimplify
  297. // form, which we're in the process of restoring!
  298. if (!Preds.empty() && HasPredOutsideOfLoop) {
  299. if (!Exit->isLandingPad()) {
  300. BasicBlock *NewExitBB =
  301. SplitBlockPredecessors(Exit, Preds, "split", P);
  302. if (P->mustPreserveAnalysisID(LCSSAID))
  303. createPHIsForSplitLoopExit(Preds, NewExitBB, Exit);
  304. } else if (SplitLandingPads) {
  305. SmallVector<BasicBlock*, 8> NewBBs;
  306. SplitLandingPadPredecessors(Exit, Preds,
  307. ".split1", ".split2",
  308. P, NewBBs);
  309. if (P->mustPreserveAnalysisID(LCSSAID))
  310. createPHIsForSplitLoopExit(Preds, NewBBs[0], Exit);
  311. }
  312. }
  313. }
  314. }
  315. // LCSSA form was updated above for the case where LoopSimplify is
  316. // available, which means that all predecessors of loop exit blocks
  317. // are within the loop. Without LoopSimplify form, it would be
  318. // necessary to insert a new phi.
  319. assert((!P->mustPreserveAnalysisID(LCSSAID) ||
  320. P->mustPreserveAnalysisID(LoopSimplifyID)) &&
  321. "SplitCriticalEdge doesn't know how to update LCCSA form "
  322. "without LoopSimplify!");
  323. }
  324. }
  325. return NewBB;
  326. }