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