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/SmallVector.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/Analysis/AliasAnalysis.h" 22 #include "llvm/Analysis/CFG.h" 23 #include "llvm/Analysis/LoopInfo.h" 24 #include "llvm/IR/CFG.h" 25 #include "llvm/IR/Dominators.h" 26 #include "llvm/IR/Instructions.h" 27 #include "llvm/IR/Type.h" 28 #include "llvm/Support/ErrorHandling.h" 29 #include "llvm/Transforms/Scalar.h" 30 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 31 using namespace llvm; 32 33 #define DEBUG_TYPE "break-crit-edges" 34 35 STATISTIC(NumBroken, "Number of blocks inserted"); 36 37 namespace { 38 struct BreakCriticalEdges : public FunctionPass { 39 static char ID; // Pass identification, replacement for typeid 40 BreakCriticalEdges() : FunctionPass(ID) { 41 initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry()); 42 } 43 44 bool runOnFunction(Function &F) override { 45 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 46 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr; 47 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>(); 48 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr; 49 unsigned N = 50 SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI)); 51 NumBroken += N; 52 return N > 0; 53 } 54 55 void getAnalysisUsage(AnalysisUsage &AU) const override { 56 AU.addPreserved<DominatorTreeWrapperPass>(); 57 AU.addPreserved<LoopInfoWrapperPass>(); 58 59 // No loop canonicalization guarantees are broken by this pass. 60 AU.addPreservedID(LoopSimplifyID); 61 } 62 }; 63 } 64 65 char BreakCriticalEdges::ID = 0; 66 INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges", 67 "Break critical edges in CFG", false, false) 68 69 // Publicly exposed interface to pass... 70 char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID; 71 FunctionPass *llvm::createBreakCriticalEdgesPass() { 72 return new BreakCriticalEdges(); 73 } 74 75 PreservedAnalyses BreakCriticalEdgesPass::run(Function &F, 76 FunctionAnalysisManager &AM) { 77 auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(F); 78 auto *LI = AM.getCachedResult<LoopAnalysis>(F); 79 unsigned N = SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI)); 80 NumBroken += N; 81 if (N == 0) 82 return PreservedAnalyses::all(); 83 PreservedAnalyses PA; 84 PA.preserve<DominatorTreeAnalysis>(); 85 PA.preserve<LoopAnalysis>(); 86 return PA; 87 } 88 89 //===----------------------------------------------------------------------===// 90 // Implementation of the external critical edge manipulation functions 91 //===----------------------------------------------------------------------===// 92 93 /// When a loop exit edge is split, LCSSA form may require new PHIs in the new 94 /// exit block. This function inserts the new PHIs, as needed. Preds is a list 95 /// of preds inside the loop, SplitBB is the new loop exit block, and DestBB is 96 /// the old loop exit, now the successor of SplitBB. 97 static void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds, 98 BasicBlock *SplitBB, 99 BasicBlock *DestBB) { 100 // SplitBB shouldn't have anything non-trivial in it yet. 101 assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() || 102 SplitBB->isLandingPad()) && "SplitBB has non-PHI nodes!"); 103 104 // For each PHI in the destination block. 105 for (BasicBlock::iterator I = DestBB->begin(); 106 PHINode *PN = dyn_cast<PHINode>(I); ++I) { 107 unsigned Idx = PN->getBasicBlockIndex(SplitBB); 108 Value *V = PN->getIncomingValue(Idx); 109 110 // If the input is a PHI which already satisfies LCSSA, don't create 111 // a new one. 112 if (const PHINode *VP = dyn_cast<PHINode>(V)) 113 if (VP->getParent() == SplitBB) 114 continue; 115 116 // Otherwise a new PHI is needed. Create one and populate it. 117 PHINode *NewPN = PHINode::Create( 118 PN->getType(), Preds.size(), "split", 119 SplitBB->isLandingPad() ? &SplitBB->front() : SplitBB->getTerminator()); 120 for (unsigned i = 0, e = Preds.size(); i != e; ++i) 121 NewPN->addIncoming(V, Preds[i]); 122 123 // Update the original PHI. 124 PN->setIncomingValue(Idx, NewPN); 125 } 126 } 127 128 BasicBlock * 129 llvm::SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum, 130 const CriticalEdgeSplittingOptions &Options) { 131 if (!isCriticalEdge(TI, SuccNum, Options.MergeIdenticalEdges)) 132 return nullptr; 133 134 assert(!isa<IndirectBrInst>(TI) && 135 "Cannot split critical edge from IndirectBrInst"); 136 137 BasicBlock *TIBB = TI->getParent(); 138 BasicBlock *DestBB = TI->getSuccessor(SuccNum); 139 140 // Splitting the critical edge to a pad block is non-trivial. Don't do 141 // it in this generic function. 142 if (DestBB->isEHPad()) return nullptr; 143 144 // Create a new basic block, linking it into the CFG. 145 BasicBlock *NewBB = BasicBlock::Create(TI->getContext(), 146 TIBB->getName() + "." + DestBB->getName() + "_crit_edge"); 147 // Create our unconditional branch. 148 BranchInst *NewBI = BranchInst::Create(DestBB, NewBB); 149 NewBI->setDebugLoc(TI->getDebugLoc()); 150 151 // Branch to the new block, breaking the edge. 152 TI->setSuccessor(SuccNum, NewBB); 153 154 // Insert the block into the function... right after the block TI lives in. 155 Function &F = *TIBB->getParent(); 156 Function::iterator FBBI = TIBB->getIterator(); 157 F.getBasicBlockList().insert(++FBBI, NewBB); 158 159 // If there are any PHI nodes in DestBB, we need to update them so that they 160 // merge incoming values from NewBB instead of from TIBB. 161 { 162 unsigned BBIdx = 0; 163 for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) { 164 // We no longer enter through TIBB, now we come in through NewBB. 165 // Revector exactly one entry in the PHI node that used to come from 166 // TIBB to come from NewBB. 167 PHINode *PN = cast<PHINode>(I); 168 169 // Reuse the previous value of BBIdx if it lines up. In cases where we 170 // have multiple phi nodes with *lots* of predecessors, this is a speed 171 // win because we don't have to scan the PHI looking for TIBB. This 172 // happens because the BB list of PHI nodes are usually in the same 173 // order. 174 if (PN->getIncomingBlock(BBIdx) != TIBB) 175 BBIdx = PN->getBasicBlockIndex(TIBB); 176 PN->setIncomingBlock(BBIdx, NewBB); 177 } 178 } 179 180 // If there are any other edges from TIBB to DestBB, update those to go 181 // through the split block, making those edges non-critical as well (and 182 // reducing the number of phi entries in the DestBB if relevant). 183 if (Options.MergeIdenticalEdges) { 184 for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) { 185 if (TI->getSuccessor(i) != DestBB) continue; 186 187 // Remove an entry for TIBB from DestBB phi nodes. 188 DestBB->removePredecessor(TIBB, Options.DontDeleteUselessPHIs); 189 190 // We found another edge to DestBB, go to NewBB instead. 191 TI->setSuccessor(i, NewBB); 192 } 193 } 194 195 // If we have nothing to update, just return. 196 auto *DT = Options.DT; 197 auto *LI = Options.LI; 198 if (!DT && !LI) 199 return NewBB; 200 201 // Now update analysis information. Since the only predecessor of NewBB is 202 // the TIBB, TIBB clearly dominates NewBB. TIBB usually doesn't dominate 203 // anything, as there are other successors of DestBB. However, if all other 204 // predecessors of DestBB are already dominated by DestBB (e.g. DestBB is a 205 // loop header) then NewBB dominates DestBB. 206 SmallVector<BasicBlock*, 8> OtherPreds; 207 208 // If there is a PHI in the block, loop over predecessors with it, which is 209 // faster than iterating pred_begin/end. 210 if (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) { 211 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 212 if (PN->getIncomingBlock(i) != NewBB) 213 OtherPreds.push_back(PN->getIncomingBlock(i)); 214 } else { 215 for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); 216 I != E; ++I) { 217 BasicBlock *P = *I; 218 if (P != NewBB) 219 OtherPreds.push_back(P); 220 } 221 } 222 223 bool NewBBDominatesDestBB = true; 224 225 // Should we update DominatorTree information? 226 if (DT) { 227 DomTreeNode *TINode = DT->getNode(TIBB); 228 229 // The new block is not the immediate dominator for any other nodes, but 230 // TINode is the immediate dominator for the new node. 231 // 232 if (TINode) { // Don't break unreachable code! 233 DomTreeNode *NewBBNode = DT->addNewBlock(NewBB, TIBB); 234 DomTreeNode *DestBBNode = nullptr; 235 236 // If NewBBDominatesDestBB hasn't been computed yet, do so with DT. 237 if (!OtherPreds.empty()) { 238 DestBBNode = DT->getNode(DestBB); 239 while (!OtherPreds.empty() && NewBBDominatesDestBB) { 240 if (DomTreeNode *OPNode = DT->getNode(OtherPreds.back())) 241 NewBBDominatesDestBB = DT->dominates(DestBBNode, OPNode); 242 OtherPreds.pop_back(); 243 } 244 OtherPreds.clear(); 245 } 246 247 // If NewBBDominatesDestBB, then NewBB dominates DestBB, otherwise it 248 // doesn't dominate anything. 249 if (NewBBDominatesDestBB) { 250 if (!DestBBNode) DestBBNode = DT->getNode(DestBB); 251 DT->changeImmediateDominator(DestBBNode, NewBBNode); 252 } 253 } 254 } 255 256 // Update LoopInfo if it is around. 257 if (LI) { 258 if (Loop *TIL = LI->getLoopFor(TIBB)) { 259 // If one or the other blocks were not in a loop, the new block is not 260 // either, and thus LI doesn't need to be updated. 261 if (Loop *DestLoop = LI->getLoopFor(DestBB)) { 262 if (TIL == DestLoop) { 263 // Both in the same loop, the NewBB joins loop. 264 DestLoop->addBasicBlockToLoop(NewBB, *LI); 265 } else if (TIL->contains(DestLoop)) { 266 // Edge from an outer loop to an inner loop. Add to the outer loop. 267 TIL->addBasicBlockToLoop(NewBB, *LI); 268 } else if (DestLoop->contains(TIL)) { 269 // Edge from an inner loop to an outer loop. Add to the outer loop. 270 DestLoop->addBasicBlockToLoop(NewBB, *LI); 271 } else { 272 // Edge from two loops with no containment relation. Because these 273 // are natural loops, we know that the destination block must be the 274 // header of its loop (adding a branch into a loop elsewhere would 275 // create an irreducible loop). 276 assert(DestLoop->getHeader() == DestBB && 277 "Should not create irreducible loops!"); 278 if (Loop *P = DestLoop->getParentLoop()) 279 P->addBasicBlockToLoop(NewBB, *LI); 280 } 281 } 282 283 // If TIBB is in a loop and DestBB is outside of that loop, we may need 284 // to update LoopSimplify form and LCSSA form. 285 if (!TIL->contains(DestBB)) { 286 assert(!TIL->contains(NewBB) && 287 "Split point for loop exit is contained in loop!"); 288 289 // Update LCSSA form in the newly created exit block. 290 if (Options.PreserveLCSSA) { 291 createPHIsForSplitLoopExit(TIBB, NewBB, DestBB); 292 } 293 294 // The only that we can break LoopSimplify form by splitting a critical 295 // edge is if after the split there exists some edge from TIL to DestBB 296 // *and* the only edge into DestBB from outside of TIL is that of 297 // NewBB. If the first isn't true, then LoopSimplify still holds, NewBB 298 // is the new exit block and it has no non-loop predecessors. If the 299 // second isn't true, then DestBB was not in LoopSimplify form prior to 300 // the split as it had a non-loop predecessor. In both of these cases, 301 // the predecessor must be directly in TIL, not in a subloop, or again 302 // LoopSimplify doesn't hold. 303 SmallVector<BasicBlock *, 4> LoopPreds; 304 for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); I != E; 305 ++I) { 306 BasicBlock *P = *I; 307 if (P == NewBB) 308 continue; // The new block is known. 309 if (LI->getLoopFor(P) != TIL) { 310 // No need to re-simplify, it wasn't to start with. 311 LoopPreds.clear(); 312 break; 313 } 314 LoopPreds.push_back(P); 315 } 316 if (!LoopPreds.empty()) { 317 assert(!DestBB->isEHPad() && "We don't split edges to EH pads!"); 318 BasicBlock *NewExitBB = SplitBlockPredecessors( 319 DestBB, LoopPreds, "split", DT, LI, Options.PreserveLCSSA); 320 if (Options.PreserveLCSSA) 321 createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB); 322 } 323 } 324 } 325 } 326 327 return NewBB; 328 } 329