(Almost) always call reserveOperandSpace() on newly created PHINodes.
[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 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
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
33 STATISTIC(NumBroken, "Number of blocks inserted");
34
35 namespace {
36   struct BreakCriticalEdges : public FunctionPass {
37     static char ID; // Pass identification, replacement for typeid
38     BreakCriticalEdges() : FunctionPass(ID) {
39       initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry());
40     }
41
42     virtual bool runOnFunction(Function &F);
43
44     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
45       AU.addPreserved<DominatorTree>();
46       AU.addPreserved<LoopInfo>();
47       AU.addPreserved<ProfileInfo>();
48
49       // No loop canonicalization guarantees are broken by this pass.
50       AU.addPreservedID(LoopSimplifyID);
51     }
52   };
53 }
54
55 char BreakCriticalEdges::ID = 0;
56 INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges",
57                 "Break critical edges in CFG", false, false)
58
59 // Publically exposed interface to pass...
60 char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID;
61 FunctionPass *llvm::createBreakCriticalEdgesPass() {
62   return new BreakCriticalEdges();
63 }
64
65 // runOnFunction - Loop over all of the edges in the CFG, breaking critical
66 // edges as they are found.
67 //
68 bool BreakCriticalEdges::runOnFunction(Function &F) {
69   bool Changed = false;
70   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
71     TerminatorInst *TI = I->getTerminator();
72     if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
73       for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
74         if (SplitCriticalEdge(TI, i, this)) {
75           ++NumBroken;
76           Changed = true;
77         }
78   }
79
80   return Changed;
81 }
82
83 //===----------------------------------------------------------------------===//
84 //    Implementation of the external critical edge manipulation functions
85 //===----------------------------------------------------------------------===//
86
87 // isCriticalEdge - Return true if the specified edge is a critical edge.
88 // Critical edges are edges from a block with multiple successors to a block
89 // with multiple predecessors.
90 //
91 bool llvm::isCriticalEdge(const TerminatorInst *TI, unsigned SuccNum,
92                           bool AllowIdenticalEdges) {
93   assert(SuccNum < TI->getNumSuccessors() && "Illegal edge specification!");
94   if (TI->getNumSuccessors() == 1) return false;
95
96   const BasicBlock *Dest = TI->getSuccessor(SuccNum);
97   const_pred_iterator I = pred_begin(Dest), E = pred_end(Dest);
98
99   // If there is more than one predecessor, this is a critical edge...
100   assert(I != E && "No preds, but we have an edge to the block?");
101   const BasicBlock *FirstPred = *I;
102   ++I;        // Skip one edge due to the incoming arc from TI.
103   if (!AllowIdenticalEdges)
104     return I != E;
105   
106   // If AllowIdenticalEdges is true, then we allow this edge to be considered
107   // non-critical iff all preds come from TI's block.
108   while (I != E) {
109     const BasicBlock *P = *I;
110     if (P != FirstPred)
111       return true;
112     // Note: leave this as is until no one ever compiles with either gcc 4.0.1
113     // or Xcode 2. This seems to work around the pred_iterator assert in PR 2207
114     E = pred_end(P);
115     ++I;
116   }
117   return false;
118 }
119
120 /// CreatePHIsForSplitLoopExit - When a loop exit edge is split, LCSSA form
121 /// may require new PHIs in the new exit block. This function inserts the
122 /// new PHIs, as needed.  Preds is a list of preds inside the loop, SplitBB
123 /// is the new loop exit block, and DestBB is the old loop exit, now the
124 /// successor of SplitBB.
125 static void CreatePHIsForSplitLoopExit(SmallVectorImpl<BasicBlock *> &Preds,
126                                        BasicBlock *SplitBB,
127                                        BasicBlock *DestBB) {
128   // SplitBB shouldn't have anything non-trivial in it yet.
129   assert(SplitBB->getFirstNonPHI() == SplitBB->getTerminator() &&
130          "SplitBB has non-PHI nodes!");
131
132   // For each PHI in the destination block...
133   for (BasicBlock::iterator I = DestBB->begin();
134        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
135     unsigned Idx = PN->getBasicBlockIndex(SplitBB);
136     Value *V = PN->getIncomingValue(Idx);
137     // If the input is a PHI which already satisfies LCSSA, don't create
138     // a new one.
139     if (const PHINode *VP = dyn_cast<PHINode>(V))
140       if (VP->getParent() == SplitBB)
141         continue;
142     // Otherwise a new PHI is needed. Create one and populate it.
143     PHINode *NewPN = PHINode::Create(PN->getType(), "split",
144                                      SplitBB->getTerminator());
145     NewPN->reserveOperandSpace(Preds.size());
146     for (unsigned i = 0, e = Preds.size(); i != e; ++i)
147       NewPN->addIncoming(V, Preds[i]);
148     // Update the original PHI.
149     PN->setIncomingValue(Idx, NewPN);
150   }
151 }
152
153 /// SplitCriticalEdge - If this edge is a critical edge, insert a new node to
154 /// split the critical edge.  This will update DominatorTree information if it
155 /// is available, thus calling this pass will not invalidate either of them.
156 /// This returns the new block if the edge was split, null otherwise.
157 ///
158 /// If MergeIdenticalEdges is true (not the default), *all* edges from TI to the
159 /// specified successor will be merged into the same critical edge block.  
160 /// This is most commonly interesting with switch instructions, which may 
161 /// have many edges to any one destination.  This ensures that all edges to that
162 /// dest go to one block instead of each going to a different block, but isn't 
163 /// the standard definition of a "critical edge".
164 ///
165 /// It is invalid to call this function on a critical edge that starts at an
166 /// IndirectBrInst.  Splitting these edges will almost always create an invalid
167 /// program because the address of the new block won't be the one that is jumped
168 /// to.
169 ///
170 BasicBlock *llvm::SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum,
171                                     Pass *P, bool MergeIdenticalEdges) {
172   if (!isCriticalEdge(TI, SuccNum, MergeIdenticalEdges)) return 0;
173   
174   assert(!isa<IndirectBrInst>(TI) &&
175          "Cannot split critical edge from IndirectBrInst");
176   
177   BasicBlock *TIBB = TI->getParent();
178   BasicBlock *DestBB = TI->getSuccessor(SuccNum);
179
180   // Create a new basic block, linking it into the CFG.
181   BasicBlock *NewBB = BasicBlock::Create(TI->getContext(),
182                       TIBB->getName() + "." + DestBB->getName() + "_crit_edge");
183   // Create our unconditional branch.
184   BranchInst::Create(DestBB, NewBB);
185
186   // Branch to the new block, breaking the edge.
187   TI->setSuccessor(SuccNum, NewBB);
188
189   // Insert the block into the function... right after the block TI lives in.
190   Function &F = *TIBB->getParent();
191   Function::iterator FBBI = TIBB;
192   F.getBasicBlockList().insert(++FBBI, NewBB);
193   
194   // If there are any PHI nodes in DestBB, we need to update them so that they
195   // merge incoming values from NewBB instead of from TIBB.
196   if (PHINode *APHI = dyn_cast<PHINode>(DestBB->begin())) {
197     // This conceptually does:
198     //  foreach (PHINode *PN in DestBB)
199     //    PN->setIncomingBlock(PN->getIncomingBlock(TIBB), NewBB);
200     // but is optimized for two cases.
201     
202     if (APHI->getNumIncomingValues() <= 8) {  // Small # preds case.
203       unsigned BBIdx = 0;
204       for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
205         // We no longer enter through TIBB, now we come in through NewBB.
206         // Revector exactly one entry in the PHI node that used to come from
207         // TIBB to come from NewBB.
208         PHINode *PN = cast<PHINode>(I);
209         
210         // Reuse the previous value of BBIdx if it lines up.  In cases where we
211         // have multiple phi nodes with *lots* of predecessors, this is a speed
212         // win because we don't have to scan the PHI looking for TIBB.  This
213         // happens because the BB list of PHI nodes are usually in the same
214         // order.
215         if (PN->getIncomingBlock(BBIdx) != TIBB)
216           BBIdx = PN->getBasicBlockIndex(TIBB);
217         PN->setIncomingBlock(BBIdx, NewBB);
218       }
219     } else {
220       // However, the foreach loop is slow for blocks with lots of predecessors
221       // because PHINode::getIncomingBlock is O(n) in # preds.  Instead, walk
222       // the user list of TIBB to find the PHI nodes.
223       SmallPtrSet<PHINode*, 16> UpdatedPHIs;
224     
225       for (Value::use_iterator UI = TIBB->use_begin(), E = TIBB->use_end();
226            UI != E; ) {
227         Value::use_iterator Use = UI++;
228         if (PHINode *PN = dyn_cast<PHINode>(*Use)) {
229           // Remove one entry from each PHI.
230           if (PN->getParent() == DestBB && UpdatedPHIs.insert(PN))
231             PN->setOperand(Use.getOperandNo(), NewBB);
232         }
233       }
234     }
235   }
236    
237   // If there are any other edges from TIBB to DestBB, update those to go
238   // through the split block, making those edges non-critical as well (and
239   // reducing the number of phi entries in the DestBB if relevant).
240   if (MergeIdenticalEdges) {
241     for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
242       if (TI->getSuccessor(i) != DestBB) continue;
243       
244       // Remove an entry for TIBB from DestBB phi nodes.
245       DestBB->removePredecessor(TIBB);
246       
247       // We found another edge to DestBB, go to NewBB instead.
248       TI->setSuccessor(i, NewBB);
249     }
250   }
251   
252   
253
254   // If we don't have a pass object, we can't update anything...
255   if (P == 0) return NewBB;
256   
257   DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>();
258   LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>();
259   ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>();
260   
261   // If we have nothing to update, just return.
262   if (DT == 0 && LI == 0 && PI == 0)
263     return NewBB;
264
265   // Now update analysis information.  Since the only predecessor of NewBB is
266   // the TIBB, TIBB clearly dominates NewBB.  TIBB usually doesn't dominate
267   // anything, as there are other successors of DestBB.  However, if all other
268   // predecessors of DestBB are already dominated by DestBB (e.g. DestBB is a
269   // loop header) then NewBB dominates DestBB.
270   SmallVector<BasicBlock*, 8> OtherPreds;
271
272   // If there is a PHI in the block, loop over predecessors with it, which is
273   // faster than iterating pred_begin/end.
274   if (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
275     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
276       if (PN->getIncomingBlock(i) != NewBB)
277         OtherPreds.push_back(PN->getIncomingBlock(i));
278   } else {
279     for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB);
280          I != E; ++I) {
281       BasicBlock *P = *I;
282       if (P != NewBB)
283         OtherPreds.push_back(P);
284     }
285   }
286
287   bool NewBBDominatesDestBB = true;
288   
289   // Should we update DominatorTree information?
290   if (DT) {
291     DomTreeNode *TINode = DT->getNode(TIBB);
292
293     // The new block is not the immediate dominator for any other nodes, but
294     // TINode is the immediate dominator for the new node.
295     //
296     if (TINode) {       // Don't break unreachable code!
297       DomTreeNode *NewBBNode = DT->addNewBlock(NewBB, TIBB);
298       DomTreeNode *DestBBNode = 0;
299      
300       // If NewBBDominatesDestBB hasn't been computed yet, do so with DT.
301       if (!OtherPreds.empty()) {
302         DestBBNode = DT->getNode(DestBB);
303         while (!OtherPreds.empty() && NewBBDominatesDestBB) {
304           if (DomTreeNode *OPNode = DT->getNode(OtherPreds.back()))
305             NewBBDominatesDestBB = DT->dominates(DestBBNode, OPNode);
306           OtherPreds.pop_back();
307         }
308         OtherPreds.clear();
309       }
310       
311       // If NewBBDominatesDestBB, then NewBB dominates DestBB, otherwise it
312       // doesn't dominate anything.
313       if (NewBBDominatesDestBB) {
314         if (!DestBBNode) DestBBNode = DT->getNode(DestBB);
315         DT->changeImmediateDominator(DestBBNode, NewBBNode);
316       }
317     }
318   }
319
320   // Update LoopInfo if it is around.
321   if (LI) {
322     if (Loop *TIL = LI->getLoopFor(TIBB)) {
323       // If one or the other blocks were not in a loop, the new block is not
324       // either, and thus LI doesn't need to be updated.
325       if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
326         if (TIL == DestLoop) {
327           // Both in the same loop, the NewBB joins loop.
328           DestLoop->addBasicBlockToLoop(NewBB, LI->getBase());
329         } else if (TIL->contains(DestLoop)) {
330           // Edge from an outer loop to an inner loop.  Add to the outer loop.
331           TIL->addBasicBlockToLoop(NewBB, LI->getBase());
332         } else if (DestLoop->contains(TIL)) {
333           // Edge from an inner loop to an outer loop.  Add to the outer loop.
334           DestLoop->addBasicBlockToLoop(NewBB, LI->getBase());
335         } else {
336           // Edge from two loops with no containment relation.  Because these
337           // are natural loops, we know that the destination block must be the
338           // header of its loop (adding a branch into a loop elsewhere would
339           // create an irreducible loop).
340           assert(DestLoop->getHeader() == DestBB &&
341                  "Should not create irreducible loops!");
342           if (Loop *P = DestLoop->getParentLoop())
343             P->addBasicBlockToLoop(NewBB, LI->getBase());
344         }
345       }
346       // If TIBB is in a loop and DestBB is outside of that loop, split the
347       // other exit blocks of the loop that also have predecessors outside
348       // the loop, to maintain a LoopSimplify guarantee.
349       if (!TIL->contains(DestBB) &&
350           P->mustPreserveAnalysisID(LoopSimplifyID)) {
351         assert(!TIL->contains(NewBB) &&
352                "Split point for loop exit is contained in loop!");
353
354         // Update LCSSA form in the newly created exit block.
355         if (P->mustPreserveAnalysisID(LCSSAID)) {
356           SmallVector<BasicBlock *, 1> OrigPred;
357           OrigPred.push_back(TIBB);
358           CreatePHIsForSplitLoopExit(OrigPred, NewBB, DestBB);
359         }
360
361         // For each unique exit block...
362         SmallVector<BasicBlock *, 4> ExitBlocks;
363         TIL->getExitBlocks(ExitBlocks);
364         for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
365           // Collect all the preds that are inside the loop, and note
366           // whether there are any preds outside the loop.
367           SmallVector<BasicBlock *, 4> Preds;
368           bool HasPredOutsideOfLoop = false;
369           BasicBlock *Exit = ExitBlocks[i];
370           for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit);
371                I != E; ++I) {
372             BasicBlock *P = *I;
373             if (TIL->contains(P))
374               Preds.push_back(P);
375             else
376               HasPredOutsideOfLoop = true;
377           }
378           // If there are any preds not in the loop, we'll need to split
379           // the edges. The Preds.empty() check is needed because a block
380           // may appear multiple times in the list. We can't use
381           // getUniqueExitBlocks above because that depends on LoopSimplify
382           // form, which we're in the process of restoring!
383           if (!Preds.empty() && HasPredOutsideOfLoop) {
384             BasicBlock *NewExitBB =
385               SplitBlockPredecessors(Exit, Preds.data(), Preds.size(),
386                                      "split", P);
387             if (P->mustPreserveAnalysisID(LCSSAID))
388               CreatePHIsForSplitLoopExit(Preds, NewExitBB, Exit);
389           }
390         }
391       }
392       // LCSSA form was updated above for the case where LoopSimplify is
393       // available, which means that all predecessors of loop exit blocks
394       // are within the loop. Without LoopSimplify form, it would be
395       // necessary to insert a new phi.
396       assert((!P->mustPreserveAnalysisID(LCSSAID) ||
397               P->mustPreserveAnalysisID(LoopSimplifyID)) &&
398              "SplitCriticalEdge doesn't know how to update LCCSA form "
399              "without LoopSimplify!");
400     }
401   }
402
403   // Update ProfileInfo if it is around.
404   if (PI)
405     PI->splitEdge(TIBB, DestBB, NewBB, MergeIdenticalEdges);
406
407   return NewBB;
408 }