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