LoopUnroll.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. //===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements some loop unrolling utilities. It does not define any
  11. // actual pass or policy, but provides a single function to perform loop
  12. // unrolling.
  13. //
  14. // The process of unrolling can produce extraneous basic blocks linked with
  15. // unconditional branches. This will be corrected in the future.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/Transforms/Utils/UnrollLoop.h"
  19. #include "llvm/ADT/SmallPtrSet.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/Analysis/AssumptionCache.h"
  22. #include "llvm/Analysis/InstructionSimplify.h"
  23. #include "llvm/Analysis/LoopIterator.h"
  24. #include "llvm/Analysis/LoopPass.h"
  25. #include "llvm/Analysis/ScalarEvolution.h"
  26. #include "llvm/IR/BasicBlock.h"
  27. #include "llvm/IR/DataLayout.h"
  28. #include "llvm/IR/DiagnosticInfo.h"
  29. #include "llvm/IR/Dominators.h"
  30. #include "llvm/IR/LLVMContext.h"
  31. #include "llvm/Support/Debug.h"
  32. #include "llvm/Support/raw_ostream.h"
  33. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  34. #include "llvm/Transforms/Utils/Cloning.h"
  35. #include "llvm/Transforms/Utils/Local.h"
  36. #include "llvm/Transforms/Utils/LoopUtils.h"
  37. #include "llvm/Transforms/Utils/SimplifyIndVar.h"
  38. using namespace llvm;
  39. #define DEBUG_TYPE "loop-unroll"
  40. // TODO: Should these be here or in LoopUnroll?
  41. STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
  42. STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
  43. /// RemapInstruction - Convert the instruction operands from referencing the
  44. /// current values into those specified by VMap.
  45. static inline void RemapInstruction(Instruction *I,
  46. ValueToValueMapTy &VMap) {
  47. for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
  48. Value *Op = I->getOperand(op);
  49. ValueToValueMapTy::iterator It = VMap.find(Op);
  50. if (It != VMap.end())
  51. I->setOperand(op, It->second);
  52. }
  53. if (PHINode *PN = dyn_cast<PHINode>(I)) {
  54. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  55. ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i));
  56. if (It != VMap.end())
  57. PN->setIncomingBlock(i, cast<BasicBlock>(It->second));
  58. }
  59. }
  60. }
  61. /// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
  62. /// only has one predecessor, and that predecessor only has one successor.
  63. /// The LoopInfo Analysis that is passed will be kept consistent. If folding is
  64. /// successful references to the containing loop must be removed from
  65. /// ScalarEvolution by calling ScalarEvolution::forgetLoop because SE may have
  66. /// references to the eliminated BB. The argument ForgottenLoops contains a set
  67. /// of loops that have already been forgotten to prevent redundant, expensive
  68. /// calls to ScalarEvolution::forgetLoop. Returns the new combined block.
  69. static BasicBlock *
  70. FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI, LPPassManager *LPM,
  71. SmallPtrSetImpl<Loop *> &ForgottenLoops) {
  72. // Merge basic blocks into their predecessor if there is only one distinct
  73. // pred, and if there is only one distinct successor of the predecessor, and
  74. // if there are no PHI nodes.
  75. BasicBlock *OnlyPred = BB->getSinglePredecessor();
  76. if (!OnlyPred) return nullptr;
  77. if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
  78. return nullptr;
  79. DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred);
  80. // Resolve any PHI nodes at the start of the block. They are all
  81. // guaranteed to have exactly one entry if they exist, unless there are
  82. // multiple duplicate (but guaranteed to be equal) entries for the
  83. // incoming edges. This occurs when there are multiple edges from
  84. // OnlyPred to OnlySucc.
  85. FoldSingleEntryPHINodes(BB);
  86. // Delete the unconditional branch from the predecessor...
  87. OnlyPred->getInstList().pop_back();
  88. // Make all PHI nodes that referred to BB now refer to Pred as their
  89. // source...
  90. BB->replaceAllUsesWith(OnlyPred);
  91. // Move all definitions in the successor to the predecessor...
  92. OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
  93. // OldName will be valid until erased.
  94. StringRef OldName = BB->getName();
  95. // Erase basic block from the function...
  96. // ScalarEvolution holds references to loop exit blocks.
  97. if (LPM) {
  98. if (ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>()) {
  99. if (Loop *L = LI->getLoopFor(BB)) {
  100. if (ForgottenLoops.insert(L).second)
  101. SE->forgetLoop(L);
  102. }
  103. }
  104. }
  105. LI->removeBlock(BB);
  106. // Inherit predecessor's name if it exists...
  107. if (!OldName.empty() && !OnlyPred->hasName())
  108. OnlyPred->setName(OldName);
  109. BB->eraseFromParent();
  110. return OnlyPred;
  111. }
  112. /// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
  113. /// if unrolling was successful, or false if the loop was unmodified. Unrolling
  114. /// can only fail when the loop's latch block is not terminated by a conditional
  115. /// branch instruction. However, if the trip count (and multiple) are not known,
  116. /// loop unrolling will mostly produce more code that is no faster.
  117. ///
  118. /// TripCount is generally defined as the number of times the loop header
  119. /// executes. UnrollLoop relaxes the definition to permit early exits: here
  120. /// TripCount is the iteration on which control exits LatchBlock if no early
  121. /// exits were taken. Note that UnrollLoop assumes that the loop counter test
  122. /// terminates LatchBlock in order to remove unnecesssary instances of the
  123. /// test. In other words, control may exit the loop prior to TripCount
  124. /// iterations via an early branch, but control may not exit the loop from the
  125. /// LatchBlock's terminator prior to TripCount iterations.
  126. ///
  127. /// Similarly, TripMultiple divides the number of times that the LatchBlock may
  128. /// execute without exiting the loop.
  129. ///
  130. /// If AllowRuntime is true then UnrollLoop will consider unrolling loops that
  131. /// have a runtime (i.e. not compile time constant) trip count. Unrolling these
  132. /// loops require a unroll "prologue" that runs "RuntimeTripCount % Count"
  133. /// iterations before branching into the unrolled loop. UnrollLoop will not
  134. /// runtime-unroll the loop if computing RuntimeTripCount will be expensive and
  135. /// AllowExpensiveTripCount is false.
  136. ///
  137. /// The LoopInfo Analysis that is passed will be kept consistent.
  138. ///
  139. /// If a LoopPassManager is passed in, and the loop is fully removed, it will be
  140. /// removed from the LoopPassManager as well. LPM can also be NULL.
  141. ///
  142. /// This utility preserves LoopInfo. If DominatorTree or ScalarEvolution are
  143. /// available from the Pass it must also preserve those analyses.
  144. bool llvm::UnrollLoop(Loop *L, unsigned Count, unsigned TripCount,
  145. bool AllowRuntime, bool AllowExpensiveTripCount,
  146. unsigned TripMultiple, LoopInfo *LI, Pass *PP,
  147. LPPassManager *LPM, AssumptionCache *AC) {
  148. BasicBlock *Preheader = L->getLoopPreheader();
  149. if (!Preheader) {
  150. DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
  151. return false;
  152. }
  153. BasicBlock *LatchBlock = L->getLoopLatch();
  154. if (!LatchBlock) {
  155. DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
  156. return false;
  157. }
  158. // Loops with indirectbr cannot be cloned.
  159. if (!L->isSafeToClone()) {
  160. DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n");
  161. return false;
  162. }
  163. BasicBlock *Header = L->getHeader();
  164. BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
  165. if (!BI || BI->isUnconditional()) {
  166. // The loop-rotate pass can be helpful to avoid this in many cases.
  167. DEBUG(dbgs() <<
  168. " Can't unroll; loop not terminated by a conditional branch.\n");
  169. return false;
  170. }
  171. if (Header->hasAddressTaken()) {
  172. // The loop-rotate pass can be helpful to avoid this in many cases.
  173. DEBUG(dbgs() <<
  174. " Won't unroll loop: address of header block is taken.\n");
  175. return false;
  176. }
  177. if (TripCount != 0)
  178. DEBUG(dbgs() << " Trip Count = " << TripCount << "\n");
  179. if (TripMultiple != 1)
  180. DEBUG(dbgs() << " Trip Multiple = " << TripMultiple << "\n");
  181. // Effectively "DCE" unrolled iterations that are beyond the tripcount
  182. // and will never be executed.
  183. if (TripCount != 0 && Count > TripCount)
  184. Count = TripCount;
  185. // Don't enter the unroll code if there is nothing to do. This way we don't
  186. // need to support "partial unrolling by 1".
  187. if (TripCount == 0 && Count < 2)
  188. return false;
  189. assert(Count > 0);
  190. assert(TripMultiple > 0);
  191. assert(TripCount == 0 || TripCount % TripMultiple == 0);
  192. // Are we eliminating the loop control altogether?
  193. bool CompletelyUnroll = Count == TripCount;
  194. // We assume a run-time trip count if the compiler cannot
  195. // figure out the loop trip count and the unroll-runtime
  196. // flag is specified.
  197. bool RuntimeTripCount = (TripCount == 0 && Count > 0 && AllowRuntime);
  198. if (RuntimeTripCount &&
  199. !UnrollRuntimeLoopProlog(L, Count, AllowExpensiveTripCount, LI, LPM))
  200. return false;
  201. // Notify ScalarEvolution that the loop will be substantially changed,
  202. // if not outright eliminated.
  203. ScalarEvolution *SE =
  204. PP ? PP->getAnalysisIfAvailable<ScalarEvolution>() : nullptr;
  205. if (SE)
  206. SE->forgetLoop(L);
  207. // If we know the trip count, we know the multiple...
  208. unsigned BreakoutTrip = 0;
  209. if (TripCount != 0) {
  210. BreakoutTrip = TripCount % Count;
  211. TripMultiple = 0;
  212. } else {
  213. // Figure out what multiple to use.
  214. BreakoutTrip = TripMultiple =
  215. (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
  216. }
  217. // Report the unrolling decision.
  218. DebugLoc LoopLoc = L->getStartLoc();
  219. Function *F = Header->getParent();
  220. LLVMContext &Ctx = F->getContext();
  221. if (CompletelyUnroll) {
  222. DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
  223. << " with trip count " << TripCount << "!\n");
  224. emitOptimizationRemark(Ctx, DEBUG_TYPE, *F, LoopLoc,
  225. Twine("completely unrolled loop with ") +
  226. Twine(TripCount) + " iterations");
  227. } else {
  228. auto EmitDiag = [&](const Twine &T) {
  229. emitOptimizationRemark(Ctx, DEBUG_TYPE, *F, LoopLoc,
  230. "unrolled loop by a factor of " + Twine(Count) +
  231. T);
  232. };
  233. DEBUG(dbgs() << "UNROLLING loop %" << Header->getName()
  234. << " by " << Count);
  235. if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
  236. DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
  237. EmitDiag(" with a breakout at trip " + Twine(BreakoutTrip));
  238. } else if (TripMultiple != 1) {
  239. DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
  240. EmitDiag(" with " + Twine(TripMultiple) + " trips per branch");
  241. } else if (RuntimeTripCount) {
  242. DEBUG(dbgs() << " with run-time trip count");
  243. EmitDiag(" with run-time trip count");
  244. }
  245. DEBUG(dbgs() << "!\n");
  246. }
  247. bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
  248. BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
  249. // For the first iteration of the loop, we should use the precloned values for
  250. // PHI nodes. Insert associations now.
  251. ValueToValueMapTy LastValueMap;
  252. std::vector<PHINode*> OrigPHINode;
  253. for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
  254. OrigPHINode.push_back(cast<PHINode>(I));
  255. }
  256. std::vector<BasicBlock*> Headers;
  257. std::vector<BasicBlock*> Latches;
  258. Headers.push_back(Header);
  259. Latches.push_back(LatchBlock);
  260. // The current on-the-fly SSA update requires blocks to be processed in
  261. // reverse postorder so that LastValueMap contains the correct value at each
  262. // exit.
  263. LoopBlocksDFS DFS(L);
  264. DFS.perform(LI);
  265. // Stash the DFS iterators before adding blocks to the loop.
  266. LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
  267. LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
  268. for (unsigned It = 1; It != Count; ++It) {
  269. std::vector<BasicBlock*> NewBlocks;
  270. SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
  271. NewLoops[L] = L;
  272. for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
  273. ValueToValueMapTy VMap;
  274. BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
  275. Header->getParent()->getBasicBlockList().push_back(New);
  276. // Tell LI about New.
  277. if (*BB == Header) {
  278. assert(LI->getLoopFor(*BB) == L && "Header should not be in a sub-loop");
  279. L->addBasicBlockToLoop(New, *LI);
  280. } else {
  281. // Figure out which loop New is in.
  282. const Loop *OldLoop = LI->getLoopFor(*BB);
  283. assert(OldLoop && "Should (at least) be in the loop being unrolled!");
  284. Loop *&NewLoop = NewLoops[OldLoop];
  285. if (!NewLoop) {
  286. // Found a new sub-loop.
  287. assert(*BB == OldLoop->getHeader() &&
  288. "Header should be first in RPO");
  289. Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
  290. assert(NewLoopParent &&
  291. "Expected parent loop before sub-loop in RPO");
  292. NewLoop = new Loop;
  293. NewLoopParent->addChildLoop(NewLoop);
  294. // Forget the old loop, since its inputs may have changed.
  295. if (SE)
  296. SE->forgetLoop(OldLoop);
  297. }
  298. NewLoop->addBasicBlockToLoop(New, *LI);
  299. }
  300. if (*BB == Header)
  301. // Loop over all of the PHI nodes in the block, changing them to use
  302. // the incoming values from the previous block.
  303. for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
  304. PHINode *NewPHI = cast<PHINode>(VMap[OrigPHINode[i]]);
  305. Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
  306. if (Instruction *InValI = dyn_cast<Instruction>(InVal))
  307. if (It > 1 && L->contains(InValI))
  308. InVal = LastValueMap[InValI];
  309. VMap[OrigPHINode[i]] = InVal;
  310. New->getInstList().erase(NewPHI);
  311. }
  312. // Update our running map of newest clones
  313. LastValueMap[*BB] = New;
  314. for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
  315. VI != VE; ++VI)
  316. LastValueMap[VI->first] = VI->second;
  317. // Add phi entries for newly created values to all exit blocks.
  318. for (succ_iterator SI = succ_begin(*BB), SE = succ_end(*BB);
  319. SI != SE; ++SI) {
  320. if (L->contains(*SI))
  321. continue;
  322. for (BasicBlock::iterator BBI = (*SI)->begin();
  323. PHINode *phi = dyn_cast<PHINode>(BBI); ++BBI) {
  324. Value *Incoming = phi->getIncomingValueForBlock(*BB);
  325. ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
  326. if (It != LastValueMap.end())
  327. Incoming = It->second;
  328. phi->addIncoming(Incoming, New);
  329. }
  330. }
  331. // Keep track of new headers and latches as we create them, so that
  332. // we can insert the proper branches later.
  333. if (*BB == Header)
  334. Headers.push_back(New);
  335. if (*BB == LatchBlock)
  336. Latches.push_back(New);
  337. NewBlocks.push_back(New);
  338. }
  339. // Remap all instructions in the most recent iteration
  340. for (unsigned i = 0; i < NewBlocks.size(); ++i)
  341. for (BasicBlock::iterator I = NewBlocks[i]->begin(),
  342. E = NewBlocks[i]->end(); I != E; ++I)
  343. ::RemapInstruction(I, LastValueMap);
  344. }
  345. // Loop over the PHI nodes in the original block, setting incoming values.
  346. for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
  347. PHINode *PN = OrigPHINode[i];
  348. if (CompletelyUnroll) {
  349. PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
  350. Header->getInstList().erase(PN);
  351. }
  352. else if (Count > 1) {
  353. Value *InVal = PN->removeIncomingValue(LatchBlock, false);
  354. // If this value was defined in the loop, take the value defined by the
  355. // last iteration of the loop.
  356. if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
  357. if (L->contains(InValI))
  358. InVal = LastValueMap[InVal];
  359. }
  360. assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
  361. PN->addIncoming(InVal, Latches.back());
  362. }
  363. }
  364. // Now that all the basic blocks for the unrolled iterations are in place,
  365. // set up the branches to connect them.
  366. for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
  367. // The original branch was replicated in each unrolled iteration.
  368. BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
  369. // The branch destination.
  370. unsigned j = (i + 1) % e;
  371. BasicBlock *Dest = Headers[j];
  372. bool NeedConditional = true;
  373. if (RuntimeTripCount && j != 0) {
  374. NeedConditional = false;
  375. }
  376. // For a complete unroll, make the last iteration end with a branch
  377. // to the exit block.
  378. if (CompletelyUnroll && j == 0) {
  379. Dest = LoopExit;
  380. NeedConditional = false;
  381. }
  382. // If we know the trip count or a multiple of it, we can safely use an
  383. // unconditional branch for some iterations.
  384. if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
  385. NeedConditional = false;
  386. }
  387. if (NeedConditional) {
  388. // Update the conditional branch's successor for the following
  389. // iteration.
  390. Term->setSuccessor(!ContinueOnTrue, Dest);
  391. } else {
  392. // Remove phi operands at this loop exit
  393. if (Dest != LoopExit) {
  394. BasicBlock *BB = Latches[i];
  395. for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
  396. SI != SE; ++SI) {
  397. if (*SI == Headers[i])
  398. continue;
  399. for (BasicBlock::iterator BBI = (*SI)->begin();
  400. PHINode *Phi = dyn_cast<PHINode>(BBI); ++BBI) {
  401. Phi->removeIncomingValue(BB, false);
  402. }
  403. }
  404. }
  405. // Replace the conditional branch with an unconditional one.
  406. BranchInst::Create(Dest, Term);
  407. Term->eraseFromParent();
  408. }
  409. }
  410. // Merge adjacent basic blocks, if possible.
  411. SmallPtrSet<Loop *, 4> ForgottenLoops;
  412. for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
  413. BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
  414. if (Term->isUnconditional()) {
  415. BasicBlock *Dest = Term->getSuccessor(0);
  416. if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI, LPM,
  417. ForgottenLoops))
  418. std::replace(Latches.begin(), Latches.end(), Dest, Fold);
  419. }
  420. }
  421. // FIXME: We could register any cloned assumptions instead of clearing the
  422. // whole function's cache.
  423. AC->clear();
  424. DominatorTree *DT = nullptr;
  425. if (PP) {
  426. // FIXME: Reconstruct dom info, because it is not preserved properly.
  427. // Incrementally updating domtree after loop unrolling would be easy.
  428. if (DominatorTreeWrapperPass *DTWP =
  429. PP->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
  430. DT = &DTWP->getDomTree();
  431. DT->recalculate(*L->getHeader()->getParent());
  432. }
  433. // Simplify any new induction variables in the partially unrolled loop.
  434. if (SE && !CompletelyUnroll) {
  435. SmallVector<WeakVH, 16> DeadInsts;
  436. simplifyLoopIVs(L, SE, LPM, DeadInsts);
  437. // Aggressively clean up dead instructions that simplifyLoopIVs already
  438. // identified. Any remaining should be cleaned up below.
  439. while (!DeadInsts.empty())
  440. if (Instruction *Inst =
  441. dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
  442. RecursivelyDeleteTriviallyDeadInstructions(Inst);
  443. }
  444. }
  445. // At this point, the code is well formed. We now do a quick sweep over the
  446. // inserted code, doing constant propagation and dead code elimination as we
  447. // go.
  448. const DataLayout &DL = Header->getModule()->getDataLayout();
  449. const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
  450. for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
  451. BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
  452. for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
  453. Instruction *Inst = I++;
  454. if (isInstructionTriviallyDead(Inst))
  455. (*BB)->getInstList().erase(Inst);
  456. else if (Value *V = SimplifyInstruction(Inst, DL))
  457. if (LI->replacementPreservesLCSSAForm(Inst, V)) {
  458. Inst->replaceAllUsesWith(V);
  459. (*BB)->getInstList().erase(Inst);
  460. }
  461. }
  462. NumCompletelyUnrolled += CompletelyUnroll;
  463. ++NumUnrolled;
  464. Loop *OuterL = L->getParentLoop();
  465. // Remove the loop from the LoopPassManager if it's completely removed.
  466. if (CompletelyUnroll && LPM != nullptr)
  467. LPM->deleteLoopFromQueue(L);
  468. // If we have a pass and a DominatorTree we should re-simplify impacted loops
  469. // to ensure subsequent analyses can rely on this form. We want to simplify
  470. // at least one layer outside of the loop that was unrolled so that any
  471. // changes to the parent loop exposed by the unrolling are considered.
  472. if (PP && DT) {
  473. if (!OuterL && !CompletelyUnroll)
  474. OuterL = L;
  475. if (OuterL) {
  476. simplifyLoop(OuterL, DT, LI, PP, /*AliasAnalysis*/ nullptr, SE, AC);
  477. // LCSSA must be performed on the outermost affected loop. The unrolled
  478. // loop's last loop latch is guaranteed to be in the outermost loop after
  479. // deleteLoopFromQueue updates LoopInfo.
  480. Loop *LatchLoop = LI->getLoopFor(Latches.back());
  481. if (!OuterL->contains(LatchLoop))
  482. while (OuterL->getParentLoop() != LatchLoop)
  483. OuterL = OuterL->getParentLoop();
  484. formLCSSARecursively(*OuterL, *DT, LI, SE);
  485. }
  486. }
  487. return true;
  488. }
  489. /// Given an llvm.loop loop id metadata node, returns the loop hint metadata
  490. /// node with the given name (for example, "llvm.loop.unroll.count"). If no
  491. /// such metadata node exists, then nullptr is returned.
  492. MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
  493. // First operand should refer to the loop id itself.
  494. assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
  495. assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
  496. for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
  497. MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
  498. if (!MD)
  499. continue;
  500. MDString *S = dyn_cast<MDString>(MD->getOperand(0));
  501. if (!S)
  502. continue;
  503. if (Name.equals(S->getString()))
  504. return MD;
  505. }
  506. return nullptr;
  507. }