Revert r354244 "[DAGCombiner] Eliminate dead stores to stack."
[llvm-complete.git] / lib / Transforms / Utils / BreakCriticalEdges.cpp
blob2944c372425e684160f45623e43f1850fbd7768b
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.
15 //===----------------------------------------------------------------------===//
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;
37 #define DEBUG_TYPE "break-crit-edges"
39 STATISTIC(NumBroken, "Number of blocks inserted");
41 namespace {
42 struct BreakCriticalEdges : public FunctionPass {
43 static char ID; // Pass identification, replacement for typeid
44 BreakCriticalEdges() : FunctionPass(ID) {
45 initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry());
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;
59 void getAnalysisUsage(AnalysisUsage &AU) const override {
60 AU.addPreserved<DominatorTreeWrapperPass>();
61 AU.addPreserved<LoopInfoWrapperPass>();
63 // No loop canonicalization guarantees are broken by this pass.
64 AU.addPreservedID(LoopSimplifyID);
69 char BreakCriticalEdges::ID = 0;
70 INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges",
71 "Break critical edges in CFG", false, false)
73 // Publicly exposed interface to pass...
74 char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID;
75 FunctionPass *llvm::createBreakCriticalEdgesPass() {
76 return new BreakCriticalEdges();
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;
93 //===----------------------------------------------------------------------===//
94 // Implementation of the external critical edge manipulation functions
95 //===----------------------------------------------------------------------===//
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!");
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);
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;
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]);
126 // Update the original PHI.
127 PN.setIncomingValue(Idx, NewPN);
131 BasicBlock *
132 llvm::SplitCriticalEdge(Instruction *TI, unsigned SuccNum,
133 const CriticalEdgeSplittingOptions &Options) {
134 if (!isCriticalEdge(TI, SuccNum, Options.MergeIdenticalEdges))
135 return nullptr;
137 assert(!isa<IndirectBrInst>(TI) &&
138 "Cannot split critical edge from IndirectBrInst");
140 BasicBlock *TIBB = TI->getParent();
141 BasicBlock *DestBB = TI->getSuccessor(SuccNum);
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;
147 // Don't split the non-fallthrough edge from a callbr.
148 if (isa<CallBrInst>(TI) && SuccNum > 0)
149 return nullptr;
151 // Create a new basic block, linking it into the CFG.
152 BasicBlock *NewBB = BasicBlock::Create(TI->getContext(),
153 TIBB->getName() + "." + DestBB->getName() + "_crit_edge");
154 // Create our unconditional branch.
155 BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
156 NewBI->setDebugLoc(TI->getDebugLoc());
158 // Branch to the new block, breaking the edge.
159 TI->setSuccessor(SuccNum, NewBB);
161 // Insert the block into the function... right after the block TI lives in.
162 Function &F = *TIBB->getParent();
163 Function::iterator FBBI = TIBB->getIterator();
164 F.getBasicBlockList().insert(++FBBI, NewBB);
166 // If there are any PHI nodes in DestBB, we need to update them so that they
167 // merge incoming values from NewBB instead of from TIBB.
169 unsigned BBIdx = 0;
170 for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
171 // We no longer enter through TIBB, now we come in through NewBB.
172 // Revector exactly one entry in the PHI node that used to come from
173 // TIBB to come from NewBB.
174 PHINode *PN = cast<PHINode>(I);
176 // Reuse the previous value of BBIdx if it lines up. In cases where we
177 // have multiple phi nodes with *lots* of predecessors, this is a speed
178 // win because we don't have to scan the PHI looking for TIBB. This
179 // happens because the BB list of PHI nodes are usually in the same
180 // order.
181 if (PN->getIncomingBlock(BBIdx) != TIBB)
182 BBIdx = PN->getBasicBlockIndex(TIBB);
183 PN->setIncomingBlock(BBIdx, NewBB);
187 // If there are any other edges from TIBB to DestBB, update those to go
188 // through the split block, making those edges non-critical as well (and
189 // reducing the number of phi entries in the DestBB if relevant).
190 if (Options.MergeIdenticalEdges) {
191 for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
192 if (TI->getSuccessor(i) != DestBB) continue;
194 // Remove an entry for TIBB from DestBB phi nodes.
195 DestBB->removePredecessor(TIBB, Options.KeepOneInputPHIs);
197 // We found another edge to DestBB, go to NewBB instead.
198 TI->setSuccessor(i, NewBB);
202 // If we have nothing to update, just return.
203 auto *DT = Options.DT;
204 auto *LI = Options.LI;
205 auto *MSSAU = Options.MSSAU;
206 if (MSSAU)
207 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(
208 DestBB, NewBB, {TIBB}, Options.MergeIdenticalEdges);
210 if (!DT && !LI)
211 return NewBB;
213 if (DT) {
214 // Update the DominatorTree.
215 // ---> NewBB -----\
216 // / V
217 // TIBB -------\\------> DestBB
219 // First, inform the DT about the new path from TIBB to DestBB via NewBB,
220 // then delete the old edge from TIBB to DestBB. By doing this in that order
221 // DestBB stays reachable in the DT the whole time and its subtree doesn't
222 // get disconnected.
223 SmallVector<DominatorTree::UpdateType, 3> Updates;
224 Updates.push_back({DominatorTree::Insert, TIBB, NewBB});
225 Updates.push_back({DominatorTree::Insert, NewBB, DestBB});
226 if (llvm::find(successors(TIBB), DestBB) == succ_end(TIBB))
227 Updates.push_back({DominatorTree::Delete, TIBB, DestBB});
229 DT->applyUpdates(Updates);
232 // Update LoopInfo if it is around.
233 if (LI) {
234 if (Loop *TIL = LI->getLoopFor(TIBB)) {
235 // If one or the other blocks were not in a loop, the new block is not
236 // either, and thus LI doesn't need to be updated.
237 if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
238 if (TIL == DestLoop) {
239 // Both in the same loop, the NewBB joins loop.
240 DestLoop->addBasicBlockToLoop(NewBB, *LI);
241 } else if (TIL->contains(DestLoop)) {
242 // Edge from an outer loop to an inner loop. Add to the outer loop.
243 TIL->addBasicBlockToLoop(NewBB, *LI);
244 } else if (DestLoop->contains(TIL)) {
245 // Edge from an inner loop to an outer loop. Add to the outer loop.
246 DestLoop->addBasicBlockToLoop(NewBB, *LI);
247 } else {
248 // Edge from two loops with no containment relation. Because these
249 // are natural loops, we know that the destination block must be the
250 // header of its loop (adding a branch into a loop elsewhere would
251 // create an irreducible loop).
252 assert(DestLoop->getHeader() == DestBB &&
253 "Should not create irreducible loops!");
254 if (Loop *P = DestLoop->getParentLoop())
255 P->addBasicBlockToLoop(NewBB, *LI);
259 // If TIBB is in a loop and DestBB is outside of that loop, we may need
260 // to update LoopSimplify form and LCSSA form.
261 if (!TIL->contains(DestBB)) {
262 assert(!TIL->contains(NewBB) &&
263 "Split point for loop exit is contained in loop!");
265 // Update LCSSA form in the newly created exit block.
266 if (Options.PreserveLCSSA) {
267 createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
270 // The only that we can break LoopSimplify form by splitting a critical
271 // edge is if after the split there exists some edge from TIL to DestBB
272 // *and* the only edge into DestBB from outside of TIL is that of
273 // NewBB. If the first isn't true, then LoopSimplify still holds, NewBB
274 // is the new exit block and it has no non-loop predecessors. If the
275 // second isn't true, then DestBB was not in LoopSimplify form prior to
276 // the split as it had a non-loop predecessor. In both of these cases,
277 // the predecessor must be directly in TIL, not in a subloop, or again
278 // LoopSimplify doesn't hold.
279 SmallVector<BasicBlock *, 4> LoopPreds;
280 for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); I != E;
281 ++I) {
282 BasicBlock *P = *I;
283 if (P == NewBB)
284 continue; // The new block is known.
285 if (LI->getLoopFor(P) != TIL) {
286 // No need to re-simplify, it wasn't to start with.
287 LoopPreds.clear();
288 break;
290 LoopPreds.push_back(P);
292 if (!LoopPreds.empty()) {
293 assert(!DestBB->isEHPad() && "We don't split edges to EH pads!");
294 BasicBlock *NewExitBB = SplitBlockPredecessors(
295 DestBB, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
296 if (Options.PreserveLCSSA)
297 createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);
303 return NewBB;
306 // Return the unique indirectbr predecessor of a block. This may return null
307 // even if such a predecessor exists, if it's not useful for splitting.
308 // If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
309 // predecessors of BB.
310 static BasicBlock *
311 findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
312 // If the block doesn't have any PHIs, we don't care about it, since there's
313 // no point in splitting it.
314 PHINode *PN = dyn_cast<PHINode>(BB->begin());
315 if (!PN)
316 return nullptr;
318 // Verify we have exactly one IBR predecessor.
319 // Conservatively bail out if one of the other predecessors is not a "regular"
320 // terminator (that is, not a switch or a br).
321 BasicBlock *IBB = nullptr;
322 for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
323 BasicBlock *PredBB = PN->getIncomingBlock(Pred);
324 Instruction *PredTerm = PredBB->getTerminator();
325 switch (PredTerm->getOpcode()) {
326 case Instruction::IndirectBr:
327 if (IBB)
328 return nullptr;
329 IBB = PredBB;
330 break;
331 case Instruction::Br:
332 case Instruction::Switch:
333 OtherPreds.push_back(PredBB);
334 continue;
335 default:
336 return nullptr;
340 return IBB;
343 bool llvm::SplitIndirectBrCriticalEdges(Function &F,
344 BranchProbabilityInfo *BPI,
345 BlockFrequencyInfo *BFI) {
346 // Check whether the function has any indirectbrs, and collect which blocks
347 // they may jump to. Since most functions don't have indirect branches,
348 // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
349 SmallSetVector<BasicBlock *, 16> Targets;
350 for (auto &BB : F) {
351 auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
352 if (!IBI)
353 continue;
355 for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
356 Targets.insert(IBI->getSuccessor(Succ));
359 if (Targets.empty())
360 return false;
362 bool ShouldUpdateAnalysis = BPI && BFI;
363 bool Changed = false;
364 for (BasicBlock *Target : Targets) {
365 SmallVector<BasicBlock *, 16> OtherPreds;
366 BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
367 // If we did not found an indirectbr, or the indirectbr is the only
368 // incoming edge, this isn't the kind of edge we're looking for.
369 if (!IBRPred || OtherPreds.empty())
370 continue;
372 // Don't even think about ehpads/landingpads.
373 Instruction *FirstNonPHI = Target->getFirstNonPHI();
374 if (FirstNonPHI->isEHPad() || Target->isLandingPad())
375 continue;
377 BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
378 if (ShouldUpdateAnalysis) {
379 // Copy the BFI/BPI from Target to BodyBlock.
380 for (unsigned I = 0, E = BodyBlock->getTerminator()->getNumSuccessors();
381 I < E; ++I)
382 BPI->setEdgeProbability(BodyBlock, I,
383 BPI->getEdgeProbability(Target, I));
384 BFI->setBlockFreq(BodyBlock, BFI->getBlockFreq(Target).getFrequency());
386 // It's possible Target was its own successor through an indirectbr.
387 // In this case, the indirectbr now comes from BodyBlock.
388 if (IBRPred == Target)
389 IBRPred = BodyBlock;
391 // At this point Target only has PHIs, and BodyBlock has the rest of the
392 // block's body. Create a copy of Target that will be used by the "direct"
393 // preds.
394 ValueToValueMapTy VMap;
395 BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
397 BlockFrequency BlockFreqForDirectSucc;
398 for (BasicBlock *Pred : OtherPreds) {
399 // If the target is a loop to itself, then the terminator of the split
400 // block (BodyBlock) needs to be updated.
401 BasicBlock *Src = Pred != Target ? Pred : BodyBlock;
402 Src->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
403 if (ShouldUpdateAnalysis)
404 BlockFreqForDirectSucc += BFI->getBlockFreq(Src) *
405 BPI->getEdgeProbability(Src, DirectSucc);
407 if (ShouldUpdateAnalysis) {
408 BFI->setBlockFreq(DirectSucc, BlockFreqForDirectSucc.getFrequency());
409 BlockFrequency NewBlockFreqForTarget =
410 BFI->getBlockFreq(Target) - BlockFreqForDirectSucc;
411 BFI->setBlockFreq(Target, NewBlockFreqForTarget.getFrequency());
412 BPI->eraseBlock(Target);
415 // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
416 // they are clones, so the number of PHIs are the same.
417 // (a) Remove the edge coming from IBRPred from the "Direct" PHI
418 // (b) Leave that as the only edge in the "Indirect" PHI.
419 // (c) Merge the two in the body block.
420 BasicBlock::iterator Indirect = Target->begin(),
421 End = Target->getFirstNonPHI()->getIterator();
422 BasicBlock::iterator Direct = DirectSucc->begin();
423 BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
425 assert(&*End == Target->getTerminator() &&
426 "Block was expected to only contain PHIs");
428 while (Indirect != End) {
429 PHINode *DirPHI = cast<PHINode>(Direct);
430 PHINode *IndPHI = cast<PHINode>(Indirect);
432 // Now, clean up - the direct block shouldn't get the indirect value,
433 // and vice versa.
434 DirPHI->removeIncomingValue(IBRPred);
435 Direct++;
437 // Advance the pointer here, to avoid invalidation issues when the old
438 // PHI is erased.
439 Indirect++;
441 PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
442 NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
443 IBRPred);
445 // Create a PHI in the body block, to merge the direct and indirect
446 // predecessors.
447 PHINode *MergePHI =
448 PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
449 MergePHI->addIncoming(NewIndPHI, Target);
450 MergePHI->addIncoming(DirPHI, DirectSucc);
452 IndPHI->replaceAllUsesWith(MergePHI);
453 IndPHI->eraseFromParent();
456 Changed = true;
459 return Changed;