LLVM  mainline
LoopUnroll.cpp
Go to the documentation of this file.
00001 //===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===//
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 some loop unrolling utilities. It does not define any
00011 // actual pass or policy, but provides a single function to perform loop
00012 // unrolling.
00013 //
00014 // The process of unrolling can produce extraneous basic blocks linked with
00015 // unconditional branches.  This will be corrected in the future.
00016 //
00017 //===----------------------------------------------------------------------===//
00018 
00019 #include "llvm/Transforms/Utils/UnrollLoop.h"
00020 #include "llvm/ADT/SmallPtrSet.h"
00021 #include "llvm/ADT/Statistic.h"
00022 #include "llvm/Analysis/AssumptionCache.h"
00023 #include "llvm/Analysis/InstructionSimplify.h"
00024 #include "llvm/Analysis/LoopIterator.h"
00025 #include "llvm/Analysis/LoopPass.h"
00026 #include "llvm/Analysis/ScalarEvolution.h"
00027 #include "llvm/IR/BasicBlock.h"
00028 #include "llvm/IR/DataLayout.h"
00029 #include "llvm/IR/DiagnosticInfo.h"
00030 #include "llvm/IR/Dominators.h"
00031 #include "llvm/IR/LLVMContext.h"
00032 #include "llvm/Support/Debug.h"
00033 #include "llvm/Support/raw_ostream.h"
00034 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00035 #include "llvm/Transforms/Utils/Cloning.h"
00036 #include "llvm/Transforms/Utils/Local.h"
00037 #include "llvm/Transforms/Utils/LoopUtils.h"
00038 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
00039 using namespace llvm;
00040 
00041 #define DEBUG_TYPE "loop-unroll"
00042 
00043 // TODO: Should these be here or in LoopUnroll?
00044 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
00045 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
00046 
00047 /// RemapInstruction - Convert the instruction operands from referencing the
00048 /// current values into those specified by VMap.
00049 static inline void RemapInstruction(Instruction *I,
00050                                     ValueToValueMapTy &VMap) {
00051   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
00052     Value *Op = I->getOperand(op);
00053     ValueToValueMapTy::iterator It = VMap.find(Op);
00054     if (It != VMap.end())
00055       I->setOperand(op, It->second);
00056   }
00057 
00058   if (PHINode *PN = dyn_cast<PHINode>(I)) {
00059     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00060       ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i));
00061       if (It != VMap.end())
00062         PN->setIncomingBlock(i, cast<BasicBlock>(It->second));
00063     }
00064   }
00065 }
00066 
00067 /// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
00068 /// only has one predecessor, and that predecessor only has one successor.
00069 /// The LoopInfo Analysis that is passed will be kept consistent.  If folding is
00070 /// successful references to the containing loop must be removed from
00071 /// ScalarEvolution by calling ScalarEvolution::forgetLoop because SE may have
00072 /// references to the eliminated BB.  The argument ForgottenLoops contains a set
00073 /// of loops that have already been forgotten to prevent redundant, expensive
00074 /// calls to ScalarEvolution::forgetLoop.  Returns the new combined block.
00075 static BasicBlock *
00076 FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI, ScalarEvolution *SE,
00077                          SmallPtrSetImpl<Loop *> &ForgottenLoops) {
00078   // Merge basic blocks into their predecessor if there is only one distinct
00079   // pred, and if there is only one distinct successor of the predecessor, and
00080   // if there are no PHI nodes.
00081   BasicBlock *OnlyPred = BB->getSinglePredecessor();
00082   if (!OnlyPred) return nullptr;
00083 
00084   if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
00085     return nullptr;
00086 
00087   DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred);
00088 
00089   // Resolve any PHI nodes at the start of the block.  They are all
00090   // guaranteed to have exactly one entry if they exist, unless there are
00091   // multiple duplicate (but guaranteed to be equal) entries for the
00092   // incoming edges.  This occurs when there are multiple edges from
00093   // OnlyPred to OnlySucc.
00094   FoldSingleEntryPHINodes(BB);
00095 
00096   // Delete the unconditional branch from the predecessor...
00097   OnlyPred->getInstList().pop_back();
00098 
00099   // Make all PHI nodes that referred to BB now refer to Pred as their
00100   // source...
00101   BB->replaceAllUsesWith(OnlyPred);
00102 
00103   // Move all definitions in the successor to the predecessor...
00104   OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
00105 
00106   // OldName will be valid until erased.
00107   StringRef OldName = BB->getName();
00108 
00109   // Erase basic block from the function...
00110 
00111   // ScalarEvolution holds references to loop exit blocks.
00112   if (SE) {
00113     if (Loop *L = LI->getLoopFor(BB)) {
00114       if (ForgottenLoops.insert(L).second)
00115         SE->forgetLoop(L);
00116     }
00117   }
00118   LI->removeBlock(BB);
00119 
00120   // Inherit predecessor's name if it exists...
00121   if (!OldName.empty() && !OnlyPred->hasName())
00122     OnlyPred->setName(OldName);
00123 
00124   BB->eraseFromParent();
00125 
00126   return OnlyPred;
00127 }
00128 
00129 /// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
00130 /// if unrolling was successful, or false if the loop was unmodified. Unrolling
00131 /// can only fail when the loop's latch block is not terminated by a conditional
00132 /// branch instruction. However, if the trip count (and multiple) are not known,
00133 /// loop unrolling will mostly produce more code that is no faster.
00134 ///
00135 /// TripCount is generally defined as the number of times the loop header
00136 /// executes. UnrollLoop relaxes the definition to permit early exits: here
00137 /// TripCount is the iteration on which control exits LatchBlock if no early
00138 /// exits were taken. Note that UnrollLoop assumes that the loop counter test
00139 /// terminates LatchBlock in order to remove unnecesssary instances of the
00140 /// test. In other words, control may exit the loop prior to TripCount
00141 /// iterations via an early branch, but control may not exit the loop from the
00142 /// LatchBlock's terminator prior to TripCount iterations.
00143 ///
00144 /// Similarly, TripMultiple divides the number of times that the LatchBlock may
00145 /// execute without exiting the loop.
00146 ///
00147 /// If AllowRuntime is true then UnrollLoop will consider unrolling loops that
00148 /// have a runtime (i.e. not compile time constant) trip count.  Unrolling these
00149 /// loops require a unroll "prologue" that runs "RuntimeTripCount % Count"
00150 /// iterations before branching into the unrolled loop.  UnrollLoop will not
00151 /// runtime-unroll the loop if computing RuntimeTripCount will be expensive and
00152 /// AllowExpensiveTripCount is false.
00153 ///
00154 /// The LoopInfo Analysis that is passed will be kept consistent.
00155 ///
00156 /// This utility preserves LoopInfo. It will also preserve ScalarEvolution and
00157 /// DominatorTree if they are non-null.
00158 bool llvm::UnrollLoop(Loop *L, unsigned Count, unsigned TripCount,
00159                       bool AllowRuntime, bool AllowExpensiveTripCount,
00160                       unsigned TripMultiple, LoopInfo *LI, ScalarEvolution *SE,
00161                       DominatorTree *DT, AssumptionCache *AC,
00162                       bool PreserveLCSSA) {
00163   BasicBlock *Preheader = L->getLoopPreheader();
00164   if (!Preheader) {
00165     DEBUG(dbgs() << "  Can't unroll; loop preheader-insertion failed.\n");
00166     return false;
00167   }
00168 
00169   BasicBlock *LatchBlock = L->getLoopLatch();
00170   if (!LatchBlock) {
00171     DEBUG(dbgs() << "  Can't unroll; loop exit-block-insertion failed.\n");
00172     return false;
00173   }
00174 
00175   // Loops with indirectbr cannot be cloned.
00176   if (!L->isSafeToClone()) {
00177     DEBUG(dbgs() << "  Can't unroll; Loop body cannot be cloned.\n");
00178     return false;
00179   }
00180 
00181   BasicBlock *Header = L->getHeader();
00182   BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
00183 
00184   if (!BI || BI->isUnconditional()) {
00185     // The loop-rotate pass can be helpful to avoid this in many cases.
00186     DEBUG(dbgs() <<
00187              "  Can't unroll; loop not terminated by a conditional branch.\n");
00188     return false;
00189   }
00190 
00191   if (Header->hasAddressTaken()) {
00192     // The loop-rotate pass can be helpful to avoid this in many cases.
00193     DEBUG(dbgs() <<
00194           "  Won't unroll loop: address of header block is taken.\n");
00195     return false;
00196   }
00197 
00198   if (TripCount != 0)
00199     DEBUG(dbgs() << "  Trip Count = " << TripCount << "\n");
00200   if (TripMultiple != 1)
00201     DEBUG(dbgs() << "  Trip Multiple = " << TripMultiple << "\n");
00202 
00203   // Effectively "DCE" unrolled iterations that are beyond the tripcount
00204   // and will never be executed.
00205   if (TripCount != 0 && Count > TripCount)
00206     Count = TripCount;
00207 
00208   // Don't enter the unroll code if there is nothing to do. This way we don't
00209   // need to support "partial unrolling by 1".
00210   if (TripCount == 0 && Count < 2)
00211     return false;
00212 
00213   assert(Count > 0);
00214   assert(TripMultiple > 0);
00215   assert(TripCount == 0 || TripCount % TripMultiple == 0);
00216 
00217   // Are we eliminating the loop control altogether?
00218   bool CompletelyUnroll = Count == TripCount;
00219   SmallVector<BasicBlock *, 4> ExitBlocks;
00220   L->getExitBlocks(ExitBlocks);
00221   Loop *ParentL = L->getParentLoop();
00222   bool AllExitsAreInsideParentLoop = !ParentL ||
00223       std::all_of(ExitBlocks.begin(), ExitBlocks.end(),
00224                   [&](BasicBlock *BB) { return ParentL->contains(BB); });
00225 
00226   // We assume a run-time trip count if the compiler cannot
00227   // figure out the loop trip count and the unroll-runtime
00228   // flag is specified.
00229   bool RuntimeTripCount = (TripCount == 0 && Count > 0 && AllowRuntime);
00230 
00231   if (RuntimeTripCount &&
00232       !UnrollRuntimeLoopProlog(L, Count, AllowExpensiveTripCount, LI, SE, DT,
00233                                PreserveLCSSA))
00234     return false;
00235 
00236   // Notify ScalarEvolution that the loop will be substantially changed,
00237   // if not outright eliminated.
00238   if (SE)
00239     SE->forgetLoop(L);
00240 
00241   // If we know the trip count, we know the multiple...
00242   unsigned BreakoutTrip = 0;
00243   if (TripCount != 0) {
00244     BreakoutTrip = TripCount % Count;
00245     TripMultiple = 0;
00246   } else {
00247     // Figure out what multiple to use.
00248     BreakoutTrip = TripMultiple =
00249       (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
00250   }
00251 
00252   // Report the unrolling decision.
00253   DebugLoc LoopLoc = L->getStartLoc();
00254   Function *F = Header->getParent();
00255   LLVMContext &Ctx = F->getContext();
00256 
00257   if (CompletelyUnroll) {
00258     DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
00259           << " with trip count " << TripCount << "!\n");
00260     emitOptimizationRemark(Ctx, DEBUG_TYPE, *F, LoopLoc,
00261                            Twine("completely unrolled loop with ") +
00262                                Twine(TripCount) + " iterations");
00263   } else {
00264     auto EmitDiag = [&](const Twine &T) {
00265       emitOptimizationRemark(Ctx, DEBUG_TYPE, *F, LoopLoc,
00266                              "unrolled loop by a factor of " + Twine(Count) +
00267                                  T);
00268     };
00269 
00270     DEBUG(dbgs() << "UNROLLING loop %" << Header->getName()
00271           << " by " << Count);
00272     if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
00273       DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
00274       EmitDiag(" with a breakout at trip " + Twine(BreakoutTrip));
00275     } else if (TripMultiple != 1) {
00276       DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
00277       EmitDiag(" with " + Twine(TripMultiple) + " trips per branch");
00278     } else if (RuntimeTripCount) {
00279       DEBUG(dbgs() << " with run-time trip count");
00280       EmitDiag(" with run-time trip count");
00281     }
00282     DEBUG(dbgs() << "!\n");
00283   }
00284 
00285   bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
00286   BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
00287 
00288   // For the first iteration of the loop, we should use the precloned values for
00289   // PHI nodes.  Insert associations now.
00290   ValueToValueMapTy LastValueMap;
00291   std::vector<PHINode*> OrigPHINode;
00292   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
00293     OrigPHINode.push_back(cast<PHINode>(I));
00294   }
00295 
00296   std::vector<BasicBlock*> Headers;
00297   std::vector<BasicBlock*> Latches;
00298   Headers.push_back(Header);
00299   Latches.push_back(LatchBlock);
00300 
00301   // The current on-the-fly SSA update requires blocks to be processed in
00302   // reverse postorder so that LastValueMap contains the correct value at each
00303   // exit.
00304   LoopBlocksDFS DFS(L);
00305   DFS.perform(LI);
00306 
00307   // Stash the DFS iterators before adding blocks to the loop.
00308   LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
00309   LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
00310 
00311   for (unsigned It = 1; It != Count; ++It) {
00312     std::vector<BasicBlock*> NewBlocks;
00313     SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
00314     NewLoops[L] = L;
00315 
00316     for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
00317       ValueToValueMapTy VMap;
00318       BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
00319       Header->getParent()->getBasicBlockList().push_back(New);
00320 
00321       // Tell LI about New.
00322       if (*BB == Header) {
00323         assert(LI->getLoopFor(*BB) == L && "Header should not be in a sub-loop");
00324         L->addBasicBlockToLoop(New, *LI);
00325       } else {
00326         // Figure out which loop New is in.
00327         const Loop *OldLoop = LI->getLoopFor(*BB);
00328         assert(OldLoop && "Should (at least) be in the loop being unrolled!");
00329 
00330         Loop *&NewLoop = NewLoops[OldLoop];
00331         if (!NewLoop) {
00332           // Found a new sub-loop.
00333           assert(*BB == OldLoop->getHeader() &&
00334                  "Header should be first in RPO");
00335 
00336           Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
00337           assert(NewLoopParent &&
00338                  "Expected parent loop before sub-loop in RPO");
00339           NewLoop = new Loop;
00340           NewLoopParent->addChildLoop(NewLoop);
00341 
00342           // Forget the old loop, since its inputs may have changed.
00343           if (SE)
00344             SE->forgetLoop(OldLoop);
00345         }
00346         NewLoop->addBasicBlockToLoop(New, *LI);
00347       }
00348 
00349       if (*BB == Header)
00350         // Loop over all of the PHI nodes in the block, changing them to use
00351         // the incoming values from the previous block.
00352         for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
00353           PHINode *NewPHI = cast<PHINode>(VMap[OrigPHINode[i]]);
00354           Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
00355           if (Instruction *InValI = dyn_cast<Instruction>(InVal))
00356             if (It > 1 && L->contains(InValI))
00357               InVal = LastValueMap[InValI];
00358           VMap[OrigPHINode[i]] = InVal;
00359           New->getInstList().erase(NewPHI);
00360         }
00361 
00362       // Update our running map of newest clones
00363       LastValueMap[*BB] = New;
00364       for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
00365            VI != VE; ++VI)
00366         LastValueMap[VI->first] = VI->second;
00367 
00368       // Add phi entries for newly created values to all exit blocks.
00369       for (succ_iterator SI = succ_begin(*BB), SE = succ_end(*BB);
00370            SI != SE; ++SI) {
00371         if (L->contains(*SI))
00372           continue;
00373         for (BasicBlock::iterator BBI = (*SI)->begin();
00374              PHINode *phi = dyn_cast<PHINode>(BBI); ++BBI) {
00375           Value *Incoming = phi->getIncomingValueForBlock(*BB);
00376           ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
00377           if (It != LastValueMap.end())
00378             Incoming = It->second;
00379           phi->addIncoming(Incoming, New);
00380         }
00381       }
00382       // Keep track of new headers and latches as we create them, so that
00383       // we can insert the proper branches later.
00384       if (*BB == Header)
00385         Headers.push_back(New);
00386       if (*BB == LatchBlock)
00387         Latches.push_back(New);
00388 
00389       NewBlocks.push_back(New);
00390     }
00391 
00392     // Remap all instructions in the most recent iteration
00393     for (unsigned i = 0; i < NewBlocks.size(); ++i)
00394       for (BasicBlock::iterator I = NewBlocks[i]->begin(),
00395            E = NewBlocks[i]->end(); I != E; ++I)
00396         ::RemapInstruction(&*I, LastValueMap);
00397   }
00398 
00399   // Loop over the PHI nodes in the original block, setting incoming values.
00400   for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
00401     PHINode *PN = OrigPHINode[i];
00402     if (CompletelyUnroll) {
00403       PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
00404       Header->getInstList().erase(PN);
00405     }
00406     else if (Count > 1) {
00407       Value *InVal = PN->removeIncomingValue(LatchBlock, false);
00408       // If this value was defined in the loop, take the value defined by the
00409       // last iteration of the loop.
00410       if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
00411         if (L->contains(InValI))
00412           InVal = LastValueMap[InVal];
00413       }
00414       assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
00415       PN->addIncoming(InVal, Latches.back());
00416     }
00417   }
00418 
00419   // Now that all the basic blocks for the unrolled iterations are in place,
00420   // set up the branches to connect them.
00421   for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
00422     // The original branch was replicated in each unrolled iteration.
00423     BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
00424 
00425     // The branch destination.
00426     unsigned j = (i + 1) % e;
00427     BasicBlock *Dest = Headers[j];
00428     bool NeedConditional = true;
00429 
00430     if (RuntimeTripCount && j != 0) {
00431       NeedConditional = false;
00432     }
00433 
00434     // For a complete unroll, make the last iteration end with a branch
00435     // to the exit block.
00436     if (CompletelyUnroll) {
00437       if (j == 0)
00438         Dest = LoopExit;
00439       NeedConditional = false;
00440     }
00441 
00442     // If we know the trip count or a multiple of it, we can safely use an
00443     // unconditional branch for some iterations.
00444     if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
00445       NeedConditional = false;
00446     }
00447 
00448     if (NeedConditional) {
00449       // Update the conditional branch's successor for the following
00450       // iteration.
00451       Term->setSuccessor(!ContinueOnTrue, Dest);
00452     } else {
00453       // Remove phi operands at this loop exit
00454       if (Dest != LoopExit) {
00455         BasicBlock *BB = Latches[i];
00456         for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
00457              SI != SE; ++SI) {
00458           if (*SI == Headers[i])
00459             continue;
00460           for (BasicBlock::iterator BBI = (*SI)->begin();
00461                PHINode *Phi = dyn_cast<PHINode>(BBI); ++BBI) {
00462             Phi->removeIncomingValue(BB, false);
00463           }
00464         }
00465       }
00466       // Replace the conditional branch with an unconditional one.
00467       BranchInst::Create(Dest, Term);
00468       Term->eraseFromParent();
00469     }
00470   }
00471 
00472   // Merge adjacent basic blocks, if possible.
00473   SmallPtrSet<Loop *, 4> ForgottenLoops;
00474   for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
00475     BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
00476     if (Term->isUnconditional()) {
00477       BasicBlock *Dest = Term->getSuccessor(0);
00478       if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI, SE,
00479                                                       ForgottenLoops))
00480         std::replace(Latches.begin(), Latches.end(), Dest, Fold);
00481     }
00482   }
00483 
00484   // FIXME: We could register any cloned assumptions instead of clearing the
00485   // whole function's cache.
00486   AC->clear();
00487 
00488   // FIXME: Reconstruct dom info, because it is not preserved properly.
00489   // Incrementally updating domtree after loop unrolling would be easy.
00490   if (DT)
00491     DT->recalculate(*L->getHeader()->getParent());
00492 
00493   // Simplify any new induction variables in the partially unrolled loop.
00494   if (SE && !CompletelyUnroll) {
00495     SmallVector<WeakVH, 16> DeadInsts;
00496     simplifyLoopIVs(L, SE, DT, LI, DeadInsts);
00497 
00498     // Aggressively clean up dead instructions that simplifyLoopIVs already
00499     // identified. Any remaining should be cleaned up below.
00500     while (!DeadInsts.empty())
00501       if (Instruction *Inst =
00502               dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
00503         RecursivelyDeleteTriviallyDeadInstructions(Inst);
00504   }
00505 
00506   // At this point, the code is well formed.  We now do a quick sweep over the
00507   // inserted code, doing constant propagation and dead code elimination as we
00508   // go.
00509   const DataLayout &DL = Header->getModule()->getDataLayout();
00510   const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
00511   for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
00512        BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
00513     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
00514       Instruction *Inst = &*I++;
00515 
00516       if (isInstructionTriviallyDead(Inst))
00517         (*BB)->getInstList().erase(Inst);
00518       else if (Value *V = SimplifyInstruction(Inst, DL))
00519         if (LI->replacementPreservesLCSSAForm(Inst, V)) {
00520           Inst->replaceAllUsesWith(V);
00521           (*BB)->getInstList().erase(Inst);
00522         }
00523     }
00524 
00525   NumCompletelyUnrolled += CompletelyUnroll;
00526   ++NumUnrolled;
00527 
00528   Loop *OuterL = L->getParentLoop();
00529   // Update LoopInfo if the loop is completely removed.
00530   if (CompletelyUnroll)
00531     LI->markAsRemoved(L);
00532 
00533   // If we have a pass and a DominatorTree we should re-simplify impacted loops
00534   // to ensure subsequent analyses can rely on this form. We want to simplify
00535   // at least one layer outside of the loop that was unrolled so that any
00536   // changes to the parent loop exposed by the unrolling are considered.
00537   if (DT) {
00538     if (!OuterL && !CompletelyUnroll)
00539       OuterL = L;
00540     if (OuterL) {
00541       bool Simplified = simplifyLoop(OuterL, DT, LI, SE, AC, PreserveLCSSA);
00542 
00543       // LCSSA must be performed on the outermost affected loop. The unrolled
00544       // loop's last loop latch is guaranteed to be in the outermost loop after
00545       // LoopInfo's been updated by markAsRemoved.
00546       Loop *LatchLoop = LI->getLoopFor(Latches.back());
00547       if (!OuterL->contains(LatchLoop))
00548         while (OuterL->getParentLoop() != LatchLoop)
00549           OuterL = OuterL->getParentLoop();
00550 
00551       if (CompletelyUnroll && (!AllExitsAreInsideParentLoop || Simplified))
00552         formLCSSARecursively(*OuterL, *DT, LI, SE);
00553       else
00554         assert(OuterL->isLCSSAForm(*DT) &&
00555                "Loops should be in LCSSA form after loop-unroll.");
00556     }
00557   }
00558 
00559   return true;
00560 }
00561 
00562 /// Given an llvm.loop loop id metadata node, returns the loop hint metadata
00563 /// node with the given name (for example, "llvm.loop.unroll.count"). If no
00564 /// such metadata node exists, then nullptr is returned.
00565 MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
00566   // First operand should refer to the loop id itself.
00567   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
00568   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
00569 
00570   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
00571     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
00572     if (!MD)
00573       continue;
00574 
00575     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
00576     if (!S)
00577       continue;
00578 
00579     if (Name.equals(S->getString()))
00580       return MD;
00581   }
00582   return nullptr;
00583 }