LLVM API Documentation

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