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 // forward dominator (set, immediate dominators, tree, and frontier) 15 // information. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #define DEBUG_TYPE "break-crit-edges" 20 #include "llvm/Transforms/Scalar.h" 21 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 22 #include "llvm/Analysis/Dominators.h" 23 #include "llvm/Analysis/LoopInfo.h" 24 #include "llvm/Analysis/ProfileInfo.h" 25 #include "llvm/Function.h" 26 #include "llvm/Instructions.h" 27 #include "llvm/Type.h" 28 #include "llvm/Support/CFG.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/ADT/SmallVector.h" 31 #include "llvm/ADT/Statistic.h" 32 using namespace llvm; 33 34 STATISTIC(NumBroken, "Number of blocks inserted"); 35 36 namespace { 37 struct BreakCriticalEdges : public FunctionPass { 38 static char ID; // Pass identification, replacement for typeid 39 BreakCriticalEdges() : FunctionPass(ID) { 40 initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry()); 41 } 42 43 virtual bool runOnFunction(Function &F); 44 45 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 46 AU.addPreserved<DominatorTree>(); 47 AU.addPreserved<DominanceFrontier>(); 48 AU.addPreserved<LoopInfo>(); 49 AU.addPreserved<ProfileInfo>(); 50 51 // No loop canonicalization guarantees are broken by this pass. 52 AU.addPreservedID(LoopSimplifyID); 53 } 54 }; 55 } 56 57 char BreakCriticalEdges::ID = 0; 58 INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges", 59 "Break critical edges in CFG", false, false) 60 61 // Publically exposed interface to pass... 62 char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID; 63 FunctionPass *llvm::createBreakCriticalEdgesPass() { 64 return new BreakCriticalEdges(); 65 } 66 67 // runOnFunction - Loop over all of the edges in the CFG, breaking critical 68 // edges as they are found. 69 // 70 bool BreakCriticalEdges::runOnFunction(Function &F) { 71 bool Changed = false; 72 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) { 73 TerminatorInst *TI = I->getTerminator(); 74 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI)) 75 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 76 if (SplitCriticalEdge(TI, i, this)) { 77 ++NumBroken; 78 Changed = true; 79 } 80 } 81 82 return Changed; 83 } 84 85 //===----------------------------------------------------------------------===// 86 // Implementation of the external critical edge manipulation functions 87 //===----------------------------------------------------------------------===// 88 89 // isCriticalEdge - Return true if the specified edge is a critical edge. 90 // Critical edges are edges from a block with multiple successors to a block 91 // with multiple predecessors. 92 // 93 bool llvm::isCriticalEdge(const TerminatorInst *TI, unsigned SuccNum, 94 bool AllowIdenticalEdges) { 95 assert(SuccNum < TI->getNumSuccessors() && "Illegal edge specification!"); 96 if (TI->getNumSuccessors() == 1) return false; 97 98 const BasicBlock *Dest = TI->getSuccessor(SuccNum); 99 const_pred_iterator I = pred_begin(Dest), E = pred_end(Dest); 100 101 // If there is more than one predecessor, this is a critical edge... 102 assert(I != E && "No preds, but we have an edge to the block?"); 103 const BasicBlock *FirstPred = *I; 104 ++I; // Skip one edge due to the incoming arc from TI. 105 if (!AllowIdenticalEdges) 106 return I != E; 107 108 // If AllowIdenticalEdges is true, then we allow this edge to be considered 109 // non-critical iff all preds come from TI's block. 110 while (I != E) { 111 const BasicBlock *P = *I; 112 if (P != FirstPred) 113 return true; 114 // Note: leave this as is until no one ever compiles with either gcc 4.0.1 115 // or Xcode 2. This seems to work around the pred_iterator assert in PR 2207 116 E = pred_end(P); 117 ++I; 118 } 119 return false; 120 } 121 122 /// CreatePHIsForSplitLoopExit - When a loop exit edge is split, LCSSA form 123 /// may require new PHIs in the new exit block. This function inserts the 124 /// new PHIs, as needed. Preds is a list of preds inside the loop, SplitBB 125 /// is the new loop exit block, and DestBB is the old loop exit, now the 126 /// successor of SplitBB. 127 static void CreatePHIsForSplitLoopExit(SmallVectorImpl<BasicBlock *> &Preds, 128 BasicBlock *SplitBB, 129 BasicBlock *DestBB) { 130 // SplitBB shouldn't have anything non-trivial in it yet. 131 assert(SplitBB->getFirstNonPHI() == SplitBB->getTerminator() && 132 "SplitBB has non-PHI nodes!"); 133 134 // For each PHI in the destination block... 135 for (BasicBlock::iterator I = DestBB->begin(); 136 PHINode *PN = dyn_cast<PHINode>(I); ++I) { 137 unsigned Idx = PN->getBasicBlockIndex(SplitBB); 138 Value *V = PN->getIncomingValue(Idx); 139 // If the input is a PHI which already satisfies LCSSA, don't create 140 // a new one. 141 if (const PHINode *VP = dyn_cast<PHINode>(V)) 142 if (VP->getParent() == SplitBB) 143 continue; 144 // Otherwise a new PHI is needed. Create one and populate it. 145 PHINode *NewPN = PHINode::Create(PN->getType(), "split", 146 SplitBB->getTerminator()); 147 for (unsigned i = 0, e = Preds.size(); i != e; ++i) 148 NewPN->addIncoming(V, Preds[i]); 149 // Update the original PHI. 150 PN->setIncomingValue(Idx, NewPN); 151 } 152 } 153 154 /// SplitCriticalEdge - If this edge is a critical edge, insert a new node to 155 /// split the critical edge. This will update DominatorTree and 156 /// DominatorFrontier information if it is available, thus calling this pass 157 /// will not invalidate either of them. This returns the new block if the edge 158 /// was split, null otherwise. 159 /// 160 /// If MergeIdenticalEdges is true (not the default), *all* edges from TI to the 161 /// specified successor will be merged into the same critical edge block. 162 /// This is most commonly interesting with switch instructions, which may 163 /// have many edges to any one destination. This ensures that all edges to that 164 /// dest go to one block instead of each going to a different block, but isn't 165 /// the standard definition of a "critical edge". 166 /// 167 /// It is invalid to call this function on a critical edge that starts at an 168 /// IndirectBrInst. Splitting these edges will almost always create an invalid 169 /// program because the address of the new block won't be the one that is jumped 170 /// to. 171 /// 172 BasicBlock *llvm::SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum, 173 Pass *P, bool MergeIdenticalEdges) { 174 if (!isCriticalEdge(TI, SuccNum, MergeIdenticalEdges)) return 0; 175 176 assert(!isa<IndirectBrInst>(TI) && 177 "Cannot split critical edge from IndirectBrInst"); 178 179 BasicBlock *TIBB = TI->getParent(); 180 BasicBlock *DestBB = TI->getSuccessor(SuccNum); 181 182 // Create a new basic block, linking it into the CFG. 183 BasicBlock *NewBB = BasicBlock::Create(TI->getContext(), 184 TIBB->getName() + "." + DestBB->getName() + "_crit_edge"); 185 // Create our unconditional branch. 186 BranchInst::Create(DestBB, NewBB); 187 188 // Branch to the new block, breaking the edge. 189 TI->setSuccessor(SuccNum, NewBB); 190 191 // Insert the block into the function... right after the block TI lives in. 192 Function &F = *TIBB->getParent(); 193 Function::iterator FBBI = TIBB; 194 F.getBasicBlockList().insert(++FBBI, NewBB); 195 196 // If there are any PHI nodes in DestBB, we need to update them so that they 197 // merge incoming values from NewBB instead of from TIBB. 198 if (PHINode *APHI = dyn_cast<PHINode>(DestBB->begin())) { 199 // This conceptually does: 200 // foreach (PHINode *PN in DestBB) 201 // PN->setIncomingBlock(PN->getIncomingBlock(TIBB), NewBB); 202 // but is optimized for two cases. 203 204 if (APHI->getNumIncomingValues() <= 8) { // Small # preds case. 205 unsigned BBIdx = 0; 206 for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) { 207 // We no longer enter through TIBB, now we come in through NewBB. 208 // Revector exactly one entry in the PHI node that used to come from 209 // TIBB to come from NewBB. 210 PHINode *PN = cast<PHINode>(I); 211 212 // Reuse the previous value of BBIdx if it lines up. In cases where we 213 // have multiple phi nodes with *lots* of predecessors, this is a speed 214 // win because we don't have to scan the PHI looking for TIBB. This 215 // happens because the BB list of PHI nodes are usually in the same 216 // order. 217 if (PN->getIncomingBlock(BBIdx) != TIBB) 218 BBIdx = PN->getBasicBlockIndex(TIBB); 219 PN->setIncomingBlock(BBIdx, NewBB); 220 } 221 } else { 222 // However, the foreach loop is slow for blocks with lots of predecessors 223 // because PHINode::getIncomingBlock is O(n) in # preds. Instead, walk 224 // the user list of TIBB to find the PHI nodes. 225 SmallPtrSet<PHINode*, 16> UpdatedPHIs; 226 227 for (Value::use_iterator UI = TIBB->use_begin(), E = TIBB->use_end(); 228 UI != E; ) { 229 Value::use_iterator Use = UI++; 230 if (PHINode *PN = dyn_cast<PHINode>(*Use)) { 231 // Remove one entry from each PHI. 232 if (PN->getParent() == DestBB && UpdatedPHIs.insert(PN)) 233 PN->setOperand(Use.getOperandNo(), NewBB); 234 } 235 } 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 (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); 248 249 // We found another edge to DestBB, go to NewBB instead. 250 TI->setSuccessor(i, NewBB); 251 } 252 } 253 254 255 256 // If we don't have a pass object, we can't update anything... 257 if (P == 0) return NewBB; 258 259 DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>(); 260 DominanceFrontier *DF = P->getAnalysisIfAvailable<DominanceFrontier>(); 261 LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>(); 262 ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>(); 263 264 // If we have nothing to update, just return. 265 if (DT == 0 && DF == 0 && LI == 0 && PI == 0) 266 return NewBB; 267 268 // Now update analysis information. Since the only predecessor of NewBB is 269 // the TIBB, TIBB clearly dominates NewBB. TIBB usually doesn't dominate 270 // anything, as there are other successors of DestBB. However, if all other 271 // predecessors of DestBB are already dominated by DestBB (e.g. DestBB is a 272 // loop header) then NewBB dominates DestBB. 273 SmallVector<BasicBlock*, 8> OtherPreds; 274 275 // If there is a PHI in the block, loop over predecessors with it, which is 276 // faster than iterating pred_begin/end. 277 if (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) { 278 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 279 if (PN->getIncomingBlock(i) != NewBB) 280 OtherPreds.push_back(PN->getIncomingBlock(i)); 281 } else { 282 for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); 283 I != E; ++I) { 284 BasicBlock *P = *I; 285 if (P != NewBB) 286 OtherPreds.push_back(P); 287 } 288 } 289 290 bool NewBBDominatesDestBB = true; 291 292 // Should we update DominatorTree information? 293 if (DT) { 294 DomTreeNode *TINode = DT->getNode(TIBB); 295 296 // The new block is not the immediate dominator for any other nodes, but 297 // TINode is the immediate dominator for the new node. 298 // 299 if (TINode) { // Don't break unreachable code! 300 DomTreeNode *NewBBNode = DT->addNewBlock(NewBB, TIBB); 301 DomTreeNode *DestBBNode = 0; 302 303 // If NewBBDominatesDestBB hasn't been computed yet, do so with DT. 304 if (!OtherPreds.empty()) { 305 DestBBNode = DT->getNode(DestBB); 306 while (!OtherPreds.empty() && NewBBDominatesDestBB) { 307 if (DomTreeNode *OPNode = DT->getNode(OtherPreds.back())) 308 NewBBDominatesDestBB = DT->dominates(DestBBNode, OPNode); 309 OtherPreds.pop_back(); 310 } 311 OtherPreds.clear(); 312 } 313 314 // If NewBBDominatesDestBB, then NewBB dominates DestBB, otherwise it 315 // doesn't dominate anything. 316 if (NewBBDominatesDestBB) { 317 if (!DestBBNode) DestBBNode = DT->getNode(DestBB); 318 DT->changeImmediateDominator(DestBBNode, NewBBNode); 319 } 320 } 321 } 322 323 // Should we update DominanceFrontier information? 324 if (DF) { 325 // If NewBBDominatesDestBB hasn't been computed yet, do so with DF. 326 if (!OtherPreds.empty()) { 327 // FIXME: IMPLEMENT THIS! 328 llvm_unreachable("Requiring domfrontiers but not idom/domtree/domset." 329 " not implemented yet!"); 330 } 331 332 // Since the new block is dominated by its only predecessor TIBB, 333 // it cannot be in any block's dominance frontier. If NewBB dominates 334 // DestBB, its dominance frontier is the same as DestBB's, otherwise it is 335 // just {DestBB}. 336 DominanceFrontier::DomSetType NewDFSet; 337 if (NewBBDominatesDestBB) { 338 DominanceFrontier::iterator I = DF->find(DestBB); 339 if (I != DF->end()) { 340 DF->addBasicBlock(NewBB, I->second); 341 342 if (I->second.count(DestBB)) { 343 // However NewBB's frontier does not include DestBB. 344 DominanceFrontier::iterator NF = DF->find(NewBB); 345 DF->removeFromFrontier(NF, DestBB); 346 } 347 } 348 else 349 DF->addBasicBlock(NewBB, DominanceFrontier::DomSetType()); 350 } else { 351 DominanceFrontier::DomSetType NewDFSet; 352 NewDFSet.insert(DestBB); 353 DF->addBasicBlock(NewBB, NewDFSet); 354 } 355 } 356 357 // Update LoopInfo if it is around. 358 if (LI) { 359 if (Loop *TIL = LI->getLoopFor(TIBB)) { 360 // If one or the other blocks were not in a loop, the new block is not 361 // either, and thus LI doesn't need to be updated. 362 if (Loop *DestLoop = LI->getLoopFor(DestBB)) { 363 if (TIL == DestLoop) { 364 // Both in the same loop, the NewBB joins loop. 365 DestLoop->addBasicBlockToLoop(NewBB, LI->getBase()); 366 } else if (TIL->contains(DestLoop)) { 367 // Edge from an outer loop to an inner loop. Add to the outer loop. 368 TIL->addBasicBlockToLoop(NewBB, LI->getBase()); 369 } else if (DestLoop->contains(TIL)) { 370 // Edge from an inner loop to an outer loop. Add to the outer loop. 371 DestLoop->addBasicBlockToLoop(NewBB, LI->getBase()); 372 } else { 373 // Edge from two loops with no containment relation. Because these 374 // are natural loops, we know that the destination block must be the 375 // header of its loop (adding a branch into a loop elsewhere would 376 // create an irreducible loop). 377 assert(DestLoop->getHeader() == DestBB && 378 "Should not create irreducible loops!"); 379 if (Loop *P = DestLoop->getParentLoop()) 380 P->addBasicBlockToLoop(NewBB, LI->getBase()); 381 } 382 } 383 // If TIBB is in a loop and DestBB is outside of that loop, split the 384 // other exit blocks of the loop that also have predecessors outside 385 // the loop, to maintain a LoopSimplify guarantee. 386 if (!TIL->contains(DestBB) && 387 P->mustPreserveAnalysisID(LoopSimplifyID)) { 388 assert(!TIL->contains(NewBB) && 389 "Split point for loop exit is contained in loop!"); 390 391 // Update LCSSA form in the newly created exit block. 392 if (P->mustPreserveAnalysisID(LCSSAID)) { 393 SmallVector<BasicBlock *, 1> OrigPred; 394 OrigPred.push_back(TIBB); 395 CreatePHIsForSplitLoopExit(OrigPred, NewBB, DestBB); 396 } 397 398 // For each unique exit block... 399 SmallVector<BasicBlock *, 4> ExitBlocks; 400 TIL->getExitBlocks(ExitBlocks); 401 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) { 402 // Collect all the preds that are inside the loop, and note 403 // whether there are any preds outside the loop. 404 SmallVector<BasicBlock *, 4> Preds; 405 bool HasPredOutsideOfLoop = false; 406 BasicBlock *Exit = ExitBlocks[i]; 407 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); 408 I != E; ++I) { 409 BasicBlock *P = *I; 410 if (TIL->contains(P)) 411 Preds.push_back(P); 412 else 413 HasPredOutsideOfLoop = true; 414 } 415 // If there are any preds not in the loop, we'll need to split 416 // the edges. The Preds.empty() check is needed because a block 417 // may appear multiple times in the list. We can't use 418 // getUniqueExitBlocks above because that depends on LoopSimplify 419 // form, which we're in the process of restoring! 420 if (!Preds.empty() && HasPredOutsideOfLoop) { 421 BasicBlock *NewExitBB = 422 SplitBlockPredecessors(Exit, Preds.data(), Preds.size(), 423 "split", P); 424 if (P->mustPreserveAnalysisID(LCSSAID)) 425 CreatePHIsForSplitLoopExit(Preds, NewExitBB, Exit); 426 } 427 } 428 } 429 // LCSSA form was updated above for the case where LoopSimplify is 430 // available, which means that all predecessors of loop exit blocks 431 // are within the loop. Without LoopSimplify form, it would be 432 // necessary to insert a new phi. 433 assert((!P->mustPreserveAnalysisID(LCSSAID) || 434 P->mustPreserveAnalysisID(LoopSimplifyID)) && 435 "SplitCriticalEdge doesn't know how to update LCCSA form " 436 "without LoopSimplify!"); 437 } 438 } 439 440 // Update ProfileInfo if it is around. 441 if (PI) 442 PI->splitEdge(TIBB, DestBB, NewBB, MergeIdenticalEdges); 443 444 return NewBB; 445 } 446