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