1 //===- BreakCriticalEdges.cpp - Critical Edge Elimination Pass ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // BreakCriticalEdges pass - Break all of the critical edges in the CFG by
10 // inserting a dummy basic block.  This pass may be "required" by passes that
11 // cannot deal with critical edges.  For this usage, the structure type is
12 // forward declared.  This pass obviously invalidates the CFG, but can update
13 // dominator trees.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/Transforms/Utils/BreakCriticalEdges.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/BlockFrequencyInfo.h"
22 #include "llvm/Analysis/BranchProbabilityInfo.h"
23 #include "llvm/Analysis/CFG.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Analysis/MemorySSAUpdater.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/Utils.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 (PHINode &PN : DestBB->phis()) {
110     unsigned Idx = PN.getBasicBlockIndex(SplitBB);
111     Value *V = PN.getIncomingValue(Idx);
112 
113     // If the input is a PHI which already satisfies LCSSA, don't create
114     // a new one.
115     if (const PHINode *VP = dyn_cast<PHINode>(V))
116       if (VP->getParent() == SplitBB)
117         continue;
118 
119     // Otherwise a new PHI is needed. Create one and populate it.
120     PHINode *NewPN = PHINode::Create(
121         PN.getType(), Preds.size(), "split",
122         SplitBB->isLandingPad() ? &SplitBB->front() : SplitBB->getTerminator());
123     for (unsigned i = 0, e = Preds.size(); i != e; ++i)
124       NewPN->addIncoming(V, Preds[i]);
125 
126     // Update the original PHI.
127     PN.setIncomingValue(Idx, NewPN);
128   }
129 }
130 
131 BasicBlock *
132 llvm::SplitCriticalEdge(Instruction *TI, unsigned SuccNum,
133                         const CriticalEdgeSplittingOptions &Options) {
134   if (!isCriticalEdge(TI, SuccNum, Options.MergeIdenticalEdges))
135     return nullptr;
136 
137   assert(!isa<IndirectBrInst>(TI) &&
138          "Cannot split critical edge from IndirectBrInst");
139 
140   BasicBlock *TIBB = TI->getParent();
141   BasicBlock *DestBB = TI->getSuccessor(SuccNum);
142 
143   // Splitting the critical edge to a pad block is non-trivial. Don't do
144   // it in this generic function.
145   if (DestBB->isEHPad()) return nullptr;
146 
147   // Create a new basic block, linking it into the CFG.
148   BasicBlock *NewBB = BasicBlock::Create(TI->getContext(),
149                       TIBB->getName() + "." + DestBB->getName() + "_crit_edge");
150   // Create our unconditional branch.
151   BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
152   NewBI->setDebugLoc(TI->getDebugLoc());
153 
154   // Branch to the new block, breaking the edge.
155   TI->setSuccessor(SuccNum, NewBB);
156 
157   // Insert the block into the function... right after the block TI lives in.
158   Function &F = *TIBB->getParent();
159   Function::iterator FBBI = TIBB->getIterator();
160   F.getBasicBlockList().insert(++FBBI, NewBB);
161 
162   // If there are any PHI nodes in DestBB, we need to update them so that they
163   // merge incoming values from NewBB instead of from TIBB.
164   {
165     unsigned BBIdx = 0;
166     for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
167       // We no longer enter through TIBB, now we come in through NewBB.
168       // Revector exactly one entry in the PHI node that used to come from
169       // TIBB to come from NewBB.
170       PHINode *PN = cast<PHINode>(I);
171 
172       // Reuse the previous value of BBIdx if it lines up.  In cases where we
173       // have multiple phi nodes with *lots* of predecessors, this is a speed
174       // win because we don't have to scan the PHI looking for TIBB.  This
175       // happens because the BB list of PHI nodes are usually in the same
176       // order.
177       if (PN->getIncomingBlock(BBIdx) != TIBB)
178         BBIdx = PN->getBasicBlockIndex(TIBB);
179       PN->setIncomingBlock(BBIdx, NewBB);
180     }
181   }
182 
183   // If there are any other edges from TIBB to DestBB, update those to go
184   // through the split block, making those edges non-critical as well (and
185   // reducing the number of phi entries in the DestBB if relevant).
186   if (Options.MergeIdenticalEdges) {
187     for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
188       if (TI->getSuccessor(i) != DestBB) continue;
189 
190       // Remove an entry for TIBB from DestBB phi nodes.
191       DestBB->removePredecessor(TIBB, Options.DontDeleteUselessPHIs);
192 
193       // We found another edge to DestBB, go to NewBB instead.
194       TI->setSuccessor(i, NewBB);
195     }
196   }
197 
198   // If we have nothing to update, just return.
199   auto *DT = Options.DT;
200   auto *LI = Options.LI;
201   auto *MSSAU = Options.MSSAU;
202   if (MSSAU)
203     MSSAU->wireOldPredecessorsToNewImmediatePredecessor(
204         DestBB, NewBB, {TIBB}, Options.MergeIdenticalEdges);
205 
206   if (!DT && !LI)
207     return NewBB;
208 
209   if (DT) {
210     // Update the DominatorTree.
211     //       ---> NewBB -----\
212     //      /                 V
213     //  TIBB -------\\------> DestBB
214     //
215     // First, inform the DT about the new path from TIBB to DestBB via NewBB,
216     // then delete the old edge from TIBB to DestBB. By doing this in that order
217     // DestBB stays reachable in the DT the whole time and its subtree doesn't
218     // get disconnected.
219     SmallVector<DominatorTree::UpdateType, 3> Updates;
220     Updates.push_back({DominatorTree::Insert, TIBB, NewBB});
221     Updates.push_back({DominatorTree::Insert, NewBB, DestBB});
222     if (llvm::find(successors(TIBB), DestBB) == succ_end(TIBB))
223       Updates.push_back({DominatorTree::Delete, TIBB, DestBB});
224 
225     DT->applyUpdates(Updates);
226   }
227 
228   // Update LoopInfo if it is around.
229   if (LI) {
230     if (Loop *TIL = LI->getLoopFor(TIBB)) {
231       // If one or the other blocks were not in a loop, the new block is not
232       // either, and thus LI doesn't need to be updated.
233       if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
234         if (TIL == DestLoop) {
235           // Both in the same loop, the NewBB joins loop.
236           DestLoop->addBasicBlockToLoop(NewBB, *LI);
237         } else if (TIL->contains(DestLoop)) {
238           // Edge from an outer loop to an inner loop.  Add to the outer loop.
239           TIL->addBasicBlockToLoop(NewBB, *LI);
240         } else if (DestLoop->contains(TIL)) {
241           // Edge from an inner loop to an outer loop.  Add to the outer loop.
242           DestLoop->addBasicBlockToLoop(NewBB, *LI);
243         } else {
244           // Edge from two loops with no containment relation.  Because these
245           // are natural loops, we know that the destination block must be the
246           // header of its loop (adding a branch into a loop elsewhere would
247           // create an irreducible loop).
248           assert(DestLoop->getHeader() == DestBB &&
249                  "Should not create irreducible loops!");
250           if (Loop *P = DestLoop->getParentLoop())
251             P->addBasicBlockToLoop(NewBB, *LI);
252         }
253       }
254 
255       // If TIBB is in a loop and DestBB is outside of that loop, we may need
256       // to update LoopSimplify form and LCSSA form.
257       if (!TIL->contains(DestBB)) {
258         assert(!TIL->contains(NewBB) &&
259                "Split point for loop exit is contained in loop!");
260 
261         // Update LCSSA form in the newly created exit block.
262         if (Options.PreserveLCSSA) {
263           createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
264         }
265 
266         // The only that we can break LoopSimplify form by splitting a critical
267         // edge is if after the split there exists some edge from TIL to DestBB
268         // *and* the only edge into DestBB from outside of TIL is that of
269         // NewBB. If the first isn't true, then LoopSimplify still holds, NewBB
270         // is the new exit block and it has no non-loop predecessors. If the
271         // second isn't true, then DestBB was not in LoopSimplify form prior to
272         // the split as it had a non-loop predecessor. In both of these cases,
273         // the predecessor must be directly in TIL, not in a subloop, or again
274         // LoopSimplify doesn't hold.
275         SmallVector<BasicBlock *, 4> LoopPreds;
276         for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); I != E;
277              ++I) {
278           BasicBlock *P = *I;
279           if (P == NewBB)
280             continue; // The new block is known.
281           if (LI->getLoopFor(P) != TIL) {
282             // No need to re-simplify, it wasn't to start with.
283             LoopPreds.clear();
284             break;
285           }
286           LoopPreds.push_back(P);
287         }
288         if (!LoopPreds.empty()) {
289           assert(!DestBB->isEHPad() && "We don't split edges to EH pads!");
290           BasicBlock *NewExitBB = SplitBlockPredecessors(
291               DestBB, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
292           if (Options.PreserveLCSSA)
293             createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);
294         }
295       }
296     }
297   }
298 
299   return NewBB;
300 }
301 
302 // Return the unique indirectbr predecessor of a block. This may return null
303 // even if such a predecessor exists, if it's not useful for splitting.
304 // If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
305 // predecessors of BB.
306 static BasicBlock *
307 findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
308   // If the block doesn't have any PHIs, we don't care about it, since there's
309   // no point in splitting it.
310   PHINode *PN = dyn_cast<PHINode>(BB->begin());
311   if (!PN)
312     return nullptr;
313 
314   // Verify we have exactly one IBR predecessor.
315   // Conservatively bail out if one of the other predecessors is not a "regular"
316   // terminator (that is, not a switch or a br).
317   BasicBlock *IBB = nullptr;
318   for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
319     BasicBlock *PredBB = PN->getIncomingBlock(Pred);
320     Instruction *PredTerm = PredBB->getTerminator();
321     switch (PredTerm->getOpcode()) {
322     case Instruction::IndirectBr:
323       if (IBB)
324         return nullptr;
325       IBB = PredBB;
326       break;
327     case Instruction::Br:
328     case Instruction::Switch:
329       OtherPreds.push_back(PredBB);
330       continue;
331     default:
332       return nullptr;
333     }
334   }
335 
336   return IBB;
337 }
338 
339 bool llvm::SplitIndirectBrCriticalEdges(Function &F,
340                                         BranchProbabilityInfo *BPI,
341                                         BlockFrequencyInfo *BFI) {
342   // Check whether the function has any indirectbrs, and collect which blocks
343   // they may jump to. Since most functions don't have indirect branches,
344   // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
345   SmallSetVector<BasicBlock *, 16> Targets;
346   for (auto &BB : F) {
347     auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
348     if (!IBI)
349       continue;
350 
351     for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
352       Targets.insert(IBI->getSuccessor(Succ));
353   }
354 
355   if (Targets.empty())
356     return false;
357 
358   bool ShouldUpdateAnalysis = BPI && BFI;
359   bool Changed = false;
360   for (BasicBlock *Target : Targets) {
361     SmallVector<BasicBlock *, 16> OtherPreds;
362     BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
363     // If we did not found an indirectbr, or the indirectbr is the only
364     // incoming edge, this isn't the kind of edge we're looking for.
365     if (!IBRPred || OtherPreds.empty())
366       continue;
367 
368     // Don't even think about ehpads/landingpads.
369     Instruction *FirstNonPHI = Target->getFirstNonPHI();
370     if (FirstNonPHI->isEHPad() || Target->isLandingPad())
371       continue;
372 
373     BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
374     if (ShouldUpdateAnalysis) {
375       // Copy the BFI/BPI from Target to BodyBlock.
376       for (unsigned I = 0, E = BodyBlock->getTerminator()->getNumSuccessors();
377            I < E; ++I)
378         BPI->setEdgeProbability(BodyBlock, I,
379                                 BPI->getEdgeProbability(Target, I));
380       BFI->setBlockFreq(BodyBlock, BFI->getBlockFreq(Target).getFrequency());
381     }
382     // It's possible Target was its own successor through an indirectbr.
383     // In this case, the indirectbr now comes from BodyBlock.
384     if (IBRPred == Target)
385       IBRPred = BodyBlock;
386 
387     // At this point Target only has PHIs, and BodyBlock has the rest of the
388     // block's body. Create a copy of Target that will be used by the "direct"
389     // preds.
390     ValueToValueMapTy VMap;
391     BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
392 
393     BlockFrequency BlockFreqForDirectSucc;
394     for (BasicBlock *Pred : OtherPreds) {
395       // If the target is a loop to itself, then the terminator of the split
396       // block (BodyBlock) needs to be updated.
397       BasicBlock *Src = Pred != Target ? Pred : BodyBlock;
398       Src->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
399       if (ShouldUpdateAnalysis)
400         BlockFreqForDirectSucc += BFI->getBlockFreq(Src) *
401             BPI->getEdgeProbability(Src, DirectSucc);
402     }
403     if (ShouldUpdateAnalysis) {
404       BFI->setBlockFreq(DirectSucc, BlockFreqForDirectSucc.getFrequency());
405       BlockFrequency NewBlockFreqForTarget =
406           BFI->getBlockFreq(Target) - BlockFreqForDirectSucc;
407       BFI->setBlockFreq(Target, NewBlockFreqForTarget.getFrequency());
408       BPI->eraseBlock(Target);
409     }
410 
411     // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
412     // they are clones, so the number of PHIs are the same.
413     // (a) Remove the edge coming from IBRPred from the "Direct" PHI
414     // (b) Leave that as the only edge in the "Indirect" PHI.
415     // (c) Merge the two in the body block.
416     BasicBlock::iterator Indirect = Target->begin(),
417                          End = Target->getFirstNonPHI()->getIterator();
418     BasicBlock::iterator Direct = DirectSucc->begin();
419     BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
420 
421     assert(&*End == Target->getTerminator() &&
422            "Block was expected to only contain PHIs");
423 
424     while (Indirect != End) {
425       PHINode *DirPHI = cast<PHINode>(Direct);
426       PHINode *IndPHI = cast<PHINode>(Indirect);
427 
428       // Now, clean up - the direct block shouldn't get the indirect value,
429       // and vice versa.
430       DirPHI->removeIncomingValue(IBRPred);
431       Direct++;
432 
433       // Advance the pointer here, to avoid invalidation issues when the old
434       // PHI is erased.
435       Indirect++;
436 
437       PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
438       NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
439                              IBRPred);
440 
441       // Create a PHI in the body block, to merge the direct and indirect
442       // predecessors.
443       PHINode *MergePHI =
444           PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
445       MergePHI->addIncoming(NewIndPHI, Target);
446       MergePHI->addIncoming(DirPHI, DirectSucc);
447 
448       IndPHI->replaceAllUsesWith(MergePHI);
449       IndPHI->eraseFromParent();
450     }
451 
452     Changed = true;
453   }
454 
455   return Changed;
456 }
457