LoopUnroll.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. //===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements some loop unrolling utilities. It does not define any
  10. // actual pass or policy, but provides a single function to perform loop
  11. // unrolling.
  12. //
  13. // The process of unrolling can produce extraneous basic blocks linked with
  14. // unconditional branches. This will be corrected in the future.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/ADT/ArrayRef.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/ADT/Optional.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/SetVector.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/ADT/Statistic.h"
  24. #include "llvm/ADT/StringRef.h"
  25. #include "llvm/ADT/Twine.h"
  26. #include "llvm/ADT/ilist_iterator.h"
  27. #include "llvm/ADT/iterator_range.h"
  28. #include "llvm/Analysis/AssumptionCache.h"
  29. #include "llvm/Analysis/DomTreeUpdater.h"
  30. #include "llvm/Analysis/InstructionSimplify.h"
  31. #include "llvm/Analysis/LoopInfo.h"
  32. #include "llvm/Analysis/LoopIterator.h"
  33. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  34. #include "llvm/Analysis/ScalarEvolution.h"
  35. #include "llvm/IR/BasicBlock.h"
  36. #include "llvm/IR/CFG.h"
  37. #include "llvm/IR/Constants.h"
  38. #include "llvm/IR/DebugInfoMetadata.h"
  39. #include "llvm/IR/DebugLoc.h"
  40. #include "llvm/IR/DiagnosticInfo.h"
  41. #include "llvm/IR/Dominators.h"
  42. #include "llvm/IR/Function.h"
  43. #include "llvm/IR/Instruction.h"
  44. #include "llvm/IR/Instructions.h"
  45. #include "llvm/IR/IntrinsicInst.h"
  46. #include "llvm/IR/Metadata.h"
  47. #include "llvm/IR/Module.h"
  48. #include "llvm/IR/Use.h"
  49. #include "llvm/IR/User.h"
  50. #include "llvm/IR/ValueHandle.h"
  51. #include "llvm/IR/ValueMap.h"
  52. #include "llvm/Support/Casting.h"
  53. #include "llvm/Support/CommandLine.h"
  54. #include "llvm/Support/Debug.h"
  55. #include "llvm/Support/GenericDomTree.h"
  56. #include "llvm/Support/MathExtras.h"
  57. #include "llvm/Support/raw_ostream.h"
  58. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  59. #include "llvm/Transforms/Utils/Cloning.h"
  60. #include "llvm/Transforms/Utils/Local.h"
  61. #include "llvm/Transforms/Utils/LoopSimplify.h"
  62. #include "llvm/Transforms/Utils/LoopUtils.h"
  63. #include "llvm/Transforms/Utils/SimplifyIndVar.h"
  64. #include "llvm/Transforms/Utils/UnrollLoop.h"
  65. #include "llvm/Transforms/Utils/ValueMapper.h"
  66. #include <algorithm>
  67. #include <assert.h>
  68. #include <type_traits>
  69. #include <vector>
  70. namespace llvm {
  71. class DataLayout;
  72. class Value;
  73. } // namespace llvm
  74. using namespace llvm;
  75. #define DEBUG_TYPE "loop-unroll"
  76. // TODO: Should these be here or in LoopUnroll?
  77. STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
  78. STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
  79. STATISTIC(NumUnrolledNotLatch, "Number of loops unrolled without a conditional "
  80. "latch (completely or otherwise)");
  81. static cl::opt<bool>
  82. UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden,
  83. cl::desc("Allow runtime unrolled loops to be unrolled "
  84. "with epilog instead of prolog."));
  85. static cl::opt<bool>
  86. UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden,
  87. cl::desc("Verify domtree after unrolling"),
  88. #ifdef EXPENSIVE_CHECKS
  89. cl::init(true)
  90. #else
  91. cl::init(false)
  92. #endif
  93. );
  94. static cl::opt<bool>
  95. UnrollVerifyLoopInfo("unroll-verify-loopinfo", cl::Hidden,
  96. cl::desc("Verify loopinfo after unrolling"),
  97. #ifdef EXPENSIVE_CHECKS
  98. cl::init(true)
  99. #else
  100. cl::init(false)
  101. #endif
  102. );
  103. /// Check if unrolling created a situation where we need to insert phi nodes to
  104. /// preserve LCSSA form.
  105. /// \param Blocks is a vector of basic blocks representing unrolled loop.
  106. /// \param L is the outer loop.
  107. /// It's possible that some of the blocks are in L, and some are not. In this
  108. /// case, if there is a use is outside L, and definition is inside L, we need to
  109. /// insert a phi-node, otherwise LCSSA will be broken.
  110. /// The function is just a helper function for llvm::UnrollLoop that returns
  111. /// true if this situation occurs, indicating that LCSSA needs to be fixed.
  112. static bool needToInsertPhisForLCSSA(Loop *L,
  113. const std::vector<BasicBlock *> &Blocks,
  114. LoopInfo *LI) {
  115. for (BasicBlock *BB : Blocks) {
  116. if (LI->getLoopFor(BB) == L)
  117. continue;
  118. for (Instruction &I : *BB) {
  119. for (Use &U : I.operands()) {
  120. if (const auto *Def = dyn_cast<Instruction>(U)) {
  121. Loop *DefLoop = LI->getLoopFor(Def->getParent());
  122. if (!DefLoop)
  123. continue;
  124. if (DefLoop->contains(L))
  125. return true;
  126. }
  127. }
  128. }
  129. }
  130. return false;
  131. }
  132. /// Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary
  133. /// and adds a mapping from the original loop to the new loop to NewLoops.
  134. /// Returns nullptr if no new loop was created and a pointer to the
  135. /// original loop OriginalBB was part of otherwise.
  136. const Loop* llvm::addClonedBlockToLoopInfo(BasicBlock *OriginalBB,
  137. BasicBlock *ClonedBB, LoopInfo *LI,
  138. NewLoopsMap &NewLoops) {
  139. // Figure out which loop New is in.
  140. const Loop *OldLoop = LI->getLoopFor(OriginalBB);
  141. assert(OldLoop && "Should (at least) be in the loop being unrolled!");
  142. Loop *&NewLoop = NewLoops[OldLoop];
  143. if (!NewLoop) {
  144. // Found a new sub-loop.
  145. assert(OriginalBB == OldLoop->getHeader() &&
  146. "Header should be first in RPO");
  147. NewLoop = LI->AllocateLoop();
  148. Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
  149. if (NewLoopParent)
  150. NewLoopParent->addChildLoop(NewLoop);
  151. else
  152. LI->addTopLevelLoop(NewLoop);
  153. NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
  154. return OldLoop;
  155. } else {
  156. NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
  157. return nullptr;
  158. }
  159. }
  160. /// The function chooses which type of unroll (epilog or prolog) is more
  161. /// profitabale.
  162. /// Epilog unroll is more profitable when there is PHI that starts from
  163. /// constant. In this case epilog will leave PHI start from constant,
  164. /// but prolog will convert it to non-constant.
  165. ///
  166. /// loop:
  167. /// PN = PHI [I, Latch], [CI, PreHeader]
  168. /// I = foo(PN)
  169. /// ...
  170. ///
  171. /// Epilog unroll case.
  172. /// loop:
  173. /// PN = PHI [I2, Latch], [CI, PreHeader]
  174. /// I1 = foo(PN)
  175. /// I2 = foo(I1)
  176. /// ...
  177. /// Prolog unroll case.
  178. /// NewPN = PHI [PrologI, Prolog], [CI, PreHeader]
  179. /// loop:
  180. /// PN = PHI [I2, Latch], [NewPN, PreHeader]
  181. /// I1 = foo(PN)
  182. /// I2 = foo(I1)
  183. /// ...
  184. ///
  185. static bool isEpilogProfitable(Loop *L) {
  186. BasicBlock *PreHeader = L->getLoopPreheader();
  187. BasicBlock *Header = L->getHeader();
  188. assert(PreHeader && Header);
  189. for (const PHINode &PN : Header->phis()) {
  190. if (isa<ConstantInt>(PN.getIncomingValueForBlock(PreHeader)))
  191. return true;
  192. }
  193. return false;
  194. }
  195. /// Perform some cleanup and simplifications on loops after unrolling. It is
  196. /// useful to simplify the IV's in the new loop, as well as do a quick
  197. /// simplify/dce pass of the instructions.
  198. void llvm::simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI,
  199. ScalarEvolution *SE, DominatorTree *DT,
  200. AssumptionCache *AC,
  201. const TargetTransformInfo *TTI) {
  202. // Simplify any new induction variables in the partially unrolled loop.
  203. if (SE && SimplifyIVs) {
  204. SmallVector<WeakTrackingVH, 16> DeadInsts;
  205. simplifyLoopIVs(L, SE, DT, LI, TTI, DeadInsts);
  206. // Aggressively clean up dead instructions that simplifyLoopIVs already
  207. // identified. Any remaining should be cleaned up below.
  208. while (!DeadInsts.empty()) {
  209. Value *V = DeadInsts.pop_back_val();
  210. if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))
  211. RecursivelyDeleteTriviallyDeadInstructions(Inst);
  212. }
  213. }
  214. // At this point, the code is well formed. Perform constprop, instsimplify,
  215. // and dce.
  216. const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
  217. SmallVector<WeakTrackingVH, 16> DeadInsts;
  218. for (BasicBlock *BB : L->getBlocks()) {
  219. for (Instruction &Inst : llvm::make_early_inc_range(*BB)) {
  220. if (Value *V = SimplifyInstruction(&Inst, {DL, nullptr, DT, AC}))
  221. if (LI->replacementPreservesLCSSAForm(&Inst, V))
  222. Inst.replaceAllUsesWith(V);
  223. if (isInstructionTriviallyDead(&Inst))
  224. DeadInsts.emplace_back(&Inst);
  225. }
  226. // We can't do recursive deletion until we're done iterating, as we might
  227. // have a phi which (potentially indirectly) uses instructions later in
  228. // the block we're iterating through.
  229. RecursivelyDeleteTriviallyDeadInstructions(DeadInsts);
  230. }
  231. }
  232. /// Unroll the given loop by Count. The loop must be in LCSSA form. Unrolling
  233. /// can only fail when the loop's latch block is not terminated by a conditional
  234. /// branch instruction. However, if the trip count (and multiple) are not known,
  235. /// loop unrolling will mostly produce more code that is no faster.
  236. ///
  237. /// If Runtime is true then UnrollLoop will try to insert a prologue or
  238. /// epilogue that ensures the latch has a trip multiple of Count. UnrollLoop
  239. /// will not runtime-unroll the loop if computing the run-time trip count will
  240. /// be expensive and AllowExpensiveTripCount is false.
  241. ///
  242. /// The LoopInfo Analysis that is passed will be kept consistent.
  243. ///
  244. /// This utility preserves LoopInfo. It will also preserve ScalarEvolution and
  245. /// DominatorTree if they are non-null.
  246. ///
  247. /// If RemainderLoop is non-null, it will receive the remainder loop (if
  248. /// required and not fully unrolled).
  249. LoopUnrollResult llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
  250. ScalarEvolution *SE, DominatorTree *DT,
  251. AssumptionCache *AC,
  252. const TargetTransformInfo *TTI,
  253. OptimizationRemarkEmitter *ORE,
  254. bool PreserveLCSSA, Loop **RemainderLoop) {
  255. assert(DT && "DomTree is required");
  256. if (!L->getLoopPreheader()) {
  257. LLVM_DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
  258. return LoopUnrollResult::Unmodified;
  259. }
  260. if (!L->getLoopLatch()) {
  261. LLVM_DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
  262. return LoopUnrollResult::Unmodified;
  263. }
  264. // Loops with indirectbr cannot be cloned.
  265. if (!L->isSafeToClone()) {
  266. LLVM_DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n");
  267. return LoopUnrollResult::Unmodified;
  268. }
  269. if (L->getHeader()->hasAddressTaken()) {
  270. // The loop-rotate pass can be helpful to avoid this in many cases.
  271. LLVM_DEBUG(
  272. dbgs() << " Won't unroll loop: address of header block is taken.\n");
  273. return LoopUnrollResult::Unmodified;
  274. }
  275. assert(ULO.Count > 0);
  276. // All these values should be taken only after peeling because they might have
  277. // changed.
  278. BasicBlock *Preheader = L->getLoopPreheader();
  279. BasicBlock *Header = L->getHeader();
  280. BasicBlock *LatchBlock = L->getLoopLatch();
  281. SmallVector<BasicBlock *, 4> ExitBlocks;
  282. L->getExitBlocks(ExitBlocks);
  283. std::vector<BasicBlock *> OriginalLoopBlocks = L->getBlocks();
  284. const unsigned MaxTripCount = SE->getSmallConstantMaxTripCount(L);
  285. const bool MaxOrZero = SE->isBackedgeTakenCountMaxOrZero(L);
  286. // Effectively "DCE" unrolled iterations that are beyond the max tripcount
  287. // and will never be executed.
  288. if (MaxTripCount && ULO.Count > MaxTripCount)
  289. ULO.Count = MaxTripCount;
  290. struct ExitInfo {
  291. unsigned TripCount;
  292. unsigned TripMultiple;
  293. unsigned BreakoutTrip;
  294. bool ExitOnTrue;
  295. SmallVector<BasicBlock *> ExitingBlocks;
  296. };
  297. DenseMap<BasicBlock *, ExitInfo> ExitInfos;
  298. SmallVector<BasicBlock *, 4> ExitingBlocks;
  299. L->getExitingBlocks(ExitingBlocks);
  300. for (auto *ExitingBlock : ExitingBlocks) {
  301. // The folding code is not prepared to deal with non-branch instructions
  302. // right now.
  303. auto *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
  304. if (!BI)
  305. continue;
  306. ExitInfo &Info = ExitInfos.try_emplace(ExitingBlock).first->second;
  307. Info.TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
  308. Info.TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
  309. if (Info.TripCount != 0) {
  310. Info.BreakoutTrip = Info.TripCount % ULO.Count;
  311. Info.TripMultiple = 0;
  312. } else {
  313. Info.BreakoutTrip = Info.TripMultiple =
  314. (unsigned)GreatestCommonDivisor64(ULO.Count, Info.TripMultiple);
  315. }
  316. Info.ExitOnTrue = !L->contains(BI->getSuccessor(0));
  317. Info.ExitingBlocks.push_back(ExitingBlock);
  318. LLVM_DEBUG(dbgs() << " Exiting block %" << ExitingBlock->getName()
  319. << ": TripCount=" << Info.TripCount
  320. << ", TripMultiple=" << Info.TripMultiple
  321. << ", BreakoutTrip=" << Info.BreakoutTrip << "\n");
  322. }
  323. // Are we eliminating the loop control altogether? Note that we can know
  324. // we're eliminating the backedge without knowing exactly which iteration
  325. // of the unrolled body exits.
  326. const bool CompletelyUnroll = ULO.Count == MaxTripCount;
  327. const bool PreserveOnlyFirst = CompletelyUnroll && MaxOrZero;
  328. // There's no point in performing runtime unrolling if this unroll count
  329. // results in a full unroll.
  330. if (CompletelyUnroll)
  331. ULO.Runtime = false;
  332. // Go through all exits of L and see if there are any phi-nodes there. We just
  333. // conservatively assume that they're inserted to preserve LCSSA form, which
  334. // means that complete unrolling might break this form. We need to either fix
  335. // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
  336. // now we just recompute LCSSA for the outer loop, but it should be possible
  337. // to fix it in-place.
  338. bool NeedToFixLCSSA =
  339. PreserveLCSSA && CompletelyUnroll &&
  340. any_of(ExitBlocks,
  341. [](const BasicBlock *BB) { return isa<PHINode>(BB->begin()); });
  342. // The current loop unroll pass can unroll loops that have
  343. // (1) single latch; and
  344. // (2a) latch is unconditional; or
  345. // (2b) latch is conditional and is an exiting block
  346. // FIXME: The implementation can be extended to work with more complicated
  347. // cases, e.g. loops with multiple latches.
  348. BranchInst *LatchBI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
  349. // A conditional branch which exits the loop, which can be optimized to an
  350. // unconditional branch in the unrolled loop in some cases.
  351. bool LatchIsExiting = L->isLoopExiting(LatchBlock);
  352. if (!LatchBI || (LatchBI->isConditional() && !LatchIsExiting)) {
  353. LLVM_DEBUG(
  354. dbgs() << "Can't unroll; a conditional latch must exit the loop");
  355. return LoopUnrollResult::Unmodified;
  356. }
  357. // Loops containing convergent instructions cannot use runtime unrolling,
  358. // as the prologue/epilogue may add additional control-dependencies to
  359. // convergent operations.
  360. LLVM_DEBUG(
  361. {
  362. bool HasConvergent = false;
  363. for (auto &BB : L->blocks())
  364. for (auto &I : *BB)
  365. if (auto *CB = dyn_cast<CallBase>(&I))
  366. HasConvergent |= CB->isConvergent();
  367. assert((!HasConvergent || !ULO.Runtime) &&
  368. "Can't runtime unroll if loop contains a convergent operation.");
  369. });
  370. bool EpilogProfitability =
  371. UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog
  372. : isEpilogProfitable(L);
  373. if (ULO.Runtime &&
  374. !UnrollRuntimeLoopRemainder(L, ULO.Count, ULO.AllowExpensiveTripCount,
  375. EpilogProfitability, ULO.UnrollRemainder,
  376. ULO.ForgetAllSCEV, LI, SE, DT, AC, TTI,
  377. PreserveLCSSA, RemainderLoop)) {
  378. if (ULO.Force)
  379. ULO.Runtime = false;
  380. else {
  381. LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be "
  382. "generated when assuming runtime trip count\n");
  383. return LoopUnrollResult::Unmodified;
  384. }
  385. }
  386. using namespace ore;
  387. // Report the unrolling decision.
  388. if (CompletelyUnroll) {
  389. LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
  390. << " with trip count " << ULO.Count << "!\n");
  391. if (ORE)
  392. ORE->emit([&]() {
  393. return OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(),
  394. L->getHeader())
  395. << "completely unrolled loop with "
  396. << NV("UnrollCount", ULO.Count) << " iterations";
  397. });
  398. } else {
  399. LLVM_DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() << " by "
  400. << ULO.Count);
  401. if (ULO.Runtime)
  402. LLVM_DEBUG(dbgs() << " with run-time trip count");
  403. LLVM_DEBUG(dbgs() << "!\n");
  404. if (ORE)
  405. ORE->emit([&]() {
  406. OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
  407. L->getHeader());
  408. Diag << "unrolled loop by a factor of " << NV("UnrollCount", ULO.Count);
  409. if (ULO.Runtime)
  410. Diag << " with run-time trip count";
  411. return Diag;
  412. });
  413. }
  414. // We are going to make changes to this loop. SCEV may be keeping cached info
  415. // about it, in particular about backedge taken count. The changes we make
  416. // are guaranteed to invalidate this information for our loop. It is tempting
  417. // to only invalidate the loop being unrolled, but it is incorrect as long as
  418. // all exiting branches from all inner loops have impact on the outer loops,
  419. // and if something changes inside them then any of outer loops may also
  420. // change. When we forget outermost loop, we also forget all contained loops
  421. // and this is what we need here.
  422. if (SE) {
  423. if (ULO.ForgetAllSCEV)
  424. SE->forgetAllLoops();
  425. else
  426. SE->forgetTopmostLoop(L);
  427. }
  428. if (!LatchIsExiting)
  429. ++NumUnrolledNotLatch;
  430. // For the first iteration of the loop, we should use the precloned values for
  431. // PHI nodes. Insert associations now.
  432. ValueToValueMapTy LastValueMap;
  433. std::vector<PHINode*> OrigPHINode;
  434. for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
  435. OrigPHINode.push_back(cast<PHINode>(I));
  436. }
  437. std::vector<BasicBlock *> Headers;
  438. std::vector<BasicBlock *> Latches;
  439. Headers.push_back(Header);
  440. Latches.push_back(LatchBlock);
  441. // The current on-the-fly SSA update requires blocks to be processed in
  442. // reverse postorder so that LastValueMap contains the correct value at each
  443. // exit.
  444. LoopBlocksDFS DFS(L);
  445. DFS.perform(LI);
  446. // Stash the DFS iterators before adding blocks to the loop.
  447. LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
  448. LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
  449. std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
  450. // Loop Unrolling might create new loops. While we do preserve LoopInfo, we
  451. // might break loop-simplified form for these loops (as they, e.g., would
  452. // share the same exit blocks). We'll keep track of loops for which we can
  453. // break this so that later we can re-simplify them.
  454. SmallSetVector<Loop *, 4> LoopsToSimplify;
  455. for (Loop *SubLoop : *L)
  456. LoopsToSimplify.insert(SubLoop);
  457. // When a FSDiscriminator is enabled, we don't need to add the multiply
  458. // factors to the discriminators.
  459. if (Header->getParent()->isDebugInfoForProfiling() && !EnableFSDiscriminator)
  460. for (BasicBlock *BB : L->getBlocks())
  461. for (Instruction &I : *BB)
  462. if (!isa<DbgInfoIntrinsic>(&I))
  463. if (const DILocation *DIL = I.getDebugLoc()) {
  464. auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.Count);
  465. if (NewDIL)
  466. I.setDebugLoc(NewDIL.getValue());
  467. else
  468. LLVM_DEBUG(dbgs()
  469. << "Failed to create new discriminator: "
  470. << DIL->getFilename() << " Line: " << DIL->getLine());
  471. }
  472. // Identify what noalias metadata is inside the loop: if it is inside the
  473. // loop, the associated metadata must be cloned for each iteration.
  474. SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes;
  475. identifyNoAliasScopesToClone(L->getBlocks(), LoopLocalNoAliasDeclScopes);
  476. // We place the unrolled iterations immediately after the original loop
  477. // latch. This is a reasonable default placement if we don't have block
  478. // frequencies, and if we do, well the layout will be adjusted later.
  479. auto BlockInsertPt = std::next(LatchBlock->getIterator());
  480. for (unsigned It = 1; It != ULO.Count; ++It) {
  481. SmallVector<BasicBlock *, 8> NewBlocks;
  482. SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
  483. NewLoops[L] = L;
  484. for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
  485. ValueToValueMapTy VMap;
  486. BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
  487. Header->getParent()->getBasicBlockList().insert(BlockInsertPt, New);
  488. assert((*BB != Header || LI->getLoopFor(*BB) == L) &&
  489. "Header should not be in a sub-loop");
  490. // Tell LI about New.
  491. const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
  492. if (OldLoop)
  493. LoopsToSimplify.insert(NewLoops[OldLoop]);
  494. if (*BB == Header)
  495. // Loop over all of the PHI nodes in the block, changing them to use
  496. // the incoming values from the previous block.
  497. for (PHINode *OrigPHI : OrigPHINode) {
  498. PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
  499. Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
  500. if (Instruction *InValI = dyn_cast<Instruction>(InVal))
  501. if (It > 1 && L->contains(InValI))
  502. InVal = LastValueMap[InValI];
  503. VMap[OrigPHI] = InVal;
  504. New->getInstList().erase(NewPHI);
  505. }
  506. // Update our running map of newest clones
  507. LastValueMap[*BB] = New;
  508. for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
  509. VI != VE; ++VI)
  510. LastValueMap[VI->first] = VI->second;
  511. // Add phi entries for newly created values to all exit blocks.
  512. for (BasicBlock *Succ : successors(*BB)) {
  513. if (L->contains(Succ))
  514. continue;
  515. for (PHINode &PHI : Succ->phis()) {
  516. Value *Incoming = PHI.getIncomingValueForBlock(*BB);
  517. ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
  518. if (It != LastValueMap.end())
  519. Incoming = It->second;
  520. PHI.addIncoming(Incoming, New);
  521. }
  522. }
  523. // Keep track of new headers and latches as we create them, so that
  524. // we can insert the proper branches later.
  525. if (*BB == Header)
  526. Headers.push_back(New);
  527. if (*BB == LatchBlock)
  528. Latches.push_back(New);
  529. // Keep track of the exiting block and its successor block contained in
  530. // the loop for the current iteration.
  531. auto ExitInfoIt = ExitInfos.find(*BB);
  532. if (ExitInfoIt != ExitInfos.end())
  533. ExitInfoIt->second.ExitingBlocks.push_back(New);
  534. NewBlocks.push_back(New);
  535. UnrolledLoopBlocks.push_back(New);
  536. // Update DomTree: since we just copy the loop body, and each copy has a
  537. // dedicated entry block (copy of the header block), this header's copy
  538. // dominates all copied blocks. That means, dominance relations in the
  539. // copied body are the same as in the original body.
  540. if (*BB == Header)
  541. DT->addNewBlock(New, Latches[It - 1]);
  542. else {
  543. auto BBDomNode = DT->getNode(*BB);
  544. auto BBIDom = BBDomNode->getIDom();
  545. BasicBlock *OriginalBBIDom = BBIDom->getBlock();
  546. DT->addNewBlock(
  547. New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
  548. }
  549. }
  550. // Remap all instructions in the most recent iteration
  551. remapInstructionsInBlocks(NewBlocks, LastValueMap);
  552. for (BasicBlock *NewBlock : NewBlocks)
  553. for (Instruction &I : *NewBlock)
  554. if (auto *II = dyn_cast<AssumeInst>(&I))
  555. AC->registerAssumption(II);
  556. {
  557. // Identify what other metadata depends on the cloned version. After
  558. // cloning, replace the metadata with the corrected version for both
  559. // memory instructions and noalias intrinsics.
  560. std::string ext = (Twine("It") + Twine(It)).str();
  561. cloneAndAdaptNoAliasScopes(LoopLocalNoAliasDeclScopes, NewBlocks,
  562. Header->getContext(), ext);
  563. }
  564. }
  565. // Loop over the PHI nodes in the original block, setting incoming values.
  566. for (PHINode *PN : OrigPHINode) {
  567. if (CompletelyUnroll) {
  568. PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
  569. Header->getInstList().erase(PN);
  570. } else if (ULO.Count > 1) {
  571. Value *InVal = PN->removeIncomingValue(LatchBlock, false);
  572. // If this value was defined in the loop, take the value defined by the
  573. // last iteration of the loop.
  574. if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
  575. if (L->contains(InValI))
  576. InVal = LastValueMap[InVal];
  577. }
  578. assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
  579. PN->addIncoming(InVal, Latches.back());
  580. }
  581. }
  582. // Connect latches of the unrolled iterations to the headers of the next
  583. // iteration. Currently they point to the header of the same iteration.
  584. for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
  585. unsigned j = (i + 1) % e;
  586. Latches[i]->getTerminator()->replaceSuccessorWith(Headers[i], Headers[j]);
  587. }
  588. // Update dominators of blocks we might reach through exits.
  589. // Immediate dominator of such block might change, because we add more
  590. // routes which can lead to the exit: we can now reach it from the copied
  591. // iterations too.
  592. if (ULO.Count > 1) {
  593. for (auto *BB : OriginalLoopBlocks) {
  594. auto *BBDomNode = DT->getNode(BB);
  595. SmallVector<BasicBlock *, 16> ChildrenToUpdate;
  596. for (auto *ChildDomNode : BBDomNode->children()) {
  597. auto *ChildBB = ChildDomNode->getBlock();
  598. if (!L->contains(ChildBB))
  599. ChildrenToUpdate.push_back(ChildBB);
  600. }
  601. // The new idom of the block will be the nearest common dominator
  602. // of all copies of the previous idom. This is equivalent to the
  603. // nearest common dominator of the previous idom and the first latch,
  604. // which dominates all copies of the previous idom.
  605. BasicBlock *NewIDom = DT->findNearestCommonDominator(BB, LatchBlock);
  606. for (auto *ChildBB : ChildrenToUpdate)
  607. DT->changeImmediateDominator(ChildBB, NewIDom);
  608. }
  609. }
  610. assert(!UnrollVerifyDomtree ||
  611. DT->verify(DominatorTree::VerificationLevel::Fast));
  612. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
  613. auto SetDest = [&](BasicBlock *Src, bool WillExit, bool ExitOnTrue) {
  614. auto *Term = cast<BranchInst>(Src->getTerminator());
  615. const unsigned Idx = ExitOnTrue ^ WillExit;
  616. BasicBlock *Dest = Term->getSuccessor(Idx);
  617. BasicBlock *DeadSucc = Term->getSuccessor(1-Idx);
  618. // Remove predecessors from all non-Dest successors.
  619. DeadSucc->removePredecessor(Src, /* KeepOneInputPHIs */ true);
  620. // Replace the conditional branch with an unconditional one.
  621. BranchInst::Create(Dest, Term);
  622. Term->eraseFromParent();
  623. DTU.applyUpdates({{DominatorTree::Delete, Src, DeadSucc}});
  624. };
  625. auto WillExit = [&](const ExitInfo &Info, unsigned i, unsigned j,
  626. bool IsLatch) -> Optional<bool> {
  627. if (CompletelyUnroll) {
  628. if (PreserveOnlyFirst) {
  629. if (i == 0)
  630. return None;
  631. return j == 0;
  632. }
  633. // Complete (but possibly inexact) unrolling
  634. if (j == 0)
  635. return true;
  636. if (Info.TripCount && j != Info.TripCount)
  637. return false;
  638. return None;
  639. }
  640. if (ULO.Runtime) {
  641. // If runtime unrolling inserts a prologue, information about non-latch
  642. // exits may be stale.
  643. if (IsLatch && j != 0)
  644. return false;
  645. return None;
  646. }
  647. if (j != Info.BreakoutTrip &&
  648. (Info.TripMultiple == 0 || j % Info.TripMultiple != 0)) {
  649. // If we know the trip count or a multiple of it, we can safely use an
  650. // unconditional branch for some iterations.
  651. return false;
  652. }
  653. return None;
  654. };
  655. // Fold branches for iterations where we know that they will exit or not
  656. // exit.
  657. for (const auto &Pair : ExitInfos) {
  658. const ExitInfo &Info = Pair.second;
  659. for (unsigned i = 0, e = Info.ExitingBlocks.size(); i != e; ++i) {
  660. // The branch destination.
  661. unsigned j = (i + 1) % e;
  662. bool IsLatch = Pair.first == LatchBlock;
  663. Optional<bool> KnownWillExit = WillExit(Info, i, j, IsLatch);
  664. if (!KnownWillExit)
  665. continue;
  666. // We don't fold known-exiting branches for non-latch exits here,
  667. // because this ensures that both all loop blocks and all exit blocks
  668. // remain reachable in the CFG.
  669. // TODO: We could fold these branches, but it would require much more
  670. // sophisticated updates to LoopInfo.
  671. if (*KnownWillExit && !IsLatch)
  672. continue;
  673. SetDest(Info.ExitingBlocks[i], *KnownWillExit, Info.ExitOnTrue);
  674. }
  675. }
  676. // When completely unrolling, the last latch becomes unreachable.
  677. if (!LatchIsExiting && CompletelyUnroll)
  678. changeToUnreachable(Latches.back()->getTerminator(), PreserveLCSSA, &DTU);
  679. // Merge adjacent basic blocks, if possible.
  680. for (BasicBlock *Latch : Latches) {
  681. BranchInst *Term = dyn_cast<BranchInst>(Latch->getTerminator());
  682. assert((Term ||
  683. (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
  684. "Need a branch as terminator, except when fully unrolling with "
  685. "unconditional latch");
  686. if (Term && Term->isUnconditional()) {
  687. BasicBlock *Dest = Term->getSuccessor(0);
  688. BasicBlock *Fold = Dest->getUniquePredecessor();
  689. if (MergeBlockIntoPredecessor(Dest, &DTU, LI)) {
  690. // Dest has been folded into Fold. Update our worklists accordingly.
  691. std::replace(Latches.begin(), Latches.end(), Dest, Fold);
  692. llvm::erase_value(UnrolledLoopBlocks, Dest);
  693. }
  694. }
  695. }
  696. // Apply updates to the DomTree.
  697. DT = &DTU.getDomTree();
  698. assert(!UnrollVerifyDomtree ||
  699. DT->verify(DominatorTree::VerificationLevel::Fast));
  700. // At this point, the code is well formed. We now simplify the unrolled loop,
  701. // doing constant propagation and dead code elimination as we go.
  702. simplifyLoopAfterUnroll(L, !CompletelyUnroll && ULO.Count > 1, LI, SE, DT, AC,
  703. TTI);
  704. NumCompletelyUnrolled += CompletelyUnroll;
  705. ++NumUnrolled;
  706. Loop *OuterL = L->getParentLoop();
  707. // Update LoopInfo if the loop is completely removed.
  708. if (CompletelyUnroll)
  709. LI->erase(L);
  710. // LoopInfo should not be valid, confirm that.
  711. if (UnrollVerifyLoopInfo)
  712. LI->verify(*DT);
  713. // After complete unrolling most of the blocks should be contained in OuterL.
  714. // However, some of them might happen to be out of OuterL (e.g. if they
  715. // precede a loop exit). In this case we might need to insert PHI nodes in
  716. // order to preserve LCSSA form.
  717. // We don't need to check this if we already know that we need to fix LCSSA
  718. // form.
  719. // TODO: For now we just recompute LCSSA for the outer loop in this case, but
  720. // it should be possible to fix it in-place.
  721. if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
  722. NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
  723. // Make sure that loop-simplify form is preserved. We want to simplify
  724. // at least one layer outside of the loop that was unrolled so that any
  725. // changes to the parent loop exposed by the unrolling are considered.
  726. if (OuterL) {
  727. // OuterL includes all loops for which we can break loop-simplify, so
  728. // it's sufficient to simplify only it (it'll recursively simplify inner
  729. // loops too).
  730. if (NeedToFixLCSSA) {
  731. // LCSSA must be performed on the outermost affected loop. The unrolled
  732. // loop's last loop latch is guaranteed to be in the outermost loop
  733. // after LoopInfo's been updated by LoopInfo::erase.
  734. Loop *LatchLoop = LI->getLoopFor(Latches.back());
  735. Loop *FixLCSSALoop = OuterL;
  736. if (!FixLCSSALoop->contains(LatchLoop))
  737. while (FixLCSSALoop->getParentLoop() != LatchLoop)
  738. FixLCSSALoop = FixLCSSALoop->getParentLoop();
  739. formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE);
  740. } else if (PreserveLCSSA) {
  741. assert(OuterL->isLCSSAForm(*DT) &&
  742. "Loops should be in LCSSA form after loop-unroll.");
  743. }
  744. // TODO: That potentially might be compile-time expensive. We should try
  745. // to fix the loop-simplified form incrementally.
  746. simplifyLoop(OuterL, DT, LI, SE, AC, nullptr, PreserveLCSSA);
  747. } else {
  748. // Simplify loops for which we might've broken loop-simplify form.
  749. for (Loop *SubLoop : LoopsToSimplify)
  750. simplifyLoop(SubLoop, DT, LI, SE, AC, nullptr, PreserveLCSSA);
  751. }
  752. return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
  753. : LoopUnrollResult::PartiallyUnrolled;
  754. }
  755. /// Given an llvm.loop loop id metadata node, returns the loop hint metadata
  756. /// node with the given name (for example, "llvm.loop.unroll.count"). If no
  757. /// such metadata node exists, then nullptr is returned.
  758. MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
  759. // First operand should refer to the loop id itself.
  760. assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
  761. assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
  762. for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
  763. MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
  764. if (!MD)
  765. continue;
  766. MDString *S = dyn_cast<MDString>(MD->getOperand(0));
  767. if (!S)
  768. continue;
  769. if (Name.equals(S->getString()))
  770. return MD;
  771. }
  772. return nullptr;
  773. }