Revert r240137 (Fixed/added namespace ending comments using clang-tidy. NFC)
[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 *AA = Options.AA;
201   auto *DT = Options.DT;
202   auto *LI = Options.LI;
203   if (!DT && !LI)
204     return NewBB;
205
206   // Now update analysis information.  Since the only predecessor of NewBB is
207   // the TIBB, TIBB clearly dominates NewBB.  TIBB usually doesn't dominate
208   // anything, as there are other successors of DestBB.  However, if all other
209   // predecessors of DestBB are already dominated by DestBB (e.g. DestBB is a
210   // loop header) then NewBB dominates DestBB.
211   SmallVector<BasicBlock*, 8> OtherPreds;
212
213   // If there is a PHI in the block, loop over predecessors with it, which is
214   // faster than iterating pred_begin/end.
215   if (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
216     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
217       if (PN->getIncomingBlock(i) != NewBB)
218         OtherPreds.push_back(PN->getIncomingBlock(i));
219   } else {
220     for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB);
221          I != E; ++I) {
222       BasicBlock *P = *I;
223       if (P != NewBB)
224         OtherPreds.push_back(P);
225     }
226   }
227
228   bool NewBBDominatesDestBB = true;
229
230   // Should we update DominatorTree information?
231   if (DT) {
232     DomTreeNode *TINode = DT->getNode(TIBB);
233
234     // The new block is not the immediate dominator for any other nodes, but
235     // TINode is the immediate dominator for the new node.
236     //
237     if (TINode) {       // Don't break unreachable code!
238       DomTreeNode *NewBBNode = DT->addNewBlock(NewBB, TIBB);
239       DomTreeNode *DestBBNode = nullptr;
240
241       // If NewBBDominatesDestBB hasn't been computed yet, do so with DT.
242       if (!OtherPreds.empty()) {
243         DestBBNode = DT->getNode(DestBB);
244         while (!OtherPreds.empty() && NewBBDominatesDestBB) {
245           if (DomTreeNode *OPNode = DT->getNode(OtherPreds.back()))
246             NewBBDominatesDestBB = DT->dominates(DestBBNode, OPNode);
247           OtherPreds.pop_back();
248         }
249         OtherPreds.clear();
250       }
251
252       // If NewBBDominatesDestBB, then NewBB dominates DestBB, otherwise it
253       // doesn't dominate anything.
254       if (NewBBDominatesDestBB) {
255         if (!DestBBNode) DestBBNode = DT->getNode(DestBB);
256         DT->changeImmediateDominator(DestBBNode, NewBBNode);
257       }
258     }
259   }
260
261   // Update LoopInfo if it is around.
262   if (LI) {
263     if (Loop *TIL = LI->getLoopFor(TIBB)) {
264       // If one or the other blocks were not in a loop, the new block is not
265       // either, and thus LI doesn't need to be updated.
266       if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
267         if (TIL == DestLoop) {
268           // Both in the same loop, the NewBB joins loop.
269           DestLoop->addBasicBlockToLoop(NewBB, *LI);
270         } else if (TIL->contains(DestLoop)) {
271           // Edge from an outer loop to an inner loop.  Add to the outer loop.
272           TIL->addBasicBlockToLoop(NewBB, *LI);
273         } else if (DestLoop->contains(TIL)) {
274           // Edge from an inner loop to an outer loop.  Add to the outer loop.
275           DestLoop->addBasicBlockToLoop(NewBB, *LI);
276         } else {
277           // Edge from two loops with no containment relation.  Because these
278           // are natural loops, we know that the destination block must be the
279           // header of its loop (adding a branch into a loop elsewhere would
280           // create an irreducible loop).
281           assert(DestLoop->getHeader() == DestBB &&
282                  "Should not create irreducible loops!");
283           if (Loop *P = DestLoop->getParentLoop())
284             P->addBasicBlockToLoop(NewBB, *LI);
285         }
286       }
287
288       // If TIBB is in a loop and DestBB is outside of that loop, we may need
289       // to update LoopSimplify form and LCSSA form.
290       if (!TIL->contains(DestBB)) {
291         assert(!TIL->contains(NewBB) &&
292                "Split point for loop exit is contained in loop!");
293
294         // Update LCSSA form in the newly created exit block.
295         if (Options.PreserveLCSSA) {
296           createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
297         }
298
299         // The only that we can break LoopSimplify form by splitting a critical
300         // edge is if after the split there exists some edge from TIL to DestBB
301         // *and* the only edge into DestBB from outside of TIL is that of
302         // NewBB. If the first isn't true, then LoopSimplify still holds, NewBB
303         // is the new exit block and it has no non-loop predecessors. If the
304         // second isn't true, then DestBB was not in LoopSimplify form prior to
305         // the split as it had a non-loop predecessor. In both of these cases,
306         // the predecessor must be directly in TIL, not in a subloop, or again
307         // LoopSimplify doesn't hold.
308         SmallVector<BasicBlock *, 4> LoopPreds;
309         for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); I != E;
310              ++I) {
311           BasicBlock *P = *I;
312           if (P == NewBB)
313             continue; // The new block is known.
314           if (LI->getLoopFor(P) != TIL) {
315             // No need to re-simplify, it wasn't to start with.
316             LoopPreds.clear();
317             break;
318           }
319           LoopPreds.push_back(P);
320         }
321         if (!LoopPreds.empty()) {
322           assert(!DestBB->isLandingPad() &&
323                  "We don't split edges to landing pads!");
324           BasicBlock *NewExitBB = SplitBlockPredecessors(
325               DestBB, LoopPreds, "split", AA, DT, LI, Options.PreserveLCSSA);
326           if (Options.PreserveLCSSA)
327             createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);
328         }
329       }
330     }
331   }
332
333   return NewBB;
334 }