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