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