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