LoopUnrollRuntime.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. //===-- UnrollLoopRuntime.cpp - Runtime 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 for loops with run-time
  10. // trip counts. See LoopUnroll.cpp for unrolling loops with compile-time
  11. // trip counts.
  12. //
  13. // The functions in this file are used to generate extra code when the
  14. // run-time trip count modulo the unroll factor is not 0. When this is the
  15. // case, we need to generate code to execute these 'left over' iterations.
  16. //
  17. // The current strategy generates an if-then-else sequence prior to the
  18. // unrolled loop to execute the 'left over' iterations before or after the
  19. // unrolled loop.
  20. //
  21. //===----------------------------------------------------------------------===//
  22. #include "llvm/ADT/SmallPtrSet.h"
  23. #include "llvm/ADT/Statistic.h"
  24. #include "llvm/Analysis/AliasAnalysis.h"
  25. #include "llvm/Analysis/LoopIterator.h"
  26. #include "llvm/Analysis/ScalarEvolution.h"
  27. #include "llvm/Analysis/ScalarEvolutionExpander.h"
  28. #include "llvm/IR/BasicBlock.h"
  29. #include "llvm/IR/Dominators.h"
  30. #include "llvm/IR/Metadata.h"
  31. #include "llvm/IR/Module.h"
  32. #include "llvm/Support/Debug.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include "llvm/Transforms/Utils.h"
  35. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  36. #include "llvm/Transforms/Utils/Cloning.h"
  37. #include "llvm/Transforms/Utils/LoopUtils.h"
  38. #include "llvm/Transforms/Utils/UnrollLoop.h"
  39. #include <algorithm>
  40. using namespace llvm;
  41. #define DEBUG_TYPE "loop-unroll"
  42. STATISTIC(NumRuntimeUnrolled,
  43. "Number of loops unrolled with run-time trip counts");
  44. static cl::opt<bool> UnrollRuntimeMultiExit(
  45. "unroll-runtime-multi-exit", cl::init(false), cl::Hidden,
  46. cl::desc("Allow runtime unrolling for loops with multiple exits, when "
  47. "epilog is generated"));
  48. /// Connect the unrolling prolog code to the original loop.
  49. /// The unrolling prolog code contains code to execute the
  50. /// 'extra' iterations if the run-time trip count modulo the
  51. /// unroll count is non-zero.
  52. ///
  53. /// This function performs the following:
  54. /// - Create PHI nodes at prolog end block to combine values
  55. /// that exit the prolog code and jump around the prolog.
  56. /// - Add a PHI operand to a PHI node at the loop exit block
  57. /// for values that exit the prolog and go around the loop.
  58. /// - Branch around the original loop if the trip count is less
  59. /// than the unroll factor.
  60. ///
  61. static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
  62. BasicBlock *PrologExit,
  63. BasicBlock *OriginalLoopLatchExit,
  64. BasicBlock *PreHeader, BasicBlock *NewPreHeader,
  65. ValueToValueMapTy &VMap, DominatorTree *DT,
  66. LoopInfo *LI, bool PreserveLCSSA) {
  67. // Loop structure should be the following:
  68. // Preheader
  69. // PrologHeader
  70. // ...
  71. // PrologLatch
  72. // PrologExit
  73. // NewPreheader
  74. // Header
  75. // ...
  76. // Latch
  77. // LatchExit
  78. BasicBlock *Latch = L->getLoopLatch();
  79. assert(Latch && "Loop must have a latch");
  80. BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]);
  81. // Create a PHI node for each outgoing value from the original loop
  82. // (which means it is an outgoing value from the prolog code too).
  83. // The new PHI node is inserted in the prolog end basic block.
  84. // The new PHI node value is added as an operand of a PHI node in either
  85. // the loop header or the loop exit block.
  86. for (BasicBlock *Succ : successors(Latch)) {
  87. for (PHINode &PN : Succ->phis()) {
  88. // Add a new PHI node to the prolog end block and add the
  89. // appropriate incoming values.
  90. // TODO: This code assumes that the PrologExit (or the LatchExit block for
  91. // prolog loop) contains only one predecessor from the loop, i.e. the
  92. // PrologLatch. When supporting multiple-exiting block loops, we can have
  93. // two or more blocks that have the LatchExit as the target in the
  94. // original loop.
  95. PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr",
  96. PrologExit->getFirstNonPHI());
  97. // Adding a value to the new PHI node from the original loop preheader.
  98. // This is the value that skips all the prolog code.
  99. if (L->contains(&PN)) {
  100. // Succ is loop header.
  101. NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader),
  102. PreHeader);
  103. } else {
  104. // Succ is LatchExit.
  105. NewPN->addIncoming(UndefValue::get(PN.getType()), PreHeader);
  106. }
  107. Value *V = PN.getIncomingValueForBlock(Latch);
  108. if (Instruction *I = dyn_cast<Instruction>(V)) {
  109. if (L->contains(I)) {
  110. V = VMap.lookup(I);
  111. }
  112. }
  113. // Adding a value to the new PHI node from the last prolog block
  114. // that was created.
  115. NewPN->addIncoming(V, PrologLatch);
  116. // Update the existing PHI node operand with the value from the
  117. // new PHI node. How this is done depends on if the existing
  118. // PHI node is in the original loop block, or the exit block.
  119. if (L->contains(&PN))
  120. PN.setIncomingValueForBlock(NewPreHeader, NewPN);
  121. else
  122. PN.addIncoming(NewPN, PrologExit);
  123. }
  124. }
  125. // Make sure that created prolog loop is in simplified form
  126. SmallVector<BasicBlock *, 4> PrologExitPreds;
  127. Loop *PrologLoop = LI->getLoopFor(PrologLatch);
  128. if (PrologLoop) {
  129. for (BasicBlock *PredBB : predecessors(PrologExit))
  130. if (PrologLoop->contains(PredBB))
  131. PrologExitPreds.push_back(PredBB);
  132. SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI,
  133. nullptr, PreserveLCSSA);
  134. }
  135. // Create a branch around the original loop, which is taken if there are no
  136. // iterations remaining to be executed after running the prologue.
  137. Instruction *InsertPt = PrologExit->getTerminator();
  138. IRBuilder<> B(InsertPt);
  139. assert(Count != 0 && "nonsensical Count!");
  140. // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1)
  141. // This means %xtraiter is (BECount + 1) and all of the iterations of this
  142. // loop were executed by the prologue. Note that if BECount <u (Count - 1)
  143. // then (BECount + 1) cannot unsigned-overflow.
  144. Value *BrLoopExit =
  145. B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1));
  146. // Split the exit to maintain loop canonicalization guarantees
  147. SmallVector<BasicBlock *, 4> Preds(predecessors(OriginalLoopLatchExit));
  148. SplitBlockPredecessors(OriginalLoopLatchExit, Preds, ".unr-lcssa", DT, LI,
  149. nullptr, PreserveLCSSA);
  150. // Add the branch to the exit block (around the unrolled loop)
  151. B.CreateCondBr(BrLoopExit, OriginalLoopLatchExit, NewPreHeader);
  152. InsertPt->eraseFromParent();
  153. if (DT)
  154. DT->changeImmediateDominator(OriginalLoopLatchExit, PrologExit);
  155. }
  156. /// Connect the unrolling epilog code to the original loop.
  157. /// The unrolling epilog code contains code to execute the
  158. /// 'extra' iterations if the run-time trip count modulo the
  159. /// unroll count is non-zero.
  160. ///
  161. /// This function performs the following:
  162. /// - Update PHI nodes at the unrolling loop exit and epilog loop exit
  163. /// - Create PHI nodes at the unrolling loop exit to combine
  164. /// values that exit the unrolling loop code and jump around it.
  165. /// - Update PHI operands in the epilog loop by the new PHI nodes
  166. /// - Branch around the epilog loop if extra iters (ModVal) is zero.
  167. ///
  168. static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit,
  169. BasicBlock *Exit, BasicBlock *PreHeader,
  170. BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader,
  171. ValueToValueMapTy &VMap, DominatorTree *DT,
  172. LoopInfo *LI, bool PreserveLCSSA) {
  173. BasicBlock *Latch = L->getLoopLatch();
  174. assert(Latch && "Loop must have a latch");
  175. BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]);
  176. // Loop structure should be the following:
  177. //
  178. // PreHeader
  179. // NewPreHeader
  180. // Header
  181. // ...
  182. // Latch
  183. // NewExit (PN)
  184. // EpilogPreHeader
  185. // EpilogHeader
  186. // ...
  187. // EpilogLatch
  188. // Exit (EpilogPN)
  189. // Update PHI nodes at NewExit and Exit.
  190. for (PHINode &PN : NewExit->phis()) {
  191. // PN should be used in another PHI located in Exit block as
  192. // Exit was split by SplitBlockPredecessors into Exit and NewExit
  193. // Basicaly it should look like:
  194. // NewExit:
  195. // PN = PHI [I, Latch]
  196. // ...
  197. // Exit:
  198. // EpilogPN = PHI [PN, EpilogPreHeader]
  199. //
  200. // There is EpilogPreHeader incoming block instead of NewExit as
  201. // NewExit was spilt 1 more time to get EpilogPreHeader.
  202. assert(PN.hasOneUse() && "The phi should have 1 use");
  203. PHINode *EpilogPN = cast<PHINode>(PN.use_begin()->getUser());
  204. assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block");
  205. // Add incoming PreHeader from branch around the Loop
  206. PN.addIncoming(UndefValue::get(PN.getType()), PreHeader);
  207. Value *V = PN.getIncomingValueForBlock(Latch);
  208. Instruction *I = dyn_cast<Instruction>(V);
  209. if (I && L->contains(I))
  210. // If value comes from an instruction in the loop add VMap value.
  211. V = VMap.lookup(I);
  212. // For the instruction out of the loop, constant or undefined value
  213. // insert value itself.
  214. EpilogPN->addIncoming(V, EpilogLatch);
  215. assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 &&
  216. "EpilogPN should have EpilogPreHeader incoming block");
  217. // Change EpilogPreHeader incoming block to NewExit.
  218. EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader),
  219. NewExit);
  220. // Now PHIs should look like:
  221. // NewExit:
  222. // PN = PHI [I, Latch], [undef, PreHeader]
  223. // ...
  224. // Exit:
  225. // EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch]
  226. }
  227. // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader).
  228. // Update corresponding PHI nodes in epilog loop.
  229. for (BasicBlock *Succ : successors(Latch)) {
  230. // Skip this as we already updated phis in exit blocks.
  231. if (!L->contains(Succ))
  232. continue;
  233. for (PHINode &PN : Succ->phis()) {
  234. // Add new PHI nodes to the loop exit block and update epilog
  235. // PHIs with the new PHI values.
  236. PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr",
  237. NewExit->getFirstNonPHI());
  238. // Adding a value to the new PHI node from the unrolling loop preheader.
  239. NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader), PreHeader);
  240. // Adding a value to the new PHI node from the unrolling loop latch.
  241. NewPN->addIncoming(PN.getIncomingValueForBlock(Latch), Latch);
  242. // Update the existing PHI node operand with the value from the new PHI
  243. // node. Corresponding instruction in epilog loop should be PHI.
  244. PHINode *VPN = cast<PHINode>(VMap[&PN]);
  245. VPN->setIncomingValueForBlock(EpilogPreHeader, NewPN);
  246. }
  247. }
  248. Instruction *InsertPt = NewExit->getTerminator();
  249. IRBuilder<> B(InsertPt);
  250. Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod");
  251. assert(Exit && "Loop must have a single exit block only");
  252. // Split the epilogue exit to maintain loop canonicalization guarantees
  253. SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
  254. SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI, nullptr,
  255. PreserveLCSSA);
  256. // Add the branch to the exit block (around the unrolling loop)
  257. B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit);
  258. InsertPt->eraseFromParent();
  259. if (DT)
  260. DT->changeImmediateDominator(Exit, NewExit);
  261. // Split the main loop exit to maintain canonicalization guarantees.
  262. SmallVector<BasicBlock*, 4> NewExitPreds{Latch};
  263. SplitBlockPredecessors(NewExit, NewExitPreds, ".loopexit", DT, LI, nullptr,
  264. PreserveLCSSA);
  265. }
  266. /// Create a clone of the blocks in a loop and connect them together.
  267. /// If CreateRemainderLoop is false, loop structure will not be cloned,
  268. /// otherwise a new loop will be created including all cloned blocks, and the
  269. /// iterator of it switches to count NewIter down to 0.
  270. /// The cloned blocks should be inserted between InsertTop and InsertBot.
  271. /// If loop structure is cloned InsertTop should be new preheader, InsertBot
  272. /// new loop exit.
  273. /// Return the new cloned loop that is created when CreateRemainderLoop is true.
  274. static Loop *
  275. CloneLoopBlocks(Loop *L, Value *NewIter, const bool CreateRemainderLoop,
  276. const bool UseEpilogRemainder, const bool UnrollRemainder,
  277. BasicBlock *InsertTop,
  278. BasicBlock *InsertBot, BasicBlock *Preheader,
  279. std::vector<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks,
  280. ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI) {
  281. StringRef suffix = UseEpilogRemainder ? "epil" : "prol";
  282. BasicBlock *Header = L->getHeader();
  283. BasicBlock *Latch = L->getLoopLatch();
  284. Function *F = Header->getParent();
  285. LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
  286. LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
  287. Loop *ParentLoop = L->getParentLoop();
  288. NewLoopsMap NewLoops;
  289. NewLoops[ParentLoop] = ParentLoop;
  290. if (!CreateRemainderLoop)
  291. NewLoops[L] = ParentLoop;
  292. // For each block in the original loop, create a new copy,
  293. // and update the value map with the newly created values.
  294. for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
  295. BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F);
  296. NewBlocks.push_back(NewBB);
  297. // If we're unrolling the outermost loop, there's no remainder loop,
  298. // and this block isn't in a nested loop, then the new block is not
  299. // in any loop. Otherwise, add it to loopinfo.
  300. if (CreateRemainderLoop || LI->getLoopFor(*BB) != L || ParentLoop)
  301. addClonedBlockToLoopInfo(*BB, NewBB, LI, NewLoops);
  302. VMap[*BB] = NewBB;
  303. if (Header == *BB) {
  304. // For the first block, add a CFG connection to this newly
  305. // created block.
  306. InsertTop->getTerminator()->setSuccessor(0, NewBB);
  307. }
  308. if (DT) {
  309. if (Header == *BB) {
  310. // The header is dominated by the preheader.
  311. DT->addNewBlock(NewBB, InsertTop);
  312. } else {
  313. // Copy information from original loop to unrolled loop.
  314. BasicBlock *IDomBB = DT->getNode(*BB)->getIDom()->getBlock();
  315. DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB]));
  316. }
  317. }
  318. if (Latch == *BB) {
  319. // For the last block, if CreateRemainderLoop is false, create a direct
  320. // jump to InsertBot. If not, create a loop back to cloned head.
  321. VMap.erase((*BB)->getTerminator());
  322. BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
  323. BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
  324. IRBuilder<> Builder(LatchBR);
  325. if (!CreateRemainderLoop) {
  326. Builder.CreateBr(InsertBot);
  327. } else {
  328. PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2,
  329. suffix + ".iter",
  330. FirstLoopBB->getFirstNonPHI());
  331. Value *IdxSub =
  332. Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
  333. NewIdx->getName() + ".sub");
  334. Value *IdxCmp =
  335. Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
  336. Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot);
  337. NewIdx->addIncoming(NewIter, InsertTop);
  338. NewIdx->addIncoming(IdxSub, NewBB);
  339. }
  340. LatchBR->eraseFromParent();
  341. }
  342. }
  343. // Change the incoming values to the ones defined in the preheader or
  344. // cloned loop.
  345. for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
  346. PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
  347. if (!CreateRemainderLoop) {
  348. if (UseEpilogRemainder) {
  349. unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
  350. NewPHI->setIncomingBlock(idx, InsertTop);
  351. NewPHI->removeIncomingValue(Latch, false);
  352. } else {
  353. VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader);
  354. cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
  355. }
  356. } else {
  357. unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
  358. NewPHI->setIncomingBlock(idx, InsertTop);
  359. BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
  360. idx = NewPHI->getBasicBlockIndex(Latch);
  361. Value *InVal = NewPHI->getIncomingValue(idx);
  362. NewPHI->setIncomingBlock(idx, NewLatch);
  363. if (Value *V = VMap.lookup(InVal))
  364. NewPHI->setIncomingValue(idx, V);
  365. }
  366. }
  367. if (CreateRemainderLoop) {
  368. Loop *NewLoop = NewLoops[L];
  369. MDNode *LoopID = NewLoop->getLoopID();
  370. assert(NewLoop && "L should have been cloned");
  371. // Only add loop metadata if the loop is not going to be completely
  372. // unrolled.
  373. if (UnrollRemainder)
  374. return NewLoop;
  375. Optional<MDNode *> NewLoopID = makeFollowupLoopID(
  376. LoopID, {LLVMLoopUnrollFollowupAll, LLVMLoopUnrollFollowupRemainder});
  377. if (NewLoopID.hasValue()) {
  378. NewLoop->setLoopID(NewLoopID.getValue());
  379. // Do not setLoopAlreadyUnrolled if loop attributes have been defined
  380. // explicitly.
  381. return NewLoop;
  382. }
  383. // Add unroll disable metadata to disable future unrolling for this loop.
  384. NewLoop->setLoopAlreadyUnrolled();
  385. return NewLoop;
  386. }
  387. else
  388. return nullptr;
  389. }
  390. /// Returns true if we can safely unroll a multi-exit/exiting loop. OtherExits
  391. /// is populated with all the loop exit blocks other than the LatchExit block.
  392. static bool
  393. canSafelyUnrollMultiExitLoop(Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits,
  394. BasicBlock *LatchExit, bool PreserveLCSSA,
  395. bool UseEpilogRemainder) {
  396. // We currently have some correctness constrains in unrolling a multi-exit
  397. // loop. Check for these below.
  398. // We rely on LCSSA form being preserved when the exit blocks are transformed.
  399. if (!PreserveLCSSA)
  400. return false;
  401. SmallVector<BasicBlock *, 4> Exits;
  402. L->getUniqueExitBlocks(Exits);
  403. for (auto *BB : Exits)
  404. if (BB != LatchExit)
  405. OtherExits.push_back(BB);
  406. // TODO: Support multiple exiting blocks jumping to the `LatchExit` when
  407. // UnrollRuntimeMultiExit is true. This will need updating the logic in
  408. // connectEpilog/connectProlog.
  409. if (!LatchExit->getSinglePredecessor()) {
  410. LLVM_DEBUG(
  411. dbgs() << "Bailout for multi-exit handling when latch exit has >1 "
  412. "predecessor.\n");
  413. return false;
  414. }
  415. // FIXME: We bail out of multi-exit unrolling when epilog loop is generated
  416. // and L is an inner loop. This is because in presence of multiple exits, the
  417. // outer loop is incorrect: we do not add the EpilogPreheader and exit to the
  418. // outer loop. This is automatically handled in the prolog case, so we do not
  419. // have that bug in prolog generation.
  420. if (UseEpilogRemainder && L->getParentLoop())
  421. return false;
  422. // All constraints have been satisfied.
  423. return true;
  424. }
  425. /// Returns true if we can profitably unroll the multi-exit loop L. Currently,
  426. /// we return true only if UnrollRuntimeMultiExit is set to true.
  427. static bool canProfitablyUnrollMultiExitLoop(
  428. Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits, BasicBlock *LatchExit,
  429. bool PreserveLCSSA, bool UseEpilogRemainder) {
  430. #if !defined(NDEBUG)
  431. SmallVector<BasicBlock *, 8> OtherExitsDummyCheck;
  432. assert(canSafelyUnrollMultiExitLoop(L, OtherExitsDummyCheck, LatchExit,
  433. PreserveLCSSA, UseEpilogRemainder) &&
  434. "Should be safe to unroll before checking profitability!");
  435. #endif
  436. // Priority goes to UnrollRuntimeMultiExit if it's supplied.
  437. if (UnrollRuntimeMultiExit.getNumOccurrences())
  438. return UnrollRuntimeMultiExit;
  439. // The main pain point with multi-exit loop unrolling is that once unrolled,
  440. // we will not be able to merge all blocks into a straight line code.
  441. // There are branches within the unrolled loop that go to the OtherExits.
  442. // The second point is the increase in code size, but this is true
  443. // irrespective of multiple exits.
  444. // Note: Both the heuristics below are coarse grained. We are essentially
  445. // enabling unrolling of loops that have a single side exit other than the
  446. // normal LatchExit (i.e. exiting into a deoptimize block).
  447. // The heuristics considered are:
  448. // 1. low number of branches in the unrolled version.
  449. // 2. high predictability of these extra branches.
  450. // We avoid unrolling loops that have more than two exiting blocks. This
  451. // limits the total number of branches in the unrolled loop to be atmost
  452. // the unroll factor (since one of the exiting blocks is the latch block).
  453. SmallVector<BasicBlock*, 4> ExitingBlocks;
  454. L->getExitingBlocks(ExitingBlocks);
  455. if (ExitingBlocks.size() > 2)
  456. return false;
  457. // The second heuristic is that L has one exit other than the latchexit and
  458. // that exit is a deoptimize block. We know that deoptimize blocks are rarely
  459. // taken, which also implies the branch leading to the deoptimize block is
  460. // highly predictable.
  461. return (OtherExits.size() == 1 &&
  462. OtherExits[0]->getTerminatingDeoptimizeCall());
  463. // TODO: These can be fine-tuned further to consider code size or deopt states
  464. // that are captured by the deoptimize exit block.
  465. // Also, we can extend this to support more cases, if we actually
  466. // know of kinds of multiexit loops that would benefit from unrolling.
  467. }
  468. /// Insert code in the prolog/epilog code when unrolling a loop with a
  469. /// run-time trip-count.
  470. ///
  471. /// This method assumes that the loop unroll factor is total number
  472. /// of loop bodies in the loop after unrolling. (Some folks refer
  473. /// to the unroll factor as the number of *extra* copies added).
  474. /// We assume also that the loop unroll factor is a power-of-two. So, after
  475. /// unrolling the loop, the number of loop bodies executed is 2,
  476. /// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch
  477. /// instruction in SimplifyCFG.cpp. Then, the backend decides how code for
  478. /// the switch instruction is generated.
  479. ///
  480. /// ***Prolog case***
  481. /// extraiters = tripcount % loopfactor
  482. /// if (extraiters == 0) jump Loop:
  483. /// else jump Prol:
  484. /// Prol: LoopBody;
  485. /// extraiters -= 1 // Omitted if unroll factor is 2.
  486. /// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
  487. /// if (tripcount < loopfactor) jump End:
  488. /// Loop:
  489. /// ...
  490. /// End:
  491. ///
  492. /// ***Epilog case***
  493. /// extraiters = tripcount % loopfactor
  494. /// if (tripcount < loopfactor) jump LoopExit:
  495. /// unroll_iters = tripcount - extraiters
  496. /// Loop: LoopBody; (executes unroll_iter times);
  497. /// unroll_iter -= 1
  498. /// if (unroll_iter != 0) jump Loop:
  499. /// LoopExit:
  500. /// if (extraiters == 0) jump EpilExit:
  501. /// Epil: LoopBody; (executes extraiters times)
  502. /// extraiters -= 1 // Omitted if unroll factor is 2.
  503. /// if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
  504. /// EpilExit:
  505. bool llvm::UnrollRuntimeLoopRemainder(Loop *L, unsigned Count,
  506. bool AllowExpensiveTripCount,
  507. bool UseEpilogRemainder,
  508. bool UnrollRemainder, bool ForgetAllSCEV,
  509. LoopInfo *LI, ScalarEvolution *SE,
  510. DominatorTree *DT, AssumptionCache *AC,
  511. bool PreserveLCSSA, Loop **ResultLoop) {
  512. LLVM_DEBUG(dbgs() << "Trying runtime unrolling on Loop: \n");
  513. LLVM_DEBUG(L->dump());
  514. LLVM_DEBUG(UseEpilogRemainder ? dbgs() << "Using epilog remainder.\n"
  515. : dbgs() << "Using prolog remainder.\n");
  516. // Make sure the loop is in canonical form.
  517. if (!L->isLoopSimplifyForm()) {
  518. LLVM_DEBUG(dbgs() << "Not in simplify form!\n");
  519. return false;
  520. }
  521. // Guaranteed by LoopSimplifyForm.
  522. BasicBlock *Latch = L->getLoopLatch();
  523. BasicBlock *Header = L->getHeader();
  524. BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
  525. if (!LatchBR || LatchBR->isUnconditional()) {
  526. // The loop-rotate pass can be helpful to avoid this in many cases.
  527. LLVM_DEBUG(
  528. dbgs()
  529. << "Loop latch not terminated by a conditional branch.\n");
  530. return false;
  531. }
  532. unsigned ExitIndex = LatchBR->getSuccessor(0) == Header ? 1 : 0;
  533. BasicBlock *LatchExit = LatchBR->getSuccessor(ExitIndex);
  534. if (L->contains(LatchExit)) {
  535. // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the
  536. // targets of the Latch be an exit block out of the loop.
  537. LLVM_DEBUG(
  538. dbgs()
  539. << "One of the loop latch successors must be the exit block.\n");
  540. return false;
  541. }
  542. // These are exit blocks other than the target of the latch exiting block.
  543. SmallVector<BasicBlock *, 4> OtherExits;
  544. bool isMultiExitUnrollingEnabled =
  545. canSafelyUnrollMultiExitLoop(L, OtherExits, LatchExit, PreserveLCSSA,
  546. UseEpilogRemainder) &&
  547. canProfitablyUnrollMultiExitLoop(L, OtherExits, LatchExit, PreserveLCSSA,
  548. UseEpilogRemainder);
  549. // Support only single exit and exiting block unless multi-exit loop unrolling is enabled.
  550. if (!isMultiExitUnrollingEnabled &&
  551. (!L->getExitingBlock() || OtherExits.size())) {
  552. LLVM_DEBUG(
  553. dbgs()
  554. << "Multiple exit/exiting blocks in loop and multi-exit unrolling not "
  555. "enabled!\n");
  556. return false;
  557. }
  558. // Use Scalar Evolution to compute the trip count. This allows more loops to
  559. // be unrolled than relying on induction var simplification.
  560. if (!SE)
  561. return false;
  562. // Only unroll loops with a computable trip count, and the trip count needs
  563. // to be an int value (allowing a pointer type is a TODO item).
  564. // We calculate the backedge count by using getExitCount on the Latch block,
  565. // which is proven to be the only exiting block in this loop. This is same as
  566. // calculating getBackedgeTakenCount on the loop (which computes SCEV for all
  567. // exiting blocks).
  568. const SCEV *BECountSC = SE->getExitCount(L, Latch);
  569. if (isa<SCEVCouldNotCompute>(BECountSC) ||
  570. !BECountSC->getType()->isIntegerTy()) {
  571. LLVM_DEBUG(dbgs() << "Could not compute exit block SCEV\n");
  572. return false;
  573. }
  574. unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
  575. // Add 1 since the backedge count doesn't include the first loop iteration.
  576. const SCEV *TripCountSC =
  577. SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
  578. if (isa<SCEVCouldNotCompute>(TripCountSC)) {
  579. LLVM_DEBUG(dbgs() << "Could not compute trip count SCEV.\n");
  580. return false;
  581. }
  582. BasicBlock *PreHeader = L->getLoopPreheader();
  583. BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
  584. const DataLayout &DL = Header->getModule()->getDataLayout();
  585. SCEVExpander Expander(*SE, DL, "loop-unroll");
  586. if (!AllowExpensiveTripCount &&
  587. Expander.isHighCostExpansion(TripCountSC, L, PreHeaderBR)) {
  588. LLVM_DEBUG(dbgs() << "High cost for expanding trip count scev!\n");
  589. return false;
  590. }
  591. // This constraint lets us deal with an overflowing trip count easily; see the
  592. // comment on ModVal below.
  593. if (Log2_32(Count) > BEWidth) {
  594. LLVM_DEBUG(
  595. dbgs()
  596. << "Count failed constraint on overflow trip count calculation.\n");
  597. return false;
  598. }
  599. // Loop structure is the following:
  600. //
  601. // PreHeader
  602. // Header
  603. // ...
  604. // Latch
  605. // LatchExit
  606. BasicBlock *NewPreHeader;
  607. BasicBlock *NewExit = nullptr;
  608. BasicBlock *PrologExit = nullptr;
  609. BasicBlock *EpilogPreHeader = nullptr;
  610. BasicBlock *PrologPreHeader = nullptr;
  611. if (UseEpilogRemainder) {
  612. // If epilog remainder
  613. // Split PreHeader to insert a branch around loop for unrolling.
  614. NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI);
  615. NewPreHeader->setName(PreHeader->getName() + ".new");
  616. // Split LatchExit to create phi nodes from branch above.
  617. SmallVector<BasicBlock*, 4> Preds(predecessors(LatchExit));
  618. NewExit = SplitBlockPredecessors(LatchExit, Preds, ".unr-lcssa", DT, LI,
  619. nullptr, PreserveLCSSA);
  620. // NewExit gets its DebugLoc from LatchExit, which is not part of the
  621. // original Loop.
  622. // Fix this by setting Loop's DebugLoc to NewExit.
  623. auto *NewExitTerminator = NewExit->getTerminator();
  624. NewExitTerminator->setDebugLoc(Header->getTerminator()->getDebugLoc());
  625. // Split NewExit to insert epilog remainder loop.
  626. EpilogPreHeader = SplitBlock(NewExit, NewExitTerminator, DT, LI);
  627. EpilogPreHeader->setName(Header->getName() + ".epil.preheader");
  628. } else {
  629. // If prolog remainder
  630. // Split the original preheader twice to insert prolog remainder loop
  631. PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI);
  632. PrologPreHeader->setName(Header->getName() + ".prol.preheader");
  633. PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(),
  634. DT, LI);
  635. PrologExit->setName(Header->getName() + ".prol.loopexit");
  636. // Split PrologExit to get NewPreHeader.
  637. NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI);
  638. NewPreHeader->setName(PreHeader->getName() + ".new");
  639. }
  640. // Loop structure should be the following:
  641. // Epilog Prolog
  642. //
  643. // PreHeader PreHeader
  644. // *NewPreHeader *PrologPreHeader
  645. // Header *PrologExit
  646. // ... *NewPreHeader
  647. // Latch Header
  648. // *NewExit ...
  649. // *EpilogPreHeader Latch
  650. // LatchExit LatchExit
  651. // Calculate conditions for branch around loop for unrolling
  652. // in epilog case and around prolog remainder loop in prolog case.
  653. // Compute the number of extra iterations required, which is:
  654. // extra iterations = run-time trip count % loop unroll factor
  655. PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
  656. Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
  657. PreHeaderBR);
  658. Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(),
  659. PreHeaderBR);
  660. IRBuilder<> B(PreHeaderBR);
  661. Value *ModVal;
  662. // Calculate ModVal = (BECount + 1) % Count.
  663. // Note that TripCount is BECount + 1.
  664. if (isPowerOf2_32(Count)) {
  665. // When Count is power of 2 we don't BECount for epilog case, however we'll
  666. // need it for a branch around unrolling loop for prolog case.
  667. ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter");
  668. // 1. There are no iterations to be run in the prolog/epilog loop.
  669. // OR
  670. // 2. The addition computing TripCount overflowed.
  671. //
  672. // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
  673. // the number of iterations that remain to be run in the original loop is a
  674. // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we
  675. // explicitly check this above).
  676. } else {
  677. // As (BECount + 1) can potentially unsigned overflow we count
  678. // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
  679. Value *ModValTmp = B.CreateURem(BECount,
  680. ConstantInt::get(BECount->getType(),
  681. Count));
  682. Value *ModValAdd = B.CreateAdd(ModValTmp,
  683. ConstantInt::get(ModValTmp->getType(), 1));
  684. // At that point (BECount % Count) + 1 could be equal to Count.
  685. // To handle this case we need to take mod by Count one more time.
  686. ModVal = B.CreateURem(ModValAdd,
  687. ConstantInt::get(BECount->getType(), Count),
  688. "xtraiter");
  689. }
  690. Value *BranchVal =
  691. UseEpilogRemainder ? B.CreateICmpULT(BECount,
  692. ConstantInt::get(BECount->getType(),
  693. Count - 1)) :
  694. B.CreateIsNotNull(ModVal, "lcmp.mod");
  695. BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader;
  696. BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit;
  697. // Branch to either remainder (extra iterations) loop or unrolling loop.
  698. B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop);
  699. PreHeaderBR->eraseFromParent();
  700. if (DT) {
  701. if (UseEpilogRemainder)
  702. DT->changeImmediateDominator(NewExit, PreHeader);
  703. else
  704. DT->changeImmediateDominator(PrologExit, PreHeader);
  705. }
  706. Function *F = Header->getParent();
  707. // Get an ordered list of blocks in the loop to help with the ordering of the
  708. // cloned blocks in the prolog/epilog code
  709. LoopBlocksDFS LoopBlocks(L);
  710. LoopBlocks.perform(LI);
  711. //
  712. // For each extra loop iteration, create a copy of the loop's basic blocks
  713. // and generate a condition that branches to the copy depending on the
  714. // number of 'left over' iterations.
  715. //
  716. std::vector<BasicBlock *> NewBlocks;
  717. ValueToValueMapTy VMap;
  718. // For unroll factor 2 remainder loop will have 1 iterations.
  719. // Do not create 1 iteration loop.
  720. bool CreateRemainderLoop = (Count != 2);
  721. // Clone all the basic blocks in the loop. If Count is 2, we don't clone
  722. // the loop, otherwise we create a cloned loop to execute the extra
  723. // iterations. This function adds the appropriate CFG connections.
  724. BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit;
  725. BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
  726. Loop *remainderLoop = CloneLoopBlocks(
  727. L, ModVal, CreateRemainderLoop, UseEpilogRemainder, UnrollRemainder,
  728. InsertTop, InsertBot,
  729. NewPreHeader, NewBlocks, LoopBlocks, VMap, DT, LI);
  730. // Insert the cloned blocks into the function.
  731. F->getBasicBlockList().splice(InsertBot->getIterator(),
  732. F->getBasicBlockList(),
  733. NewBlocks[0]->getIterator(),
  734. F->end());
  735. // Now the loop blocks are cloned and the other exiting blocks from the
  736. // remainder are connected to the original Loop's exit blocks. The remaining
  737. // work is to update the phi nodes in the original loop, and take in the
  738. // values from the cloned region.
  739. for (auto *BB : OtherExits) {
  740. for (auto &II : *BB) {
  741. // Given we preserve LCSSA form, we know that the values used outside the
  742. // loop will be used through these phi nodes at the exit blocks that are
  743. // transformed below.
  744. if (!isa<PHINode>(II))
  745. break;
  746. PHINode *Phi = cast<PHINode>(&II);
  747. unsigned oldNumOperands = Phi->getNumIncomingValues();
  748. // Add the incoming values from the remainder code to the end of the phi
  749. // node.
  750. for (unsigned i =0; i < oldNumOperands; i++){
  751. Value *newVal = VMap.lookup(Phi->getIncomingValue(i));
  752. // newVal can be a constant or derived from values outside the loop, and
  753. // hence need not have a VMap value. Also, since lookup already generated
  754. // a default "null" VMap entry for this value, we need to populate that
  755. // VMap entry correctly, with the mapped entry being itself.
  756. if (!newVal) {
  757. newVal = Phi->getIncomingValue(i);
  758. VMap[Phi->getIncomingValue(i)] = Phi->getIncomingValue(i);
  759. }
  760. Phi->addIncoming(newVal,
  761. cast<BasicBlock>(VMap[Phi->getIncomingBlock(i)]));
  762. }
  763. }
  764. #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
  765. for (BasicBlock *SuccBB : successors(BB)) {
  766. assert(!(any_of(OtherExits,
  767. [SuccBB](BasicBlock *EB) { return EB == SuccBB; }) ||
  768. SuccBB == LatchExit) &&
  769. "Breaks the definition of dedicated exits!");
  770. }
  771. #endif
  772. }
  773. // Update the immediate dominator of the exit blocks and blocks that are
  774. // reachable from the exit blocks. This is needed because we now have paths
  775. // from both the original loop and the remainder code reaching the exit
  776. // blocks. While the IDom of these exit blocks were from the original loop,
  777. // now the IDom is the preheader (which decides whether the original loop or
  778. // remainder code should run).
  779. if (DT && !L->getExitingBlock()) {
  780. SmallVector<BasicBlock *, 16> ChildrenToUpdate;
  781. // NB! We have to examine the dom children of all loop blocks, not just
  782. // those which are the IDom of the exit blocks. This is because blocks
  783. // reachable from the exit blocks can have their IDom as the nearest common
  784. // dominator of the exit blocks.
  785. for (auto *BB : L->blocks()) {
  786. auto *DomNodeBB = DT->getNode(BB);
  787. for (auto *DomChild : DomNodeBB->getChildren()) {
  788. auto *DomChildBB = DomChild->getBlock();
  789. if (!L->contains(LI->getLoopFor(DomChildBB)))
  790. ChildrenToUpdate.push_back(DomChildBB);
  791. }
  792. }
  793. for (auto *BB : ChildrenToUpdate)
  794. DT->changeImmediateDominator(BB, PreHeader);
  795. }
  796. // Loop structure should be the following:
  797. // Epilog Prolog
  798. //
  799. // PreHeader PreHeader
  800. // NewPreHeader PrologPreHeader
  801. // Header PrologHeader
  802. // ... ...
  803. // Latch PrologLatch
  804. // NewExit PrologExit
  805. // EpilogPreHeader NewPreHeader
  806. // EpilogHeader Header
  807. // ... ...
  808. // EpilogLatch Latch
  809. // LatchExit LatchExit
  810. // Rewrite the cloned instruction operands to use the values created when the
  811. // clone is created.
  812. for (BasicBlock *BB : NewBlocks) {
  813. for (Instruction &I : *BB) {
  814. RemapInstruction(&I, VMap,
  815. RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
  816. }
  817. }
  818. if (UseEpilogRemainder) {
  819. // Connect the epilog code to the original loop and update the
  820. // PHI functions.
  821. ConnectEpilog(L, ModVal, NewExit, LatchExit, PreHeader,
  822. EpilogPreHeader, NewPreHeader, VMap, DT, LI,
  823. PreserveLCSSA);
  824. // Update counter in loop for unrolling.
  825. // I should be multiply of Count.
  826. IRBuilder<> B2(NewPreHeader->getTerminator());
  827. Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter");
  828. BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
  829. B2.SetInsertPoint(LatchBR);
  830. PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter",
  831. Header->getFirstNonPHI());
  832. Value *IdxSub =
  833. B2.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
  834. NewIdx->getName() + ".nsub");
  835. Value *IdxCmp;
  836. if (LatchBR->getSuccessor(0) == Header)
  837. IdxCmp = B2.CreateIsNotNull(IdxSub, NewIdx->getName() + ".ncmp");
  838. else
  839. IdxCmp = B2.CreateIsNull(IdxSub, NewIdx->getName() + ".ncmp");
  840. NewIdx->addIncoming(TestVal, NewPreHeader);
  841. NewIdx->addIncoming(IdxSub, Latch);
  842. LatchBR->setCondition(IdxCmp);
  843. } else {
  844. // Connect the prolog code to the original loop and update the
  845. // PHI functions.
  846. ConnectProlog(L, BECount, Count, PrologExit, LatchExit, PreHeader,
  847. NewPreHeader, VMap, DT, LI, PreserveLCSSA);
  848. }
  849. // If this loop is nested, then the loop unroller changes the code in the any
  850. // of its parent loops, so the Scalar Evolution pass needs to be run again.
  851. SE->forgetTopmostLoop(L);
  852. // Verify that the Dom Tree is correct.
  853. #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
  854. if (DT)
  855. assert(DT->verify(DominatorTree::VerificationLevel::Full));
  856. #endif
  857. // Canonicalize to LoopSimplifyForm both original and remainder loops. We
  858. // cannot rely on the LoopUnrollPass to do this because it only does
  859. // canonicalization for parent/subloops and not the sibling loops.
  860. if (OtherExits.size() > 0) {
  861. // Generate dedicated exit blocks for the original loop, to preserve
  862. // LoopSimplifyForm.
  863. formDedicatedExitBlocks(L, DT, LI, nullptr, PreserveLCSSA);
  864. // Generate dedicated exit blocks for the remainder loop if one exists, to
  865. // preserve LoopSimplifyForm.
  866. if (remainderLoop)
  867. formDedicatedExitBlocks(remainderLoop, DT, LI, nullptr, PreserveLCSSA);
  868. }
  869. auto UnrollResult = LoopUnrollResult::Unmodified;
  870. if (remainderLoop && UnrollRemainder) {
  871. LLVM_DEBUG(dbgs() << "Unrolling remainder loop\n");
  872. UnrollResult =
  873. UnrollLoop(remainderLoop,
  874. {/*Count*/ Count - 1, /*TripCount*/ Count - 1,
  875. /*Force*/ false, /*AllowRuntime*/ false,
  876. /*AllowExpensiveTripCount*/ false, /*PreserveCondBr*/ true,
  877. /*PreserveOnlyFirst*/ false, /*TripMultiple*/ 1,
  878. /*PeelCount*/ 0, /*UnrollRemainder*/ false, ForgetAllSCEV},
  879. LI, SE, DT, AC, /*ORE*/ nullptr, PreserveLCSSA);
  880. }
  881. if (ResultLoop && UnrollResult != LoopUnrollResult::FullyUnrolled)
  882. *ResultLoop = remainderLoop;
  883. NumRuntimeUnrolled++;
  884. return true;
  885. }