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/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, Loop *L) {
00198   bool seenIncrement = false;
00199   bool MultiExitLoop = false;
00200 
00201   if (!L->getExitingBlock())
00202     MultiExitLoop = true;
00203 
00204   for (BasicBlock::iterator I = Begin; I != End; ++I) {
00205 
00206     if (!isSafeToSpeculativelyExecute(I))
00207       return false;
00208 
00209     if (isa<DbgInfoIntrinsic>(I))
00210       continue;
00211 
00212     switch (I->getOpcode()) {
00213     default:
00214       return false;
00215     case Instruction::GetElementPtr:
00216       // GEPs are cheap if all indices are constant.
00217       if (!cast<GEPOperator>(I)->hasAllConstantIndices())
00218         return false;
00219       // fall-thru to increment case
00220     case Instruction::Add:
00221     case Instruction::Sub:
00222     case Instruction::And:
00223     case Instruction::Or:
00224     case Instruction::Xor:
00225     case Instruction::Shl:
00226     case Instruction::LShr:
00227     case Instruction::AShr: {
00228       Value *IVOpnd = nullptr;
00229       if (isa<ConstantInt>(I->getOperand(0)))
00230         IVOpnd = I->getOperand(1);
00231 
00232       if (isa<ConstantInt>(I->getOperand(1))) {
00233         if (IVOpnd)
00234           return false;
00235 
00236         IVOpnd = I->getOperand(0);
00237       }
00238 
00239       // If increment operand is used outside of the loop, this speculation
00240       // could cause extra live range interference.
00241       if (MultiExitLoop && IVOpnd) {
00242         for (User *UseI : IVOpnd->users()) {
00243           auto *UserInst = cast<Instruction>(UseI);
00244           if (!L->contains(UserInst))
00245             return false;
00246         }
00247       }
00248 
00249       if (seenIncrement)
00250         return false;
00251       seenIncrement = true;
00252       break;
00253     }
00254     case Instruction::Trunc:
00255     case Instruction::ZExt:
00256     case Instruction::SExt:
00257       // ignore type conversions
00258       break;
00259     }
00260   }
00261   return true;
00262 }
00263 
00264 /// Fold the loop tail into the loop exit by speculating the loop tail
00265 /// instructions. Typically, this is a single post-increment. In the case of a
00266 /// simple 2-block loop, hoisting the increment can be much better than
00267 /// duplicating the entire loop header. In the case of loops with early exits,
00268 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
00269 /// canonical form so downstream passes can handle it.
00270 ///
00271 /// I don't believe this invalidates SCEV.
00272 bool LoopRotate::simplifyLoopLatch(Loop *L) {
00273   BasicBlock *Latch = L->getLoopLatch();
00274   if (!Latch || Latch->hasAddressTaken())
00275     return false;
00276 
00277   BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
00278   if (!Jmp || !Jmp->isUnconditional())
00279     return false;
00280 
00281   BasicBlock *LastExit = Latch->getSinglePredecessor();
00282   if (!LastExit || !L->isLoopExiting(LastExit))
00283     return false;
00284 
00285   BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
00286   if (!BI)
00287     return false;
00288 
00289   if (!shouldSpeculateInstrs(Latch->begin(), Jmp, L))
00290     return false;
00291 
00292   DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
00293         << LastExit->getName() << "\n");
00294 
00295   // Hoist the instructions from Latch into LastExit.
00296   LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
00297 
00298   unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
00299   BasicBlock *Header = Jmp->getSuccessor(0);
00300   assert(Header == L->getHeader() && "expected a backward branch");
00301 
00302   // Remove Latch from the CFG so that LastExit becomes the new Latch.
00303   BI->setSuccessor(FallThruPath, Header);
00304   Latch->replaceSuccessorsPhiUsesWith(LastExit);
00305   Jmp->eraseFromParent();
00306 
00307   // Nuke the Latch block.
00308   assert(Latch->empty() && "unable to evacuate Latch");
00309   LI->removeBlock(Latch);
00310   if (DominatorTreeWrapperPass *DTWP =
00311           getAnalysisIfAvailable<DominatorTreeWrapperPass>())
00312     DTWP->getDomTree().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, AT, 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, AT 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 (DominatorTreeWrapperPass *DTWP =
00498             getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
00499       DominatorTree &DT = DTWP->getDomTree();
00500       // Everything that was dominated by the old loop header is now dominated
00501       // by the original loop preheader. Conceptually the header was merged
00502       // into the preheader, even though we reuse the actual block as a new
00503       // loop latch.
00504       DomTreeNode *OrigHeaderNode = DT.getNode(OrigHeader);
00505       SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
00506                                                    OrigHeaderNode->end());
00507       DomTreeNode *OrigPreheaderNode = DT.getNode(OrigPreheader);
00508       for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
00509         DT.changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
00510 
00511       assert(DT.getNode(Exit)->getIDom() == OrigPreheaderNode);
00512       assert(DT.getNode(NewHeader)->getIDom() == OrigPreheaderNode);
00513 
00514       // Update OrigHeader to be dominated by the new header block.
00515       DT.changeImmediateDominator(OrigHeader, OrigLatch);
00516     }
00517 
00518     // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
00519     // thus is not a preheader anymore.
00520     // Split the edge to form a real preheader.
00521     BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this);
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(*PI, Exit, this);
00539       ExitSplit->moveBefore(Exit);
00540     }
00541     assert(SplitLatchEdge &&
00542            "Despite splitting all preds, failed to split latch exit?");
00543   } else {
00544     // We can fold the conditional branch in the preheader, this makes things
00545     // simpler. The first step is to remove the extra edge to the Exit block.
00546     Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
00547     BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
00548     NewBI->setDebugLoc(PHBI->getDebugLoc());
00549     PHBI->eraseFromParent();
00550 
00551     // With our CFG finalized, update DomTree if it is available.
00552     if (DominatorTreeWrapperPass *DTWP =
00553             getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
00554       DominatorTree &DT = DTWP->getDomTree();
00555       // Update OrigHeader to be dominated by the new header block.
00556       DT.changeImmediateDominator(NewHeader, OrigPreheader);
00557       DT.changeImmediateDominator(OrigHeader, OrigLatch);
00558 
00559       // Brute force incremental dominator tree update. Call
00560       // findNearestCommonDominator on all CFG predecessors of each child of the
00561       // original header.
00562       DomTreeNode *OrigHeaderNode = DT.getNode(OrigHeader);
00563       SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
00564                                                    OrigHeaderNode->end());
00565       bool Changed;
00566       do {
00567         Changed = false;
00568         for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
00569           DomTreeNode *Node = HeaderChildren[I];
00570           BasicBlock *BB = Node->getBlock();
00571 
00572           pred_iterator PI = pred_begin(BB);
00573           BasicBlock *NearestDom = *PI;
00574           for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
00575             NearestDom = DT.findNearestCommonDominator(NearestDom, *PI);
00576 
00577           // Remember if this changes the DomTree.
00578           if (Node->getIDom()->getBlock() != NearestDom) {
00579             DT.changeImmediateDominator(BB, NearestDom);
00580             Changed = true;
00581           }
00582         }
00583 
00584       // If the dominator changed, this may have an effect on other
00585       // predecessors, continue until we reach a fixpoint.
00586       } while (Changed);
00587     }
00588   }
00589 
00590   assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
00591   assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
00592 
00593   // Now that the CFG and DomTree are in a consistent state again, try to merge
00594   // the OrigHeader block into OrigLatch.  This will succeed if they are
00595   // connected by an unconditional branch.  This is just a cleanup so the
00596   // emitted code isn't too gross in this common case.
00597   MergeBlockIntoPredecessor(OrigHeader, this);
00598 
00599   DEBUG(dbgs() << "LoopRotation: into "; L->dump());
00600 
00601   ++NumRotated;
00602   return true;
00603 }