]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/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/Analysis/MemorySSAUpdater.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/Utils.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 (PHINode &PN : DestBB->phis()) {
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(Instruction *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   auto *MSSAU = Options.MSSAU;
203   if (MSSAU)
204     MSSAU->wireOldPredecessorsToNewImmediatePredecessor(
205         DestBB, NewBB, {TIBB}, Options.MergeIdenticalEdges);
206
207   if (!DT && !LI)
208     return NewBB;
209
210   if (DT) {
211     // Update the DominatorTree.
212     //       ---> NewBB -----\
213     //      /                 V
214     //  TIBB -------\\------> DestBB
215     //
216     // First, inform the DT about the new path from TIBB to DestBB via NewBB,
217     // then delete the old edge from TIBB to DestBB. By doing this in that order
218     // DestBB stays reachable in the DT the whole time and its subtree doesn't
219     // get disconnected.
220     SmallVector<DominatorTree::UpdateType, 3> Updates;
221     Updates.push_back({DominatorTree::Insert, TIBB, NewBB});
222     Updates.push_back({DominatorTree::Insert, NewBB, DestBB});
223     if (llvm::find(successors(TIBB), DestBB) == succ_end(TIBB))
224       Updates.push_back({DominatorTree::Delete, TIBB, DestBB});
225
226     DT->applyUpdates(Updates);
227   }
228
229   // Update LoopInfo if it is around.
230   if (LI) {
231     if (Loop *TIL = LI->getLoopFor(TIBB)) {
232       // If one or the other blocks were not in a loop, the new block is not
233       // either, and thus LI doesn't need to be updated.
234       if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
235         if (TIL == DestLoop) {
236           // Both in the same loop, the NewBB joins loop.
237           DestLoop->addBasicBlockToLoop(NewBB, *LI);
238         } else if (TIL->contains(DestLoop)) {
239           // Edge from an outer loop to an inner loop.  Add to the outer loop.
240           TIL->addBasicBlockToLoop(NewBB, *LI);
241         } else if (DestLoop->contains(TIL)) {
242           // Edge from an inner loop to an outer loop.  Add to the outer loop.
243           DestLoop->addBasicBlockToLoop(NewBB, *LI);
244         } else {
245           // Edge from two loops with no containment relation.  Because these
246           // are natural loops, we know that the destination block must be the
247           // header of its loop (adding a branch into a loop elsewhere would
248           // create an irreducible loop).
249           assert(DestLoop->getHeader() == DestBB &&
250                  "Should not create irreducible loops!");
251           if (Loop *P = DestLoop->getParentLoop())
252             P->addBasicBlockToLoop(NewBB, *LI);
253         }
254       }
255
256       // If TIBB is in a loop and DestBB is outside of that loop, we may need
257       // to update LoopSimplify form and LCSSA form.
258       if (!TIL->contains(DestBB)) {
259         assert(!TIL->contains(NewBB) &&
260                "Split point for loop exit is contained in loop!");
261
262         // Update LCSSA form in the newly created exit block.
263         if (Options.PreserveLCSSA) {
264           createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
265         }
266
267         // The only that we can break LoopSimplify form by splitting a critical
268         // edge is if after the split there exists some edge from TIL to DestBB
269         // *and* the only edge into DestBB from outside of TIL is that of
270         // NewBB. If the first isn't true, then LoopSimplify still holds, NewBB
271         // is the new exit block and it has no non-loop predecessors. If the
272         // second isn't true, then DestBB was not in LoopSimplify form prior to
273         // the split as it had a non-loop predecessor. In both of these cases,
274         // the predecessor must be directly in TIL, not in a subloop, or again
275         // LoopSimplify doesn't hold.
276         SmallVector<BasicBlock *, 4> LoopPreds;
277         for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); I != E;
278              ++I) {
279           BasicBlock *P = *I;
280           if (P == NewBB)
281             continue; // The new block is known.
282           if (LI->getLoopFor(P) != TIL) {
283             // No need to re-simplify, it wasn't to start with.
284             LoopPreds.clear();
285             break;
286           }
287           LoopPreds.push_back(P);
288         }
289         if (!LoopPreds.empty()) {
290           assert(!DestBB->isEHPad() && "We don't split edges to EH pads!");
291           BasicBlock *NewExitBB = SplitBlockPredecessors(
292               DestBB, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
293           if (Options.PreserveLCSSA)
294             createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);
295         }
296       }
297     }
298   }
299
300   return NewBB;
301 }
302
303 // Return the unique indirectbr predecessor of a block. This may return null
304 // even if such a predecessor exists, if it's not useful for splitting.
305 // If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
306 // predecessors of BB.
307 static BasicBlock *
308 findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
309   // If the block doesn't have any PHIs, we don't care about it, since there's
310   // no point in splitting it.
311   PHINode *PN = dyn_cast<PHINode>(BB->begin());
312   if (!PN)
313     return nullptr;
314
315   // Verify we have exactly one IBR predecessor.
316   // Conservatively bail out if one of the other predecessors is not a "regular"
317   // terminator (that is, not a switch or a br).
318   BasicBlock *IBB = nullptr;
319   for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
320     BasicBlock *PredBB = PN->getIncomingBlock(Pred);
321     Instruction *PredTerm = PredBB->getTerminator();
322     switch (PredTerm->getOpcode()) {
323     case Instruction::IndirectBr:
324       if (IBB)
325         return nullptr;
326       IBB = PredBB;
327       break;
328     case Instruction::Br:
329     case Instruction::Switch:
330       OtherPreds.push_back(PredBB);
331       continue;
332     default:
333       return nullptr;
334     }
335   }
336
337   return IBB;
338 }
339
340 bool llvm::SplitIndirectBrCriticalEdges(Function &F,
341                                         BranchProbabilityInfo *BPI,
342                                         BlockFrequencyInfo *BFI) {
343   // Check whether the function has any indirectbrs, and collect which blocks
344   // they may jump to. Since most functions don't have indirect branches,
345   // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
346   SmallSetVector<BasicBlock *, 16> Targets;
347   for (auto &BB : F) {
348     auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
349     if (!IBI)
350       continue;
351
352     for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
353       Targets.insert(IBI->getSuccessor(Succ));
354   }
355
356   if (Targets.empty())
357     return false;
358
359   bool ShouldUpdateAnalysis = BPI && BFI;
360   bool Changed = false;
361   for (BasicBlock *Target : Targets) {
362     SmallVector<BasicBlock *, 16> OtherPreds;
363     BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
364     // If we did not found an indirectbr, or the indirectbr is the only
365     // incoming edge, this isn't the kind of edge we're looking for.
366     if (!IBRPred || OtherPreds.empty())
367       continue;
368
369     // Don't even think about ehpads/landingpads.
370     Instruction *FirstNonPHI = Target->getFirstNonPHI();
371     if (FirstNonPHI->isEHPad() || Target->isLandingPad())
372       continue;
373
374     BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
375     if (ShouldUpdateAnalysis) {
376       // Copy the BFI/BPI from Target to BodyBlock.
377       for (unsigned I = 0, E = BodyBlock->getTerminator()->getNumSuccessors();
378            I < E; ++I)
379         BPI->setEdgeProbability(BodyBlock, I,
380                                 BPI->getEdgeProbability(Target, I));
381       BFI->setBlockFreq(BodyBlock, BFI->getBlockFreq(Target).getFrequency());
382     }
383     // It's possible Target was its own successor through an indirectbr.
384     // In this case, the indirectbr now comes from BodyBlock.
385     if (IBRPred == Target)
386       IBRPred = BodyBlock;
387
388     // At this point Target only has PHIs, and BodyBlock has the rest of the
389     // block's body. Create a copy of Target that will be used by the "direct"
390     // preds.
391     ValueToValueMapTy VMap;
392     BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
393
394     BlockFrequency BlockFreqForDirectSucc;
395     for (BasicBlock *Pred : OtherPreds) {
396       // If the target is a loop to itself, then the terminator of the split
397       // block (BodyBlock) needs to be updated.
398       BasicBlock *Src = Pred != Target ? Pred : BodyBlock;
399       Src->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
400       if (ShouldUpdateAnalysis)
401         BlockFreqForDirectSucc += BFI->getBlockFreq(Src) *
402             BPI->getEdgeProbability(Src, DirectSucc);
403     }
404     if (ShouldUpdateAnalysis) {
405       BFI->setBlockFreq(DirectSucc, BlockFreqForDirectSucc.getFrequency());
406       BlockFrequency NewBlockFreqForTarget =
407           BFI->getBlockFreq(Target) - BlockFreqForDirectSucc;
408       BFI->setBlockFreq(Target, NewBlockFreqForTarget.getFrequency());
409       BPI->eraseBlock(Target);
410     }
411
412     // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
413     // they are clones, so the number of PHIs are the same.
414     // (a) Remove the edge coming from IBRPred from the "Direct" PHI
415     // (b) Leave that as the only edge in the "Indirect" PHI.
416     // (c) Merge the two in the body block.
417     BasicBlock::iterator Indirect = Target->begin(),
418                          End = Target->getFirstNonPHI()->getIterator();
419     BasicBlock::iterator Direct = DirectSucc->begin();
420     BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
421
422     assert(&*End == Target->getTerminator() &&
423            "Block was expected to only contain PHIs");
424
425     while (Indirect != End) {
426       PHINode *DirPHI = cast<PHINode>(Direct);
427       PHINode *IndPHI = cast<PHINode>(Indirect);
428
429       // Now, clean up - the direct block shouldn't get the indirect value,
430       // and vice versa.
431       DirPHI->removeIncomingValue(IBRPred);
432       Direct++;
433
434       // Advance the pointer here, to avoid invalidation issues when the old
435       // PHI is erased.
436       Indirect++;
437
438       PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
439       NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
440                              IBRPred);
441
442       // Create a PHI in the body block, to merge the direct and indirect
443       // predecessors.
444       PHINode *MergePHI =
445           PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
446       MergePHI->addIncoming(NewIndPHI, Target);
447       MergePHI->addIncoming(DirPHI, DirectSucc);
448
449       IndPHI->replaceAllUsesWith(MergePHI);
450       IndPHI->eraseFromParent();
451     }
452
453     Changed = true;
454   }
455
456   return Changed;
457 }