BreakCriticalEdges.cpp 15 KB

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