LLVM API Documentation
00001 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements Loop Rotation Pass. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "llvm/Transforms/Scalar.h" 00015 #include "llvm/ADT/Statistic.h" 00016 #include "llvm/Analysis/AssumptionTracker.h" 00017 #include "llvm/Analysis/CodeMetrics.h" 00018 #include "llvm/Analysis/InstructionSimplify.h" 00019 #include "llvm/Analysis/LoopPass.h" 00020 #include "llvm/Analysis/ScalarEvolution.h" 00021 #include "llvm/Analysis/TargetTransformInfo.h" 00022 #include "llvm/Analysis/ValueTracking.h" 00023 #include "llvm/IR/CFG.h" 00024 #include "llvm/IR/Dominators.h" 00025 #include "llvm/IR/Function.h" 00026 #include "llvm/IR/IntrinsicInst.h" 00027 #include "llvm/Support/CommandLine.h" 00028 #include "llvm/Support/Debug.h" 00029 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 00030 #include "llvm/Transforms/Utils/Local.h" 00031 #include "llvm/Transforms/Utils/SSAUpdater.h" 00032 #include "llvm/Transforms/Utils/ValueMapper.h" 00033 using namespace llvm; 00034 00035 #define DEBUG_TYPE "loop-rotate" 00036 00037 static cl::opt<unsigned> 00038 DefaultRotationThreshold("rotation-max-header-size", cl::init(16), cl::Hidden, 00039 cl::desc("The default maximum header size for automatic loop rotation")); 00040 00041 STATISTIC(NumRotated, "Number of loops rotated"); 00042 namespace { 00043 00044 class LoopRotate : public LoopPass { 00045 public: 00046 static char ID; // Pass ID, replacement for typeid 00047 LoopRotate(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) { 00048 initializeLoopRotatePass(*PassRegistry::getPassRegistry()); 00049 if (SpecifiedMaxHeaderSize == -1) 00050 MaxHeaderSize = DefaultRotationThreshold; 00051 else 00052 MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize); 00053 } 00054 00055 // LCSSA form makes instruction renaming easier. 00056 void getAnalysisUsage(AnalysisUsage &AU) const override { 00057 AU.addRequired<AssumptionTracker>(); 00058 AU.addPreserved<DominatorTreeWrapperPass>(); 00059 AU.addRequired<LoopInfo>(); 00060 AU.addPreserved<LoopInfo>(); 00061 AU.addRequiredID(LoopSimplifyID); 00062 AU.addPreservedID(LoopSimplifyID); 00063 AU.addRequiredID(LCSSAID); 00064 AU.addPreservedID(LCSSAID); 00065 AU.addPreserved<ScalarEvolution>(); 00066 AU.addRequired<TargetTransformInfo>(); 00067 } 00068 00069 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 00070 bool simplifyLoopLatch(Loop *L); 00071 bool rotateLoop(Loop *L, bool SimplifiedLatch); 00072 00073 private: 00074 unsigned MaxHeaderSize; 00075 LoopInfo *LI; 00076 const TargetTransformInfo *TTI; 00077 AssumptionTracker *AT; 00078 }; 00079 } 00080 00081 char LoopRotate::ID = 0; 00082 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false) 00083 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo) 00084 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker) 00085 INITIALIZE_PASS_DEPENDENCY(LoopInfo) 00086 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 00087 INITIALIZE_PASS_DEPENDENCY(LCSSA) 00088 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false) 00089 00090 Pass *llvm::createLoopRotatePass(int MaxHeaderSize) { 00091 return new LoopRotate(MaxHeaderSize); 00092 } 00093 00094 /// Rotate Loop L as many times as possible. Return true if 00095 /// the loop is rotated at least once. 00096 bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) { 00097 if (skipOptnoneFunction(L)) 00098 return false; 00099 00100 // Save the loop metadata. 00101 MDNode *LoopMD = L->getLoopID(); 00102 00103 LI = &getAnalysis<LoopInfo>(); 00104 TTI = &getAnalysis<TargetTransformInfo>(); 00105 AT = &getAnalysis<AssumptionTracker>(); 00106 00107 // Simplify the loop latch before attempting to rotate the header 00108 // upward. Rotation may not be needed if the loop tail can be folded into the 00109 // loop exit. 00110 bool SimplifiedLatch = simplifyLoopLatch(L); 00111 00112 // One loop can be rotated multiple times. 00113 bool MadeChange = false; 00114 while (rotateLoop(L, SimplifiedLatch)) { 00115 MadeChange = true; 00116 SimplifiedLatch = false; 00117 } 00118 00119 // Restore the loop metadata. 00120 // NB! We presume LoopRotation DOESN'T ADD its own metadata. 00121 if ((MadeChange || SimplifiedLatch) && LoopMD) 00122 L->setLoopID(LoopMD); 00123 00124 return MadeChange; 00125 } 00126 00127 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the 00128 /// old header into the preheader. If there were uses of the values produced by 00129 /// these instruction that were outside of the loop, we have to insert PHI nodes 00130 /// to merge the two values. Do this now. 00131 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader, 00132 BasicBlock *OrigPreheader, 00133 ValueToValueMapTy &ValueMap) { 00134 // Remove PHI node entries that are no longer live. 00135 BasicBlock::iterator I, E = OrigHeader->end(); 00136 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I) 00137 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader)); 00138 00139 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes 00140 // as necessary. 00141 SSAUpdater SSA; 00142 for (I = OrigHeader->begin(); I != E; ++I) { 00143 Value *OrigHeaderVal = I; 00144 00145 // If there are no uses of the value (e.g. because it returns void), there 00146 // is nothing to rewrite. 00147 if (OrigHeaderVal->use_empty()) 00148 continue; 00149 00150 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal]; 00151 00152 // The value now exits in two versions: the initial value in the preheader 00153 // and the loop "next" value in the original header. 00154 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName()); 00155 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal); 00156 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal); 00157 00158 // Visit each use of the OrigHeader instruction. 00159 for (Value::use_iterator UI = OrigHeaderVal->use_begin(), 00160 UE = OrigHeaderVal->use_end(); UI != UE; ) { 00161 // Grab the use before incrementing the iterator. 00162 Use &U = *UI; 00163 00164 // Increment the iterator before removing the use from the list. 00165 ++UI; 00166 00167 // SSAUpdater can't handle a non-PHI use in the same block as an 00168 // earlier def. We can easily handle those cases manually. 00169 Instruction *UserInst = cast<Instruction>(U.getUser()); 00170 if (!isa<PHINode>(UserInst)) { 00171 BasicBlock *UserBB = UserInst->getParent(); 00172 00173 // The original users in the OrigHeader are already using the 00174 // original definitions. 00175 if (UserBB == OrigHeader) 00176 continue; 00177 00178 // Users in the OrigPreHeader need to use the value to which the 00179 // original definitions are mapped. 00180 if (UserBB == OrigPreheader) { 00181 U = OrigPreHeaderVal; 00182 continue; 00183 } 00184 } 00185 00186 // Anything else can be handled by SSAUpdater. 00187 SSA.RewriteUse(U); 00188 } 00189 } 00190 } 00191 00192 /// Determine whether the instructions in this range may be safely and cheaply 00193 /// speculated. This is not an important enough situation to develop complex 00194 /// heuristics. We handle a single arithmetic instruction along with any type 00195 /// conversions. 00196 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin, 00197 BasicBlock::iterator End) { 00198 bool seenIncrement = false; 00199 for (BasicBlock::iterator I = Begin; I != End; ++I) { 00200 00201 if (!isSafeToSpeculativelyExecute(I)) 00202 return false; 00203 00204 if (isa<DbgInfoIntrinsic>(I)) 00205 continue; 00206 00207 switch (I->getOpcode()) { 00208 default: 00209 return false; 00210 case Instruction::GetElementPtr: 00211 // GEPs are cheap if all indices are constant. 00212 if (!cast<GEPOperator>(I)->hasAllConstantIndices()) 00213 return false; 00214 // fall-thru to increment case 00215 case Instruction::Add: 00216 case Instruction::Sub: 00217 case Instruction::And: 00218 case Instruction::Or: 00219 case Instruction::Xor: 00220 case Instruction::Shl: 00221 case Instruction::LShr: 00222 case Instruction::AShr: 00223 if (seenIncrement) 00224 return false; 00225 seenIncrement = true; 00226 break; 00227 case Instruction::Trunc: 00228 case Instruction::ZExt: 00229 case Instruction::SExt: 00230 // ignore type conversions 00231 break; 00232 } 00233 } 00234 return true; 00235 } 00236 00237 /// Fold the loop tail into the loop exit by speculating the loop tail 00238 /// instructions. Typically, this is a single post-increment. In the case of a 00239 /// simple 2-block loop, hoisting the increment can be much better than 00240 /// duplicating the entire loop header. In the case of loops with early exits, 00241 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in 00242 /// canonical form so downstream passes can handle it. 00243 /// 00244 /// I don't believe this invalidates SCEV. 00245 bool LoopRotate::simplifyLoopLatch(Loop *L) { 00246 BasicBlock *Latch = L->getLoopLatch(); 00247 if (!Latch || Latch->hasAddressTaken()) 00248 return false; 00249 00250 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator()); 00251 if (!Jmp || !Jmp->isUnconditional()) 00252 return false; 00253 00254 BasicBlock *LastExit = Latch->getSinglePredecessor(); 00255 if (!LastExit || !L->isLoopExiting(LastExit)) 00256 return false; 00257 00258 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator()); 00259 if (!BI) 00260 return false; 00261 00262 if (!shouldSpeculateInstrs(Latch->begin(), Jmp)) 00263 return false; 00264 00265 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into " 00266 << LastExit->getName() << "\n"); 00267 00268 // Hoist the instructions from Latch into LastExit. 00269 LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp); 00270 00271 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1; 00272 BasicBlock *Header = Jmp->getSuccessor(0); 00273 assert(Header == L->getHeader() && "expected a backward branch"); 00274 00275 // Remove Latch from the CFG so that LastExit becomes the new Latch. 00276 BI->setSuccessor(FallThruPath, Header); 00277 Latch->replaceSuccessorsPhiUsesWith(LastExit); 00278 Jmp->eraseFromParent(); 00279 00280 // Nuke the Latch block. 00281 assert(Latch->empty() && "unable to evacuate Latch"); 00282 LI->removeBlock(Latch); 00283 if (DominatorTreeWrapperPass *DTWP = 00284 getAnalysisIfAvailable<DominatorTreeWrapperPass>()) 00285 DTWP->getDomTree().eraseNode(Latch); 00286 Latch->eraseFromParent(); 00287 return true; 00288 } 00289 00290 /// Rotate loop LP. Return true if the loop is rotated. 00291 /// 00292 /// \param SimplifiedLatch is true if the latch was just folded into the final 00293 /// loop exit. In this case we may want to rotate even though the new latch is 00294 /// now an exiting branch. This rotation would have happened had the latch not 00295 /// been simplified. However, if SimplifiedLatch is false, then we avoid 00296 /// rotating loops in which the latch exits to avoid excessive or endless 00297 /// rotation. LoopRotate should be repeatable and converge to a canonical 00298 /// form. This property is satisfied because simplifying the loop latch can only 00299 /// happen once across multiple invocations of the LoopRotate pass. 00300 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) { 00301 // If the loop has only one block then there is not much to rotate. 00302 if (L->getBlocks().size() == 1) 00303 return false; 00304 00305 BasicBlock *OrigHeader = L->getHeader(); 00306 BasicBlock *OrigLatch = L->getLoopLatch(); 00307 00308 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator()); 00309 if (!BI || BI->isUnconditional()) 00310 return false; 00311 00312 // If the loop header is not one of the loop exiting blocks then 00313 // either this loop is already rotated or it is not 00314 // suitable for loop rotation transformations. 00315 if (!L->isLoopExiting(OrigHeader)) 00316 return false; 00317 00318 // If the loop latch already contains a branch that leaves the loop then the 00319 // loop is already rotated. 00320 if (!OrigLatch) 00321 return false; 00322 00323 // Rotate if either the loop latch does *not* exit the loop, or if the loop 00324 // latch was just simplified. 00325 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch) 00326 return false; 00327 00328 // Check size of original header and reject loop if it is very big or we can't 00329 // duplicate blocks inside it. 00330 { 00331 SmallPtrSet<const Value *, 32> EphValues; 00332 CodeMetrics::collectEphemeralValues(L, AT, EphValues); 00333 00334 CodeMetrics Metrics; 00335 Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues); 00336 if (Metrics.notDuplicatable) { 00337 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable" 00338 << " instructions: "; L->dump()); 00339 return false; 00340 } 00341 if (Metrics.NumInsts > MaxHeaderSize) 00342 return false; 00343 } 00344 00345 // Now, this loop is suitable for rotation. 00346 BasicBlock *OrigPreheader = L->getLoopPreheader(); 00347 00348 // If the loop could not be converted to canonical form, it must have an 00349 // indirectbr in it, just give up. 00350 if (!OrigPreheader) 00351 return false; 00352 00353 // Anything ScalarEvolution may know about this loop or the PHI nodes 00354 // in its header will soon be invalidated. 00355 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>()) 00356 SE->forgetLoop(L); 00357 00358 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump()); 00359 00360 // Find new Loop header. NewHeader is a Header's one and only successor 00361 // that is inside loop. Header's other successor is outside the 00362 // loop. Otherwise loop is not suitable for rotation. 00363 BasicBlock *Exit = BI->getSuccessor(0); 00364 BasicBlock *NewHeader = BI->getSuccessor(1); 00365 if (L->contains(Exit)) 00366 std::swap(Exit, NewHeader); 00367 assert(NewHeader && "Unable to determine new loop header"); 00368 assert(L->contains(NewHeader) && !L->contains(Exit) && 00369 "Unable to determine loop header and exit blocks"); 00370 00371 // This code assumes that the new header has exactly one predecessor. 00372 // Remove any single-entry PHI nodes in it. 00373 assert(NewHeader->getSinglePredecessor() && 00374 "New header doesn't have one pred!"); 00375 FoldSingleEntryPHINodes(NewHeader); 00376 00377 // Begin by walking OrigHeader and populating ValueMap with an entry for 00378 // each Instruction. 00379 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end(); 00380 ValueToValueMapTy ValueMap; 00381 00382 // For PHI nodes, the value available in OldPreHeader is just the 00383 // incoming value from OldPreHeader. 00384 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I) 00385 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader); 00386 00387 // For the rest of the instructions, either hoist to the OrigPreheader if 00388 // possible or create a clone in the OldPreHeader if not. 00389 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator(); 00390 while (I != E) { 00391 Instruction *Inst = I++; 00392 00393 // If the instruction's operands are invariant and it doesn't read or write 00394 // memory, then it is safe to hoist. Doing this doesn't change the order of 00395 // execution in the preheader, but does prevent the instruction from 00396 // executing in each iteration of the loop. This means it is safe to hoist 00397 // something that might trap, but isn't safe to hoist something that reads 00398 // memory (without proving that the loop doesn't write). 00399 if (L->hasLoopInvariantOperands(Inst) && 00400 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() && 00401 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) && 00402 !isa<AllocaInst>(Inst)) { 00403 Inst->moveBefore(LoopEntryBranch); 00404 continue; 00405 } 00406 00407 // Otherwise, create a duplicate of the instruction. 00408 Instruction *C = Inst->clone(); 00409 00410 // Eagerly remap the operands of the instruction. 00411 RemapInstruction(C, ValueMap, 00412 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries); 00413 00414 // With the operands remapped, see if the instruction constant folds or is 00415 // otherwise simplifyable. This commonly occurs because the entry from PHI 00416 // nodes allows icmps and other instructions to fold. 00417 // FIXME: Provide DL, TLI, DT, AT to SimplifyInstruction. 00418 Value *V = SimplifyInstruction(C); 00419 if (V && LI->replacementPreservesLCSSAForm(C, V)) { 00420 // If so, then delete the temporary instruction and stick the folded value 00421 // in the map. 00422 delete C; 00423 ValueMap[Inst] = V; 00424 } else { 00425 // Otherwise, stick the new instruction into the new block! 00426 C->setName(Inst->getName()); 00427 C->insertBefore(LoopEntryBranch); 00428 ValueMap[Inst] = C; 00429 } 00430 } 00431 00432 // Along with all the other instructions, we just cloned OrigHeader's 00433 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's 00434 // successors by duplicating their incoming values for OrigHeader. 00435 TerminatorInst *TI = OrigHeader->getTerminator(); 00436 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 00437 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin(); 00438 PHINode *PN = dyn_cast<PHINode>(BI); ++BI) 00439 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader); 00440 00441 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove 00442 // OrigPreHeader's old terminator (the original branch into the loop), and 00443 // remove the corresponding incoming values from the PHI nodes in OrigHeader. 00444 LoopEntryBranch->eraseFromParent(); 00445 00446 // If there were any uses of instructions in the duplicated block outside the 00447 // loop, update them, inserting PHI nodes as required 00448 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap); 00449 00450 // NewHeader is now the header of the loop. 00451 L->moveToHeader(NewHeader); 00452 assert(L->getHeader() == NewHeader && "Latch block is our new header"); 00453 00454 00455 // At this point, we've finished our major CFG changes. As part of cloning 00456 // the loop into the preheader we've simplified instructions and the 00457 // duplicated conditional branch may now be branching on a constant. If it is 00458 // branching on a constant and if that constant means that we enter the loop, 00459 // then we fold away the cond branch to an uncond branch. This simplifies the 00460 // loop in cases important for nested loops, and it also means we don't have 00461 // to split as many edges. 00462 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator()); 00463 assert(PHBI->isConditional() && "Should be clone of BI condbr!"); 00464 if (!isa<ConstantInt>(PHBI->getCondition()) || 00465 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) 00466 != NewHeader) { 00467 // The conditional branch can't be folded, handle the general case. 00468 // Update DominatorTree to reflect the CFG change we just made. Then split 00469 // edges as necessary to preserve LoopSimplify form. 00470 if (DominatorTreeWrapperPass *DTWP = 00471 getAnalysisIfAvailable<DominatorTreeWrapperPass>()) { 00472 DominatorTree &DT = DTWP->getDomTree(); 00473 // Everything that was dominated by the old loop header is now dominated 00474 // by the original loop preheader. Conceptually the header was merged 00475 // into the preheader, even though we reuse the actual block as a new 00476 // loop latch. 00477 DomTreeNode *OrigHeaderNode = DT.getNode(OrigHeader); 00478 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(), 00479 OrigHeaderNode->end()); 00480 DomTreeNode *OrigPreheaderNode = DT.getNode(OrigPreheader); 00481 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) 00482 DT.changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode); 00483 00484 assert(DT.getNode(Exit)->getIDom() == OrigPreheaderNode); 00485 assert(DT.getNode(NewHeader)->getIDom() == OrigPreheaderNode); 00486 00487 // Update OrigHeader to be dominated by the new header block. 00488 DT.changeImmediateDominator(OrigHeader, OrigLatch); 00489 } 00490 00491 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and 00492 // thus is not a preheader anymore. 00493 // Split the edge to form a real preheader. 00494 BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this); 00495 NewPH->setName(NewHeader->getName() + ".lr.ph"); 00496 00497 // Preserve canonical loop form, which means that 'Exit' should have only 00498 // one predecessor. Note that Exit could be an exit block for multiple 00499 // nested loops, causing both of the edges to now be critical and need to 00500 // be split. 00501 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit)); 00502 bool SplitLatchEdge = false; 00503 for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(), 00504 PE = ExitPreds.end(); 00505 PI != PE; ++PI) { 00506 // We only need to split loop exit edges. 00507 Loop *PredLoop = LI->getLoopFor(*PI); 00508 if (!PredLoop || PredLoop->contains(Exit)) 00509 continue; 00510 SplitLatchEdge |= L->getLoopLatch() == *PI; 00511 BasicBlock *ExitSplit = SplitCriticalEdge(*PI, Exit, this); 00512 ExitSplit->moveBefore(Exit); 00513 } 00514 assert(SplitLatchEdge && 00515 "Despite splitting all preds, failed to split latch exit?"); 00516 } else { 00517 // We can fold the conditional branch in the preheader, this makes things 00518 // simpler. The first step is to remove the extra edge to the Exit block. 00519 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/); 00520 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI); 00521 NewBI->setDebugLoc(PHBI->getDebugLoc()); 00522 PHBI->eraseFromParent(); 00523 00524 // With our CFG finalized, update DomTree if it is available. 00525 if (DominatorTreeWrapperPass *DTWP = 00526 getAnalysisIfAvailable<DominatorTreeWrapperPass>()) { 00527 DominatorTree &DT = DTWP->getDomTree(); 00528 // Update OrigHeader to be dominated by the new header block. 00529 DT.changeImmediateDominator(NewHeader, OrigPreheader); 00530 DT.changeImmediateDominator(OrigHeader, OrigLatch); 00531 00532 // Brute force incremental dominator tree update. Call 00533 // findNearestCommonDominator on all CFG predecessors of each child of the 00534 // original header. 00535 DomTreeNode *OrigHeaderNode = DT.getNode(OrigHeader); 00536 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(), 00537 OrigHeaderNode->end()); 00538 bool Changed; 00539 do { 00540 Changed = false; 00541 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) { 00542 DomTreeNode *Node = HeaderChildren[I]; 00543 BasicBlock *BB = Node->getBlock(); 00544 00545 pred_iterator PI = pred_begin(BB); 00546 BasicBlock *NearestDom = *PI; 00547 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI) 00548 NearestDom = DT.findNearestCommonDominator(NearestDom, *PI); 00549 00550 // Remember if this changes the DomTree. 00551 if (Node->getIDom()->getBlock() != NearestDom) { 00552 DT.changeImmediateDominator(BB, NearestDom); 00553 Changed = true; 00554 } 00555 } 00556 00557 // If the dominator changed, this may have an effect on other 00558 // predecessors, continue until we reach a fixpoint. 00559 } while (Changed); 00560 } 00561 } 00562 00563 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation"); 00564 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation"); 00565 00566 // Now that the CFG and DomTree are in a consistent state again, try to merge 00567 // the OrigHeader block into OrigLatch. This will succeed if they are 00568 // connected by an unconditional branch. This is just a cleanup so the 00569 // emitted code isn't too gross in this common case. 00570 MergeBlockIntoPredecessor(OrigHeader, this); 00571 00572 DEBUG(dbgs() << "LoopRotation: into "; L->dump()); 00573 00574 ++NumRotated; 00575 return true; 00576 }