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