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