LoopSimplify.cpp revision 0f98e75adff9024dcfe1d2afbfa83625d60ebaa8
1//===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by the LLVM research group and is distributed under 6// the University of Illinois Open Source License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This pass performs several transformations to transform natural loops into a 11// simpler form, which makes subsequent analyses and transformations simpler and 12// more effective. 13// 14// Loop pre-header insertion guarantees that there is a single, non-critical 15// entry edge from outside of the loop to the loop header. This simplifies a 16// number of analyses and transformations, such as LICM. 17// 18// Loop exit-block insertion guarantees that all exit blocks from the loop 19// (blocks which are outside of the loop that have predecessors inside of the 20// loop) only have predecessors from inside of the loop (and are thus dominated 21// by the loop header). This simplifies transformations such as store-sinking 22// that are built into LICM. 23// 24// This pass also guarantees that loops will have exactly one backedge. 25// 26// Note that the simplifycfg pass will clean up blocks which are split out but 27// end up being unnecessary, so usage of this pass should not pessimize 28// generated code. 29// 30// This pass obviously modifies the CFG, but updates loop information and 31// dominator information. 32// 33//===----------------------------------------------------------------------===// 34 35#include "llvm/Transforms/Scalar.h" 36#include "llvm/Function.h" 37#include "llvm/iTerminators.h" 38#include "llvm/iPHINode.h" 39#include "llvm/Constant.h" 40#include "llvm/Analysis/Dominators.h" 41#include "llvm/Analysis/LoopInfo.h" 42#include "llvm/Support/CFG.h" 43#include "Support/SetOperations.h" 44#include "Support/Statistic.h" 45#include "Support/DepthFirstIterator.h" 46using namespace llvm; 47 48namespace { 49 Statistic<> 50 NumInserted("loopsimplify", "Number of pre-header or exit blocks inserted"); 51 52 struct LoopSimplify : public FunctionPass { 53 virtual bool runOnFunction(Function &F); 54 55 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 56 // We need loop information to identify the loops... 57 AU.addRequired<LoopInfo>(); 58 AU.addRequired<DominatorSet>(); 59 60 AU.addPreserved<LoopInfo>(); 61 AU.addPreserved<DominatorSet>(); 62 AU.addPreserved<ImmediateDominators>(); 63 AU.addPreserved<DominatorTree>(); 64 AU.addPreserved<DominanceFrontier>(); 65 AU.addPreservedID(BreakCriticalEdgesID); // No crit edges added.... 66 } 67 private: 68 bool ProcessLoop(Loop *L); 69 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix, 70 const std::vector<BasicBlock*> &Preds); 71 void RewriteLoopExitBlock(Loop *L, BasicBlock *Exit); 72 void InsertPreheaderForLoop(Loop *L); 73 void InsertUniqueBackedgeBlock(Loop *L); 74 75 void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB, 76 std::vector<BasicBlock*> &PredBlocks); 77 }; 78 79 RegisterOpt<LoopSimplify> 80 X("loopsimplify", "Canonicalize natural loops", true); 81} 82 83// Publically exposed interface to pass... 84const PassInfo *llvm::LoopSimplifyID = X.getPassInfo(); 85Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); } 86 87/// runOnFunction - Run down all loops in the CFG (recursively, but we could do 88/// it in any convenient order) inserting preheaders... 89/// 90bool LoopSimplify::runOnFunction(Function &F) { 91 bool Changed = false; 92 LoopInfo &LI = getAnalysis<LoopInfo>(); 93 94 for (unsigned i = 0, e = LI.getTopLevelLoops().size(); i != e; ++i) 95 Changed |= ProcessLoop(LI.getTopLevelLoops()[i]); 96 97 return Changed; 98} 99 100 101/// ProcessLoop - Walk the loop structure in depth first order, ensuring that 102/// all loops have preheaders. 103/// 104bool LoopSimplify::ProcessLoop(Loop *L) { 105 bool Changed = false; 106 107 // Does the loop already have a preheader? If so, don't modify the loop... 108 if (L->getLoopPreheader() == 0) { 109 InsertPreheaderForLoop(L); 110 NumInserted++; 111 Changed = true; 112 } 113 114 // Next, check to make sure that all exit nodes of the loop only have 115 // predecessors that are inside of the loop. This check guarantees that the 116 // loop preheader/header will dominate the exit blocks. If the exit block has 117 // predecessors from outside of the loop, split the edge now. 118 for (unsigned i = 0, e = L->getExitBlocks().size(); i != e; ++i) { 119 BasicBlock *ExitBlock = L->getExitBlocks()[i]; 120 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock); 121 PI != PE; ++PI) 122 if (!L->contains(*PI)) { 123 RewriteLoopExitBlock(L, ExitBlock); 124 NumInserted++; 125 Changed = true; 126 break; 127 } 128 } 129 130 // The preheader may have more than two predecessors at this point (from the 131 // preheader and from the backedges). To simplify the loop more, insert an 132 // extra back-edge block in the loop so that there is exactly one backedge. 133 if (L->getNumBackEdges() != 1) { 134 InsertUniqueBackedgeBlock(L); 135 NumInserted++; 136 Changed = true; 137 } 138 139 const std::vector<Loop*> &SubLoops = L->getSubLoops(); 140 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i) 141 Changed |= ProcessLoop(SubLoops[i]); 142 return Changed; 143} 144 145/// SplitBlockPredecessors - Split the specified block into two blocks. We want 146/// to move the predecessors specified in the Preds list to point to the new 147/// block, leaving the remaining predecessors pointing to BB. This method 148/// updates the SSA PHINode's, but no other analyses. 149/// 150BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB, 151 const char *Suffix, 152 const std::vector<BasicBlock*> &Preds) { 153 154 // Create new basic block, insert right before the original block... 155 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB); 156 157 // The preheader first gets an unconditional branch to the loop header... 158 BranchInst *BI = new BranchInst(BB, NewBB); 159 160 // For every PHI node in the block, insert a PHI node into NewBB where the 161 // incoming values from the out of loop edges are moved to NewBB. We have two 162 // possible cases here. If the loop is dead, we just insert dummy entries 163 // into the PHI nodes for the new edge. If the loop is not dead, we move the 164 // incoming edges in BB into new PHI nodes in NewBB. 165 // 166 if (!Preds.empty()) { // Is the loop not obviously dead? 167 // Check to see if the values being merged into the new block need PHI 168 // nodes. If so, insert them. 169 for (BasicBlock::iterator I = BB->begin(); 170 PHINode *PN = dyn_cast<PHINode>(I); ++I) { 171 172 // Check to see if all of the values coming in are the same. If so, we 173 // don't need to create a new PHI node. 174 Value *InVal = PN->getIncomingValueForBlock(Preds[0]); 175 for (unsigned i = 1, e = Preds.size(); i != e; ++i) 176 if (InVal != PN->getIncomingValueForBlock(Preds[i])) { 177 InVal = 0; 178 break; 179 } 180 181 // If the values coming into the block are not the same, we need a PHI. 182 if (InVal == 0) { 183 // Create the new PHI node, insert it into NewBB at the end of the block 184 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI); 185 186 // Move all of the edges from blocks outside the loop to the new PHI 187 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 188 Value *V = PN->removeIncomingValue(Preds[i]); 189 NewPHI->addIncoming(V, Preds[i]); 190 } 191 InVal = NewPHI; 192 } else { 193 // Remove all of the edges coming into the PHI nodes from outside of the 194 // block. 195 for (unsigned i = 0, e = Preds.size(); i != e; ++i) 196 PN->removeIncomingValue(Preds[i], false); 197 } 198 199 // Add an incoming value to the PHI node in the loop for the preheader 200 // edge. 201 PN->addIncoming(InVal, NewBB); 202 } 203 204 // Now that the PHI nodes are updated, actually move the edges from 205 // Preds to point to NewBB instead of BB. 206 // 207 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 208 TerminatorInst *TI = Preds[i]->getTerminator(); 209 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s) 210 if (TI->getSuccessor(s) == BB) 211 TI->setSuccessor(s, NewBB); 212 } 213 214 } else { // Otherwise the loop is dead... 215 for (BasicBlock::iterator I = BB->begin(); 216 PHINode *PN = dyn_cast<PHINode>(I); ++I) 217 // Insert dummy values as the incoming value... 218 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB); 219 } 220 return NewBB; 221} 222 223// ChangeExitBlock - This recursive function is used to change any exit blocks 224// that use OldExit to use NewExit instead. This is recursive because children 225// may need to be processed as well. 226// 227static void ChangeExitBlock(Loop *L, BasicBlock *OldExit, BasicBlock *NewExit) { 228 if (L->hasExitBlock(OldExit)) { 229 L->changeExitBlock(OldExit, NewExit); 230 const std::vector<Loop*> &SubLoops = L->getSubLoops(); 231 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i) 232 ChangeExitBlock(SubLoops[i], OldExit, NewExit); 233 } 234} 235 236 237/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a 238/// preheader, this method is called to insert one. This method has two phases: 239/// preheader insertion and analysis updating. 240/// 241void LoopSimplify::InsertPreheaderForLoop(Loop *L) { 242 BasicBlock *Header = L->getHeader(); 243 244 // Compute the set of predecessors of the loop that are not in the loop. 245 std::vector<BasicBlock*> OutsideBlocks; 246 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header); 247 PI != PE; ++PI) 248 if (!L->contains(*PI)) // Coming in from outside the loop? 249 OutsideBlocks.push_back(*PI); // Keep track of it... 250 251 // Split out the loop pre-header 252 BasicBlock *NewBB = 253 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks); 254 255 //===--------------------------------------------------------------------===// 256 // Update analysis results now that we have performed the transformation 257 // 258 259 // We know that we have loop information to update... update it now. 260 if (Loop *Parent = L->getParentLoop()) 261 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>()); 262 263 // If the header for the loop used to be an exit node for another loop, then 264 // we need to update this to know that the loop-preheader is now the exit 265 // node. Note that the only loop that could have our header as an exit node 266 // is a sibling loop, ie, one with the same parent loop, or one if it's 267 // children. 268 // 269 const std::vector<Loop*> *ParentSubLoops; 270 if (Loop *Parent = L->getParentLoop()) 271 ParentSubLoops = &Parent->getSubLoops(); 272 else // Must check top-level loops... 273 ParentSubLoops = &getAnalysis<LoopInfo>().getTopLevelLoops(); 274 275 // Loop over all sibling loops, performing the substitution (recursively to 276 // include child loops)... 277 for (unsigned i = 0, e = ParentSubLoops->size(); i != e; ++i) 278 ChangeExitBlock((*ParentSubLoops)[i], Header, NewBB); 279 280 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info 281 { 282 // The blocks that dominate NewBB are the blocks that dominate Header, 283 // minus Header, plus NewBB. 284 DominatorSet::DomSetType DomSet = DS.getDominators(Header); 285 DomSet.insert(NewBB); // We dominate ourself 286 DomSet.erase(Header); // Header does not dominate us... 287 DS.addBasicBlock(NewBB, DomSet); 288 289 // The newly created basic block dominates all nodes dominated by Header. 290 for (Function::iterator I = Header->getParent()->begin(), 291 E = Header->getParent()->end(); I != E; ++I) 292 if (DS.dominates(Header, I)) 293 DS.addDominator(I, NewBB); 294 } 295 296 // Update immediate dominator information if we have it... 297 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) { 298 // Whatever i-dominated the header node now immediately dominates NewBB 299 ID->addNewBlock(NewBB, ID->get(Header)); 300 301 // The preheader now is the immediate dominator for the header node... 302 ID->setImmediateDominator(Header, NewBB); 303 } 304 305 // Update DominatorTree information if it is active. 306 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) { 307 // The immediate dominator of the preheader is the immediate dominator of 308 // the old header. 309 // 310 DominatorTree::Node *HeaderNode = DT->getNode(Header); 311 DominatorTree::Node *PHNode = DT->createNewNode(NewBB, 312 HeaderNode->getIDom()); 313 314 // Change the header node so that PNHode is the new immediate dominator 315 DT->changeImmediateDominator(HeaderNode, PHNode); 316 } 317 318 // Update dominance frontier information... 319 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) { 320 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates 321 // everything that Header does, and it strictly dominates Header in 322 // addition. 323 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?"); 324 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second; 325 NewDFSet.erase(Header); 326 DF->addBasicBlock(NewBB, NewDFSet); 327 328 // Now we must loop over all of the dominance frontiers in the function, 329 // replacing occurrences of Header with NewBB in some cases. If a block 330 // dominates a (now) predecessor of NewBB, but did not strictly dominate 331 // Header, it will have Header in it's DF set, but should now have NewBB in 332 // its set. 333 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) { 334 // Get all of the dominators of the predecessor... 335 const DominatorSet::DomSetType &PredDoms = 336 DS.getDominators(OutsideBlocks[i]); 337 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(), 338 PDE = PredDoms.end(); PDI != PDE; ++PDI) { 339 BasicBlock *PredDom = *PDI; 340 // If the loop header is in DF(PredDom), then PredDom didn't dominate 341 // the header but did dominate a predecessor outside of the loop. Now 342 // we change this entry to include the preheader in the DF instead of 343 // the header. 344 DominanceFrontier::iterator DFI = DF->find(PredDom); 345 assert(DFI != DF->end() && "No dominance frontier for node?"); 346 if (DFI->second.count(Header)) { 347 DF->removeFromFrontier(DFI, Header); 348 DF->addToFrontier(DFI, NewBB); 349 } 350 } 351 } 352 } 353} 354 355void LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) { 356 DominatorSet &DS = getAnalysis<DominatorSet>(); 357 assert(std::find(L->getExitBlocks().begin(), L->getExitBlocks().end(), Exit) 358 != L->getExitBlocks().end() && "Not a current exit block!"); 359 360 std::vector<BasicBlock*> LoopBlocks; 361 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I) 362 if (L->contains(*I)) 363 LoopBlocks.push_back(*I); 364 365 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?"); 366 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks); 367 368 // Update Loop Information - we know that the new block will be in the parent 369 // loop of L. 370 if (Loop *Parent = L->getParentLoop()) 371 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>()); 372 373 // Replace any instances of Exit with NewBB in this and any nested loops... 374 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I) 375 if (I->hasExitBlock(Exit)) 376 I->changeExitBlock(Exit, NewBB); // Update exit block information 377 378 // Update dominator information (set, immdom, domtree, and domfrontier) 379 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks); 380} 381 382/// InsertUniqueBackedgeBlock - This method is called when the specified loop 383/// has more than one backedge in it. If this occurs, revector all of these 384/// backedges to target a new basic block and have that block branch to the loop 385/// header. This ensures that loops have exactly one backedge. 386/// 387void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) { 388 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!"); 389 390 // Get information about the loop 391 BasicBlock *Preheader = L->getLoopPreheader(); 392 BasicBlock *Header = L->getHeader(); 393 Function *F = Header->getParent(); 394 395 // Figure out which basic blocks contain back-edges to the loop header. 396 std::vector<BasicBlock*> BackedgeBlocks; 397 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I) 398 if (*I != Preheader) BackedgeBlocks.push_back(*I); 399 400 // Create and insert the new backedge block... 401 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F); 402 BranchInst *BETerminator = new BranchInst(Header, BEBlock); 403 404 // Move the new backedge block to right after the last backedge block. 405 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos; 406 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock); 407 408 // Now that the block has been inserted into the function, create PHI nodes in 409 // the backedge block which correspond to any PHI nodes in the header block. 410 for (BasicBlock::iterator I = Header->begin(); 411 PHINode *PN = dyn_cast<PHINode>(I); ++I) { 412 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be", 413 BETerminator); 414 NewPN->op_reserve(2*BackedgeBlocks.size()); 415 416 // Loop over the PHI node, moving all entries except the one for the 417 // preheader over to the new PHI node. 418 unsigned PreheaderIdx = ~0U; 419 bool HasUniqueIncomingValue = true; 420 Value *UniqueValue = 0; 421 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 422 BasicBlock *IBB = PN->getIncomingBlock(i); 423 Value *IV = PN->getIncomingValue(i); 424 if (IBB == Preheader) { 425 PreheaderIdx = i; 426 } else { 427 NewPN->addIncoming(IV, IBB); 428 if (HasUniqueIncomingValue) { 429 if (UniqueValue == 0) 430 UniqueValue = IV; 431 else if (UniqueValue != IV) 432 HasUniqueIncomingValue = false; 433 } 434 } 435 } 436 437 // Delete all of the incoming values from the old PN except the preheader's 438 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??"); 439 if (PreheaderIdx != 0) { 440 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx)); 441 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx)); 442 } 443 PN->op_erase(PN->op_begin()+2, PN->op_end()); 444 445 // Finally, add the newly constructed PHI node as the entry for the BEBlock. 446 PN->addIncoming(NewPN, BEBlock); 447 448 // As an optimization, if all incoming values in the new PhiNode (which is a 449 // subset of the incoming values of the old PHI node) have the same value, 450 // eliminate the PHI Node. 451 if (HasUniqueIncomingValue) { 452 NewPN->replaceAllUsesWith(UniqueValue); 453 BEBlock->getInstList().erase(NewPN); 454 } 455 } 456 457 // Now that all of the PHI nodes have been inserted and adjusted, modify the 458 // backedge blocks to just to the BEBlock instead of the header. 459 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) { 460 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator(); 461 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op) 462 if (TI->getSuccessor(Op) == Header) 463 TI->setSuccessor(Op, BEBlock); 464 } 465 466 //===--- Update all analyses which we must preserve now -----------------===// 467 468 // Update Loop Information - we know that this block is now in the current 469 // loop and all parent loops. 470 L->addBasicBlockToLoop(BEBlock, getAnalysis<LoopInfo>()); 471 472 // Replace any instances of Exit with NewBB in this and any nested loops... 473 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I) 474 if (I->hasExitBlock(Header)) 475 I->changeExitBlock(Header, BEBlock); // Update exit block information 476 477 // Update dominator information (set, immdom, domtree, and domfrontier) 478 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks); 479} 480 481/// UpdateDomInfoForRevectoredPreds - This method is used to update the four 482/// different kinds of dominator information (dominator sets, immediate 483/// dominators, dominator trees, and dominance frontiers) after a new block has 484/// been added to the CFG. 485/// 486/// This only supports the case when an existing block (known as "Exit"), had 487/// some of its predecessors factored into a new basic block. This 488/// transformation inserts a new basic block ("NewBB"), with a single 489/// unconditional branch to Exit, and moves some predecessors of "Exit" to now 490/// branch to NewBB. These predecessors are listed in PredBlocks, even though 491/// they are the same as pred_begin(NewBB)/pred_end(NewBB). 492/// 493void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB, 494 std::vector<BasicBlock*> &PredBlocks) { 495 assert(succ_begin(NewBB) != succ_end(NewBB) && 496 ++succ_begin(NewBB) == succ_end(NewBB) && 497 "NewBB should have a single successor!"); 498 DominatorSet &DS = getAnalysis<DominatorSet>(); 499 500 // Update dominator information... The blocks that dominate NewBB are the 501 // intersection of the dominators of predecessors, plus the block itself. 502 // The newly created basic block does not dominate anything except itself. 503 // 504 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(PredBlocks[0]); 505 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i) 506 set_intersect(NewBBDomSet, DS.getDominators(PredBlocks[i])); 507 NewBBDomSet.insert(NewBB); // All blocks dominate themselves... 508 DS.addBasicBlock(NewBB, NewBBDomSet); 509 510 // Update immediate dominator information if we have it... 511 BasicBlock *NewBBIDom = 0; 512 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) { 513 // This block does not strictly dominate anything, so it is not an immediate 514 // dominator. To find the immediate dominator of the new exit node, we 515 // trace up the immediate dominators of a predecessor until we find a basic 516 // block that dominates the exit block. 517 // 518 BasicBlock *Dom = PredBlocks[0]; // Some random predecessor... 519 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator... 520 assert(Dom != 0 && "No shared dominator found???"); 521 Dom = ID->get(Dom); 522 } 523 524 // Set the immediate dominator now... 525 ID->addNewBlock(NewBB, Dom); 526 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info... 527 } 528 529 // Update DominatorTree information if it is active. 530 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) { 531 // NewBB doesn't dominate anything, so just create a node and link it into 532 // its immediate dominator. If we don't have ImmediateDominator info 533 // around, calculate the idom as above. 534 DominatorTree::Node *NewBBIDomNode; 535 if (NewBBIDom) { 536 NewBBIDomNode = DT->getNode(NewBBIDom); 537 } else { 538 NewBBIDomNode = DT->getNode(PredBlocks[0]); // Random pred 539 while (!NewBBDomSet.count(NewBBIDomNode->getBlock())) { 540 NewBBIDomNode = NewBBIDomNode->getIDom(); 541 assert(NewBBIDomNode && "No shared dominator found??"); 542 } 543 } 544 545 // Create the new dominator tree node... 546 DT->createNewNode(NewBB, NewBBIDomNode); 547 } 548 549 // Update dominance frontier information... 550 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) { 551 // DF(NewBB) is {Exit} because NewBB does not strictly dominate Exit, but it 552 // does dominate itself (and there is an edge (NewBB -> Exit)). Exit is the 553 // single successor of NewBB. 554 DominanceFrontier::DomSetType NewDFSet; 555 BasicBlock *Exit = *succ_begin(NewBB); 556 NewDFSet.insert(Exit); 557 DF->addBasicBlock(NewBB, NewDFSet); 558 559 // Now we must loop over all of the dominance frontiers in the function, 560 // replacing occurrences of Exit with NewBB in some cases. All blocks that 561 // dominate a block in PredBlocks and contained Exit in their dominance 562 // frontier must be updated to contain NewBB instead. This only occurs if 563 // there is more than one block in PredBlocks. 564 // 565 if (PredBlocks.size() > 1) { 566 for (unsigned i = 0, e = PredBlocks.size(); i != e; ++i) { 567 BasicBlock *Pred = PredBlocks[i]; 568 // Get all of the dominators of the predecessor... 569 const DominatorSet::DomSetType &PredDoms = DS.getDominators(Pred); 570 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(), 571 PDE = PredDoms.end(); PDI != PDE; ++PDI) { 572 BasicBlock *PredDom = *PDI; 573 574 // If the Exit node is in DF(PredDom), then PredDom didn't dominate 575 // Exit but did dominate a predecessor of it. Now we change this 576 // entry to include NewBB in the DF instead of Exit. 577 DominanceFrontier::iterator DFI = DF->find(PredDom); 578 assert(DFI != DF->end() && "No dominance frontier for node?"); 579 if (DFI->second.count(Exit)) { 580 DF->removeFromFrontier(DFI, Exit); 581 DF->addToFrontier(DFI, NewBB); 582 } 583 } 584 } 585 } 586 } 587} 588 589