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/Utils/BreakCriticalEdges.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/BlockFrequencyInfo.h"
23 #include "llvm/Analysis/BranchProbabilityInfo.h"
24 #include "llvm/Analysis/CFG.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/IR/CFG.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Type.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Transforms/Scalar.h"
32 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
33 #include "llvm/Transforms/Utils/Cloning.h"
34 #include "llvm/Transforms/Utils/ValueMapper.h"
35 using namespace llvm;
36 
37 #define DEBUG_TYPE "break-crit-edges"
38 
39 STATISTIC(NumBroken, "Number of blocks inserted");
40 
41 namespace {
42   struct BreakCriticalEdges : public FunctionPass {
43     static char ID; // Pass identification, replacement for typeid
44     BreakCriticalEdges() : FunctionPass(ID) {
45       initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry());
46     }
47 
48     bool runOnFunction(Function &F) override {
49       auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
50       auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
51       auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
52       auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
53       unsigned N =
54           SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI));
55       NumBroken += N;
56       return N > 0;
57     }
58 
59     void getAnalysisUsage(AnalysisUsage &AU) const override {
60       AU.addPreserved<DominatorTreeWrapperPass>();
61       AU.addPreserved<LoopInfoWrapperPass>();
62 
63       // No loop canonicalization guarantees are broken by this pass.
64       AU.addPreservedID(LoopSimplifyID);
65     }
66   };
67 }
68 
69 char BreakCriticalEdges::ID = 0;
70 INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges",
71                 "Break critical edges in CFG", false, false)
72 
73 // Publicly exposed interface to pass...
74 char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID;
75 FunctionPass *llvm::createBreakCriticalEdgesPass() {
76   return new BreakCriticalEdges();
77 }
78 
79 PreservedAnalyses BreakCriticalEdgesPass::run(Function &F,
80                                               FunctionAnalysisManager &AM) {
81   auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(F);
82   auto *LI = AM.getCachedResult<LoopAnalysis>(F);
83   unsigned N = SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI));
84   NumBroken += N;
85   if (N == 0)
86     return PreservedAnalyses::all();
87   PreservedAnalyses PA;
88   PA.preserve<DominatorTreeAnalysis>();
89   PA.preserve<LoopAnalysis>();
90   return PA;
91 }
92 
93 //===----------------------------------------------------------------------===//
94 //    Implementation of the external critical edge manipulation functions
95 //===----------------------------------------------------------------------===//
96 
97 /// When a loop exit edge is split, LCSSA form may require new PHIs in the new
98 /// exit block. This function inserts the new PHIs, as needed. Preds is a list
99 /// of preds inside the loop, SplitBB is the new loop exit block, and DestBB is
100 /// the old loop exit, now the successor of SplitBB.
101 static void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
102                                        BasicBlock *SplitBB,
103                                        BasicBlock *DestBB) {
104   // SplitBB shouldn't have anything non-trivial in it yet.
105   assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
106           SplitBB->isLandingPad()) && "SplitBB has non-PHI nodes!");
107 
108   // For each PHI in the destination block.
109   for (BasicBlock::iterator I = DestBB->begin();
110        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
111     unsigned Idx = PN->getBasicBlockIndex(SplitBB);
112     Value *V = PN->getIncomingValue(Idx);
113 
114     // If the input is a PHI which already satisfies LCSSA, don't create
115     // a new one.
116     if (const PHINode *VP = dyn_cast<PHINode>(V))
117       if (VP->getParent() == SplitBB)
118         continue;
119 
120     // Otherwise a new PHI is needed. Create one and populate it.
121     PHINode *NewPN = PHINode::Create(
122         PN->getType(), Preds.size(), "split",
123         SplitBB->isLandingPad() ? &SplitBB->front() : SplitBB->getTerminator());
124     for (unsigned i = 0, e = Preds.size(); i != e; ++i)
125       NewPN->addIncoming(V, Preds[i]);
126 
127     // Update the original PHI.
128     PN->setIncomingValue(Idx, NewPN);
129   }
130 }
131 
132 BasicBlock *
133 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 pad block is non-trivial. Don't do
145   // it in this generic function.
146   if (DestBB->isEHPad()) 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->getIterator();
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   if (DT) {
206     // Update the DominatorTree.
207     //       ---> NewBB -----\
208     //      /                 V
209     //  TIBB -------\\------> DestBB
210     //
211     // First, inform the DT about the new path from TIBB to DestBB via NewBB,
212     // then delete the old edge from TIBB to DestBB. By doing this in that order
213     // DestBB stays reachable in the DT the whole time and its subtree doesn't
214     // get disconnected.
215     SmallVector<DominatorTree::UpdateType, 3> Updates;
216     Updates.push_back({DominatorTree::Insert, TIBB, NewBB});
217     Updates.push_back({DominatorTree::Insert, NewBB, DestBB});
218     if (llvm::find(successors(TIBB), DestBB) == succ_end(TIBB))
219       Updates.push_back({DominatorTree::Delete, TIBB, DestBB});
220 
221     DT->applyUpdates(Updates);
222   }
223 
224   // Update LoopInfo if it is around.
225   if (LI) {
226     if (Loop *TIL = LI->getLoopFor(TIBB)) {
227       // If one or the other blocks were not in a loop, the new block is not
228       // either, and thus LI doesn't need to be updated.
229       if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
230         if (TIL == DestLoop) {
231           // Both in the same loop, the NewBB joins loop.
232           DestLoop->addBasicBlockToLoop(NewBB, *LI);
233         } else if (TIL->contains(DestLoop)) {
234           // Edge from an outer loop to an inner loop.  Add to the outer loop.
235           TIL->addBasicBlockToLoop(NewBB, *LI);
236         } else if (DestLoop->contains(TIL)) {
237           // Edge from an inner loop to an outer loop.  Add to the outer loop.
238           DestLoop->addBasicBlockToLoop(NewBB, *LI);
239         } else {
240           // Edge from two loops with no containment relation.  Because these
241           // are natural loops, we know that the destination block must be the
242           // header of its loop (adding a branch into a loop elsewhere would
243           // create an irreducible loop).
244           assert(DestLoop->getHeader() == DestBB &&
245                  "Should not create irreducible loops!");
246           if (Loop *P = DestLoop->getParentLoop())
247             P->addBasicBlockToLoop(NewBB, *LI);
248         }
249       }
250 
251       // If TIBB is in a loop and DestBB is outside of that loop, we may need
252       // to update LoopSimplify form and LCSSA form.
253       if (!TIL->contains(DestBB)) {
254         assert(!TIL->contains(NewBB) &&
255                "Split point for loop exit is contained in loop!");
256 
257         // Update LCSSA form in the newly created exit block.
258         if (Options.PreserveLCSSA) {
259           createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
260         }
261 
262         // The only that we can break LoopSimplify form by splitting a critical
263         // edge is if after the split there exists some edge from TIL to DestBB
264         // *and* the only edge into DestBB from outside of TIL is that of
265         // NewBB. If the first isn't true, then LoopSimplify still holds, NewBB
266         // is the new exit block and it has no non-loop predecessors. If the
267         // second isn't true, then DestBB was not in LoopSimplify form prior to
268         // the split as it had a non-loop predecessor. In both of these cases,
269         // the predecessor must be directly in TIL, not in a subloop, or again
270         // LoopSimplify doesn't hold.
271         SmallVector<BasicBlock *, 4> LoopPreds;
272         for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); I != E;
273              ++I) {
274           BasicBlock *P = *I;
275           if (P == NewBB)
276             continue; // The new block is known.
277           if (LI->getLoopFor(P) != TIL) {
278             // No need to re-simplify, it wasn't to start with.
279             LoopPreds.clear();
280             break;
281           }
282           LoopPreds.push_back(P);
283         }
284         if (!LoopPreds.empty()) {
285           assert(!DestBB->isEHPad() && "We don't split edges to EH pads!");
286           BasicBlock *NewExitBB = SplitBlockPredecessors(
287               DestBB, LoopPreds, "split", DT, LI, Options.PreserveLCSSA);
288           if (Options.PreserveLCSSA)
289             createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);
290         }
291       }
292     }
293   }
294 
295   return NewBB;
296 }
297 
298 // Return the unique indirectbr predecessor of a block. This may return null
299 // even if such a predecessor exists, if it's not useful for splitting.
300 // If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
301 // predecessors of BB.
302 static BasicBlock *
303 findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
304   // If the block doesn't have any PHIs, we don't care about it, since there's
305   // no point in splitting it.
306   PHINode *PN = dyn_cast<PHINode>(BB->begin());
307   if (!PN)
308     return nullptr;
309 
310   // Verify we have exactly one IBR predecessor.
311   // Conservatively bail out if one of the other predecessors is not a "regular"
312   // terminator (that is, not a switch or a br).
313   BasicBlock *IBB = nullptr;
314   for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
315     BasicBlock *PredBB = PN->getIncomingBlock(Pred);
316     TerminatorInst *PredTerm = PredBB->getTerminator();
317     switch (PredTerm->getOpcode()) {
318     case Instruction::IndirectBr:
319       if (IBB)
320         return nullptr;
321       IBB = PredBB;
322       break;
323     case Instruction::Br:
324     case Instruction::Switch:
325       OtherPreds.push_back(PredBB);
326       continue;
327     default:
328       return nullptr;
329     }
330   }
331 
332   return IBB;
333 }
334 
335 bool llvm::SplitIndirectBrCriticalEdges(Function &F,
336                                         BranchProbabilityInfo *BPI,
337                                         BlockFrequencyInfo *BFI) {
338   // Check whether the function has any indirectbrs, and collect which blocks
339   // they may jump to. Since most functions don't have indirect branches,
340   // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
341   SmallSetVector<BasicBlock *, 16> Targets;
342   for (auto &BB : F) {
343     auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
344     if (!IBI)
345       continue;
346 
347     for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
348       Targets.insert(IBI->getSuccessor(Succ));
349   }
350 
351   if (Targets.empty())
352     return false;
353 
354   bool ShouldUpdateAnalysis = BPI && BFI;
355   bool Changed = false;
356   for (BasicBlock *Target : Targets) {
357     SmallVector<BasicBlock *, 16> OtherPreds;
358     BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
359     // If we did not found an indirectbr, or the indirectbr is the only
360     // incoming edge, this isn't the kind of edge we're looking for.
361     if (!IBRPred || OtherPreds.empty())
362       continue;
363 
364     // Don't even think about ehpads/landingpads.
365     Instruction *FirstNonPHI = Target->getFirstNonPHI();
366     if (FirstNonPHI->isEHPad() || Target->isLandingPad())
367       continue;
368 
369     BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
370     if (ShouldUpdateAnalysis) {
371       // Copy the BFI/BPI from Target to BodyBlock.
372       for (unsigned I = 0, E = BodyBlock->getTerminator()->getNumSuccessors();
373            I < E; ++I)
374         BPI->setEdgeProbability(BodyBlock, I,
375                                 BPI->getEdgeProbability(Target, I));
376       BFI->setBlockFreq(BodyBlock, BFI->getBlockFreq(Target).getFrequency());
377     }
378     // It's possible Target was its own successor through an indirectbr.
379     // In this case, the indirectbr now comes from BodyBlock.
380     if (IBRPred == Target)
381       IBRPred = BodyBlock;
382 
383     // At this point Target only has PHIs, and BodyBlock has the rest of the
384     // block's body. Create a copy of Target that will be used by the "direct"
385     // preds.
386     ValueToValueMapTy VMap;
387     BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
388 
389     BlockFrequency BlockFreqForDirectSucc;
390     for (BasicBlock *Pred : OtherPreds) {
391       // If the target is a loop to itself, then the terminator of the split
392       // block (BodyBlock) needs to be updated.
393       BasicBlock *Src = Pred != Target ? Pred : BodyBlock;
394       Src->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
395       if (ShouldUpdateAnalysis)
396         BlockFreqForDirectSucc += BFI->getBlockFreq(Src) *
397             BPI->getEdgeProbability(Src, DirectSucc);
398     }
399     if (ShouldUpdateAnalysis) {
400       BFI->setBlockFreq(DirectSucc, BlockFreqForDirectSucc.getFrequency());
401       BlockFrequency NewBlockFreqForTarget =
402           BFI->getBlockFreq(Target) - BlockFreqForDirectSucc;
403       BFI->setBlockFreq(Target, NewBlockFreqForTarget.getFrequency());
404       BPI->eraseBlock(Target);
405     }
406 
407     // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
408     // they are clones, so the number of PHIs are the same.
409     // (a) Remove the edge coming from IBRPred from the "Direct" PHI
410     // (b) Leave that as the only edge in the "Indirect" PHI.
411     // (c) Merge the two in the body block.
412     BasicBlock::iterator Indirect = Target->begin(),
413                          End = Target->getFirstNonPHI()->getIterator();
414     BasicBlock::iterator Direct = DirectSucc->begin();
415     BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
416 
417     assert(&*End == Target->getTerminator() &&
418            "Block was expected to only contain PHIs");
419 
420     while (Indirect != End) {
421       PHINode *DirPHI = cast<PHINode>(Direct);
422       PHINode *IndPHI = cast<PHINode>(Indirect);
423 
424       // Now, clean up - the direct block shouldn't get the indirect value,
425       // and vice versa.
426       DirPHI->removeIncomingValue(IBRPred);
427       Direct++;
428 
429       // Advance the pointer here, to avoid invalidation issues when the old
430       // PHI is erased.
431       Indirect++;
432 
433       PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
434       NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
435                              IBRPred);
436 
437       // Create a PHI in the body block, to merge the direct and indirect
438       // predecessors.
439       PHINode *MergePHI =
440           PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
441       MergePHI->addIncoming(NewIndPHI, Target);
442       MergePHI->addIncoming(DirPHI, DirectSucc);
443 
444       IndPHI->replaceAllUsesWith(MergePHI);
445       IndPHI->eraseFromParent();
446     }
447 
448     Changed = true;
449   }
450 
451   return Changed;
452 }
453