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