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