Teach SplitCriticalEdge to update LoopInfo if it is alive. This fixes
[oota-llvm.git] / lib / Transforms / Utils / BreakCriticalEdges.cpp
1 //===- BreakCriticalEdges.cpp - Critical Edge Elimination Pass ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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
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/Function.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Type.h"
26 #include "llvm/Support/CFG.h"
27 #include "llvm/ADT/Statistic.h"
28 using namespace llvm;
29
30 namespace {
31   Statistic<> NumBroken("break-crit-edges", "Number of blocks inserted");
32
33   struct BreakCriticalEdges : public FunctionPass {
34     virtual bool runOnFunction(Function &F);
35
36     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
37       AU.addPreserved<DominatorSet>();
38       AU.addPreserved<ImmediateDominators>();
39       AU.addPreserved<DominatorTree>();
40       AU.addPreserved<DominanceFrontier>();
41       AU.addPreserved<LoopInfo>();
42
43       // No loop canonicalization guarantees are broken by this pass.
44       AU.addPreservedID(LoopSimplifyID);
45     }
46   };
47
48   RegisterOpt<BreakCriticalEdges> X("break-crit-edges",
49                                     "Break critical edges in CFG");
50 }
51
52 // Publically exposed interface to pass...
53 const PassInfo *llvm::BreakCriticalEdgesID = X.getPassInfo();
54 FunctionPass *llvm::createBreakCriticalEdgesPass() {
55   return new BreakCriticalEdges();
56 }
57
58 // runOnFunction - Loop over all of the edges in the CFG, breaking critical
59 // edges as they are found.
60 //
61 bool BreakCriticalEdges::runOnFunction(Function &F) {
62   bool Changed = false;
63   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
64     TerminatorInst *TI = I->getTerminator();
65     if (TI->getNumSuccessors() > 1)
66       for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
67         if (SplitCriticalEdge(TI, i, this)) {
68           ++NumBroken;
69           Changed = true;
70         }
71   }
72
73   return Changed;
74 }
75
76 //===----------------------------------------------------------------------===//
77 //    Implementation of the external critical edge manipulation functions
78 //===----------------------------------------------------------------------===//
79
80 // isCriticalEdge - Return true if the specified edge is a critical edge.
81 // Critical edges are edges from a block with multiple successors to a block
82 // with multiple predecessors.
83 //
84 bool llvm::isCriticalEdge(const TerminatorInst *TI, unsigned SuccNum) {
85   assert(SuccNum < TI->getNumSuccessors() && "Illegal edge specification!");
86   if (TI->getNumSuccessors() == 1) return false;
87
88   const BasicBlock *Dest = TI->getSuccessor(SuccNum);
89   pred_const_iterator I = pred_begin(Dest), E = pred_end(Dest);
90
91   // If there is more than one predecessor, this is a critical edge...
92   assert(I != E && "No preds, but we have an edge to the block?");
93   ++I;        // Skip one edge due to the incoming arc from TI.
94   return I != E;
95 }
96
97 // SplitCriticalEdge - If this edge is a critical edge, insert a new node to
98 // split the critical edge.  This will update DominatorSet, ImmediateDominator,
99 // DominatorTree, and DominatorFrontier information if it is available, thus
100 // calling this pass will not invalidate either of them.  This returns true if
101 // the edge was split, false otherwise.
102 //
103 bool llvm::SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
104   if (!isCriticalEdge(TI, SuccNum)) return false;
105   BasicBlock *TIBB = TI->getParent();
106   BasicBlock *DestBB = TI->getSuccessor(SuccNum);
107
108   // Create a new basic block, linking it into the CFG.
109   BasicBlock *NewBB = new BasicBlock(TIBB->getName() + "." +
110                                      DestBB->getName() + "_crit_edge");
111   // Create our unconditional branch...
112   new BranchInst(DestBB, NewBB);
113
114   // Branch to the new block, breaking the edge...
115   TI->setSuccessor(SuccNum, NewBB);
116
117   // Insert the block into the function... right after the block TI lives in.
118   Function &F = *TIBB->getParent();
119   F.getBasicBlockList().insert(TIBB->getNext(), NewBB);
120
121   // If there are any PHI nodes in DestBB, we need to update them so that they
122   // merge incoming values from NewBB instead of from TIBB.
123   //
124   for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
125     PHINode *PN = cast<PHINode>(I);
126     // We no longer enter through TIBB, now we come in through NewBB.  Revector
127     // exactly one entry in the PHI node that used to come from TIBB to come
128     // from NewBB.
129     int BBIdx = PN->getBasicBlockIndex(TIBB);
130     PN->setIncomingBlock(BBIdx, NewBB);
131   }
132
133   // If we don't have a pass object, we can't update anything...
134   if (P == 0) return true;
135
136   // Now update analysis information.  These are the analyses that we are
137   // currently capable of updating...
138   //
139
140   // Should we update DominatorSet information?
141   if (DominatorSet *DS = P->getAnalysisToUpdate<DominatorSet>()) {
142     // The blocks that dominate the new one are the blocks that dominate TIBB
143     // plus the new block itself.
144     DominatorSet::DomSetType DomSet = DS->getDominators(TIBB);
145     DomSet.insert(NewBB);  // A block always dominates itself.
146     DS->addBasicBlock(NewBB, DomSet);
147   }
148
149   // Should we update ImmediateDominator information?
150   if (ImmediateDominators *ID = P->getAnalysisToUpdate<ImmediateDominators>()) {
151     // TIBB is the new immediate dominator for NewBB.  NewBB doesn't dominate
152     // anything.
153     ID->addNewBlock(NewBB, TIBB);
154   }
155
156   // Should we update DominatorTree information?
157   if (DominatorTree *DT = P->getAnalysisToUpdate<DominatorTree>()) {
158     DominatorTree::Node *TINode = DT->getNode(TIBB);
159
160     // The new block is not the immediate dominator for any other nodes, but
161     // TINode is the immediate dominator for the new node.
162     //
163     if (TINode)        // Don't break unreachable code!
164       DT->createNewNode(NewBB, TINode);
165   }
166
167   // Should we update DominanceFrontier information?
168   if (DominanceFrontier *DF = P->getAnalysisToUpdate<DominanceFrontier>()) {
169     // Since the new block is dominated by its only predecessor TIBB,
170     // it cannot be in any block's dominance frontier.  Its dominance
171     // frontier is {DestBB}.
172     DominanceFrontier::DomSetType NewDFSet;
173     NewDFSet.insert(DestBB);
174     DF->addBasicBlock(NewBB, NewDFSet);
175   }
176   
177   // Update LoopInfo if it is around.
178   if (LoopInfo *LI = P->getAnalysisToUpdate<LoopInfo>()) {
179     // If one or the other blocks were not in a loop, the new block is not
180     // either, and thus LI doesn't need to be updated.
181     if (Loop *TIL = LI->getLoopFor(TIBB))
182       if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
183         if (TIL == DestLoop) {
184           // Both in the same loop, the NewBB joins loop.
185           DestLoop->addBasicBlockToLoop(NewBB, *LI);
186         } else if (TIL->contains(DestLoop->getHeader())) {
187           // Edge from an outer loop to an inner loop.  Add to the outer lopo.
188           TIL->addBasicBlockToLoop(NewBB, *LI);
189         } else if (DestLoop->contains(TIL->getHeader())) {
190           // Edge from an inner loop to an outer loop.  Add to the outer lopo.
191           DestLoop->addBasicBlockToLoop(NewBB, *LI);
192         } else {
193           // Edge from two loops with no containment relation.  Because these
194           // are natural loops, we know that the destination block must be the
195           // header of its loop (adding a branch into a loop elsewhere would
196           // create an irreducible loop).
197           assert(DestLoop->getHeader() == DestBB &&
198                  "Should not create irreducible loops!");
199           if (Loop *P = DestLoop->getParentLoop())
200             P->addBasicBlockToLoop(NewBB, *LI);
201         }
202       }
203     
204   }
205   return true;
206 }