xref: /llvm-project/llvm/lib/Transforms/Utils/LoopUnrollRuntime.cpp (revision 17b9cb181775e47fb986dae45e2e2a38b84e33cf)
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/SmallPtrSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/LoopIterator.h"
26 #include "llvm/Analysis/ScalarEvolution.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/MDBuilder.h"
30 #include "llvm/IR/Metadata.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.h"
36 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
37 #include "llvm/Transforms/Utils/Cloning.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.
303 /// If CreateRemainderLoop is false, loop structure will not be cloned,
304 /// otherwise a new loop will be created including all cloned blocks, and the
305 /// iterator of it switches to count NewIter down to 0.
306 /// The cloned blocks should be inserted between InsertTop and InsertBot.
307 /// If loop structure is cloned InsertTop should be new preheader, InsertBot
308 /// new loop exit.
309 /// Return the new cloned loop that is created when CreateRemainderLoop is true.
310 static Loop *
311 CloneLoopBlocks(Loop *L, Value *NewIter, const bool CreateRemainderLoop,
312                 const bool UseEpilogRemainder, const bool UnrollRemainder,
313                 BasicBlock *InsertTop,
314                 BasicBlock *InsertBot, BasicBlock *Preheader,
315                 std::vector<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks,
316                 ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI) {
317   StringRef suffix = UseEpilogRemainder ? "epil" : "prol";
318   BasicBlock *Header = L->getHeader();
319   BasicBlock *Latch = L->getLoopLatch();
320   Function *F = Header->getParent();
321   LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
322   LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
323   Loop *ParentLoop = L->getParentLoop();
324   NewLoopsMap NewLoops;
325   NewLoops[ParentLoop] = ParentLoop;
326   if (!CreateRemainderLoop)
327     NewLoops[L] = ParentLoop;
328 
329   // For each block in the original loop, create a new copy,
330   // and update the value map with the newly created values.
331   for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
332     BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F);
333     NewBlocks.push_back(NewBB);
334 
335     // If we're unrolling the outermost loop, there's no remainder loop,
336     // and this block isn't in a nested loop, then the new block is not
337     // in any loop. Otherwise, add it to loopinfo.
338     if (CreateRemainderLoop || LI->getLoopFor(*BB) != L || ParentLoop)
339       addClonedBlockToLoopInfo(*BB, NewBB, LI, NewLoops);
340 
341     VMap[*BB] = NewBB;
342     if (Header == *BB) {
343       // For the first block, add a CFG connection to this newly
344       // created block.
345       InsertTop->getTerminator()->setSuccessor(0, NewBB);
346     }
347 
348     if (DT) {
349       if (Header == *BB) {
350         // The header is dominated by the preheader.
351         DT->addNewBlock(NewBB, InsertTop);
352       } else {
353         // Copy information from original loop to unrolled loop.
354         BasicBlock *IDomBB = DT->getNode(*BB)->getIDom()->getBlock();
355         DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB]));
356       }
357     }
358 
359     if (Latch == *BB) {
360       // For the last block, if CreateRemainderLoop is false, create a direct
361       // jump to InsertBot. If not, create a loop back to cloned head.
362       VMap.erase((*BB)->getTerminator());
363       BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
364       BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
365       IRBuilder<> Builder(LatchBR);
366       if (!CreateRemainderLoop) {
367         Builder.CreateBr(InsertBot);
368       } else {
369         PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2,
370                                           suffix + ".iter",
371                                           FirstLoopBB->getFirstNonPHI());
372         Value *IdxSub =
373             Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
374                               NewIdx->getName() + ".sub");
375         Value *IdxCmp =
376             Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
377         Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot);
378         NewIdx->addIncoming(NewIter, InsertTop);
379         NewIdx->addIncoming(IdxSub, NewBB);
380       }
381       LatchBR->eraseFromParent();
382     }
383   }
384 
385   // Change the incoming values to the ones defined in the preheader or
386   // cloned loop.
387   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
388     PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
389     if (!CreateRemainderLoop) {
390       if (UseEpilogRemainder) {
391         unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
392         NewPHI->setIncomingBlock(idx, InsertTop);
393         NewPHI->removeIncomingValue(Latch, false);
394       } else {
395         VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader);
396         cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
397       }
398     } else {
399       unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
400       NewPHI->setIncomingBlock(idx, InsertTop);
401       BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
402       idx = NewPHI->getBasicBlockIndex(Latch);
403       Value *InVal = NewPHI->getIncomingValue(idx);
404       NewPHI->setIncomingBlock(idx, NewLatch);
405       if (Value *V = VMap.lookup(InVal))
406         NewPHI->setIncomingValue(idx, V);
407     }
408   }
409   if (CreateRemainderLoop) {
410     Loop *NewLoop = NewLoops[L];
411     assert(NewLoop && "L should have been cloned");
412     MDNode *LoopID = NewLoop->getLoopID();
413 
414     // Only add loop metadata if the loop is not going to be completely
415     // unrolled.
416     if (UnrollRemainder)
417       return NewLoop;
418 
419     Optional<MDNode *> NewLoopID = makeFollowupLoopID(
420         LoopID, {LLVMLoopUnrollFollowupAll, LLVMLoopUnrollFollowupRemainder});
421     if (NewLoopID.hasValue()) {
422       NewLoop->setLoopID(NewLoopID.getValue());
423 
424       // Do not setLoopAlreadyUnrolled if loop attributes have been defined
425       // explicitly.
426       return NewLoop;
427     }
428 
429     // Add unroll disable metadata to disable future unrolling for this loop.
430     NewLoop->setLoopAlreadyUnrolled();
431     return NewLoop;
432   }
433   else
434     return nullptr;
435 }
436 
437 /// Returns true if we can safely unroll a multi-exit/exiting loop. OtherExits
438 /// is populated with all the loop exit blocks other than the LatchExit block.
439 static bool canSafelyUnrollMultiExitLoop(Loop *L, BasicBlock *LatchExit,
440                                          bool PreserveLCSSA,
441                                          bool UseEpilogRemainder) {
442 
443   // We currently have some correctness constrains in unrolling a multi-exit
444   // loop. Check for these below.
445 
446   // We rely on LCSSA form being preserved when the exit blocks are transformed.
447   // (Note that only an off-by-default mode of the old PM disables PreserveLCCA.)
448   if (!PreserveLCSSA)
449     return false;
450 
451   // FIXME: We bail out of multi-exit unrolling when epilog loop is generated
452   // and L is an inner loop. This is because in presence of multiple exits, the
453   // outer loop is incorrect: we do not add the EpilogPreheader and exit to the
454   // outer loop. This is automatically handled in the prolog case, so we do not
455   // have that bug in prolog generation.
456   if (UseEpilogRemainder && L->getParentLoop())
457     return false;
458 
459   // All constraints have been satisfied.
460   return true;
461 }
462 
463 /// Returns true if we can profitably unroll the multi-exit loop L. Currently,
464 /// we return true only if UnrollRuntimeMultiExit is set to true.
465 static bool canProfitablyUnrollMultiExitLoop(
466     Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits, BasicBlock *LatchExit,
467     bool PreserveLCSSA, bool UseEpilogRemainder) {
468 
469 #if !defined(NDEBUG)
470   assert(canSafelyUnrollMultiExitLoop(L, LatchExit, PreserveLCSSA,
471                                       UseEpilogRemainder) &&
472          "Should be safe to unroll before checking profitability!");
473 #endif
474 
475   // Priority goes to UnrollRuntimeMultiExit if it's supplied.
476   if (UnrollRuntimeMultiExit.getNumOccurrences())
477     return UnrollRuntimeMultiExit;
478 
479   // TODO: We used to bail out for correctness (now fixed).  Under what
480   // circumstances is this case profitable to allow?
481   if (!LatchExit->getSinglePredecessor())
482     return false;
483 
484   // The main pain point with multi-exit loop unrolling is that once unrolled,
485   // we will not be able to merge all blocks into a straight line code.
486   // There are branches within the unrolled loop that go to the OtherExits.
487   // The second point is the increase in code size, but this is true
488   // irrespective of multiple exits.
489 
490   // Note: Both the heuristics below are coarse grained. We are essentially
491   // enabling unrolling of loops that have a single side exit other than the
492   // normal LatchExit (i.e. exiting into a deoptimize block).
493   // The heuristics considered are:
494   // 1. low number of branches in the unrolled version.
495   // 2. high predictability of these extra branches.
496   // We avoid unrolling loops that have more than two exiting blocks. This
497   // limits the total number of branches in the unrolled loop to be atmost
498   // the unroll factor (since one of the exiting blocks is the latch block).
499   SmallVector<BasicBlock*, 4> ExitingBlocks;
500   L->getExitingBlocks(ExitingBlocks);
501   if (ExitingBlocks.size() > 2)
502     return false;
503 
504   // Allow unrolling of loops with no non latch exit blocks.
505   if (OtherExits.size() == 0)
506     return true;
507 
508   // The second heuristic is that L has one exit other than the latchexit and
509   // that exit is a deoptimize block. We know that deoptimize blocks are rarely
510   // taken, which also implies the branch leading to the deoptimize block is
511   // highly predictable. When UnrollRuntimeOtherExitPredictable is specified, we
512   // assume the other exit branch is predictable even if it has no deoptimize
513   // call.
514   return (OtherExits.size() == 1 &&
515           (UnrollRuntimeOtherExitPredictable ||
516            OtherExits[0]->getTerminatingDeoptimizeCall()));
517   // TODO: These can be fine-tuned further to consider code size or deopt states
518   // that are captured by the deoptimize exit block.
519   // Also, we can extend this to support more cases, if we actually
520   // know of kinds of multiexit loops that would benefit from unrolling.
521 }
522 
523 // Assign the maximum possible trip count as the back edge weight for the
524 // remainder loop if the original loop comes with a branch weight.
525 static void updateLatchBranchWeightsForRemainderLoop(Loop *OrigLoop,
526                                                      Loop *RemainderLoop,
527                                                      uint64_t UnrollFactor) {
528   uint64_t TrueWeight, FalseWeight;
529   BranchInst *LatchBR =
530       cast<BranchInst>(OrigLoop->getLoopLatch()->getTerminator());
531   if (LatchBR->extractProfMetadata(TrueWeight, FalseWeight)) {
532     uint64_t ExitWeight = LatchBR->getSuccessor(0) == OrigLoop->getHeader()
533                               ? FalseWeight
534                               : TrueWeight;
535     assert(UnrollFactor > 1);
536     uint64_t BackEdgeWeight = (UnrollFactor - 1) * ExitWeight;
537     BasicBlock *Header = RemainderLoop->getHeader();
538     BasicBlock *Latch = RemainderLoop->getLoopLatch();
539     auto *RemainderLatchBR = cast<BranchInst>(Latch->getTerminator());
540     unsigned HeaderIdx = (RemainderLatchBR->getSuccessor(0) == Header ? 0 : 1);
541     MDBuilder MDB(RemainderLatchBR->getContext());
542     MDNode *WeightNode =
543         HeaderIdx ? MDB.createBranchWeights(ExitWeight, BackEdgeWeight)
544                   : MDB.createBranchWeights(BackEdgeWeight, ExitWeight);
545     RemainderLatchBR->setMetadata(LLVMContext::MD_prof, WeightNode);
546   }
547 }
548 
549 /// Calculate ModVal = (BECount + 1) % Count on the abstract integer domain
550 /// accounting for the possibility of unsigned overflow in the 2s complement
551 /// domain. Preconditions:
552 /// 1) TripCount = BECount + 1 (allowing overflow)
553 /// 2) Log2(Count) <= BitWidth(BECount)
554 static Value *CreateTripRemainder(IRBuilder<> &B, Value *BECount,
555                                   Value *TripCount, unsigned Count) {
556   // Note that TripCount is BECount + 1.
557   if (isPowerOf2_32(Count))
558     // If the expression is zero, then either:
559     //  1. There are no iterations to be run in the prolog/epilog loop.
560     // OR
561     //  2. The addition computing TripCount overflowed.
562     //
563     // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
564     // the number of iterations that remain to be run in the original loop is a
565     // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (a
566     // precondition of this method).
567     return B.CreateAnd(TripCount, Count - 1, "xtraiter");
568 
569   // As (BECount + 1) can potentially unsigned overflow we count
570   // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
571   Constant *CountC = ConstantInt::get(BECount->getType(), Count);
572   Value *ModValTmp = B.CreateURem(BECount, CountC);
573   Value *ModValAdd = B.CreateAdd(ModValTmp,
574                                  ConstantInt::get(ModValTmp->getType(), 1));
575   // At that point (BECount % Count) + 1 could be equal to Count.
576   // To handle this case we need to take mod by Count one more time.
577   return B.CreateURem(ModValAdd, CountC, "xtraiter");
578 }
579 
580 
581 /// Insert code in the prolog/epilog code when unrolling a loop with a
582 /// run-time trip-count.
583 ///
584 /// This method assumes that the loop unroll factor is total number
585 /// of loop bodies in the loop after unrolling. (Some folks refer
586 /// to the unroll factor as the number of *extra* copies added).
587 /// We assume also that the loop unroll factor is a power-of-two. So, after
588 /// unrolling the loop, the number of loop bodies executed is 2,
589 /// 4, 8, etc.  Note - LLVM converts the if-then-sequence to a switch
590 /// instruction in SimplifyCFG.cpp.  Then, the backend decides how code for
591 /// the switch instruction is generated.
592 ///
593 /// ***Prolog case***
594 ///        extraiters = tripcount % loopfactor
595 ///        if (extraiters == 0) jump Loop:
596 ///        else jump Prol:
597 /// Prol:  LoopBody;
598 ///        extraiters -= 1                 // Omitted if unroll factor is 2.
599 ///        if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
600 ///        if (tripcount < loopfactor) jump End:
601 /// Loop:
602 /// ...
603 /// End:
604 ///
605 /// ***Epilog case***
606 ///        extraiters = tripcount % loopfactor
607 ///        if (tripcount < loopfactor) jump LoopExit:
608 ///        unroll_iters = tripcount - extraiters
609 /// Loop:  LoopBody; (executes unroll_iter times);
610 ///        unroll_iter -= 1
611 ///        if (unroll_iter != 0) jump Loop:
612 /// LoopExit:
613 ///        if (extraiters == 0) jump EpilExit:
614 /// Epil:  LoopBody; (executes extraiters times)
615 ///        extraiters -= 1                 // Omitted if unroll factor is 2.
616 ///        if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
617 /// EpilExit:
618 
619 bool llvm::UnrollRuntimeLoopRemainder(
620     Loop *L, unsigned Count, bool AllowExpensiveTripCount,
621     bool UseEpilogRemainder, bool UnrollRemainder, bool ForgetAllSCEV,
622     LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC,
623     const TargetTransformInfo *TTI, bool PreserveLCSSA, Loop **ResultLoop) {
624   LLVM_DEBUG(dbgs() << "Trying runtime unrolling on Loop: \n");
625   LLVM_DEBUG(L->dump());
626   LLVM_DEBUG(UseEpilogRemainder ? dbgs() << "Using epilog remainder.\n"
627                                 : dbgs() << "Using prolog remainder.\n");
628 
629   // Make sure the loop is in canonical form.
630   if (!L->isLoopSimplifyForm()) {
631     LLVM_DEBUG(dbgs() << "Not in simplify form!\n");
632     return false;
633   }
634 
635   // Guaranteed by LoopSimplifyForm.
636   BasicBlock *Latch = L->getLoopLatch();
637   BasicBlock *Header = L->getHeader();
638 
639   BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
640 
641   if (!LatchBR || LatchBR->isUnconditional()) {
642     // The loop-rotate pass can be helpful to avoid this in many cases.
643     LLVM_DEBUG(
644         dbgs()
645         << "Loop latch not terminated by a conditional branch.\n");
646     return false;
647   }
648 
649   unsigned ExitIndex = LatchBR->getSuccessor(0) == Header ? 1 : 0;
650   BasicBlock *LatchExit = LatchBR->getSuccessor(ExitIndex);
651 
652   if (L->contains(LatchExit)) {
653     // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the
654     // targets of the Latch be an exit block out of the loop.
655     LLVM_DEBUG(
656         dbgs()
657         << "One of the loop latch successors must be the exit block.\n");
658     return false;
659   }
660 
661   // These are exit blocks other than the target of the latch exiting block.
662   SmallVector<BasicBlock *, 4> OtherExits;
663   L->getUniqueNonLatchExitBlocks(OtherExits);
664   bool isMultiExitUnrollingEnabled =
665       canSafelyUnrollMultiExitLoop(L, LatchExit, PreserveLCSSA,
666                                    UseEpilogRemainder) &&
667       canProfitablyUnrollMultiExitLoop(L, OtherExits, LatchExit, PreserveLCSSA,
668                                        UseEpilogRemainder);
669   // Support only single exit and exiting block unless multi-exit loop unrolling is enabled.
670   if (!isMultiExitUnrollingEnabled &&
671       (!L->getExitingBlock() || OtherExits.size())) {
672     LLVM_DEBUG(
673         dbgs()
674         << "Multiple exit/exiting blocks in loop and multi-exit unrolling not "
675            "enabled!\n");
676     return false;
677   }
678   // Use Scalar Evolution to compute the trip count. This allows more loops to
679   // be unrolled than relying on induction var simplification.
680   if (!SE)
681     return false;
682 
683   // Only unroll loops with a computable trip count, and the trip count needs
684   // to be an int value (allowing a pointer type is a TODO item).
685   // We calculate the backedge count by using getExitCount on the Latch block,
686   // which is proven to be the only exiting block in this loop. This is same as
687   // calculating getBackedgeTakenCount on the loop (which computes SCEV for all
688   // exiting blocks).
689   const SCEV *BECountSC = SE->getExitCount(L, Latch);
690   if (isa<SCEVCouldNotCompute>(BECountSC) ||
691       !BECountSC->getType()->isIntegerTy()) {
692     LLVM_DEBUG(dbgs() << "Could not compute exit block SCEV\n");
693     return false;
694   }
695 
696   unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
697 
698   // Add 1 since the backedge count doesn't include the first loop iteration.
699   // (Note that overflow can occur, this is handled explicitly below)
700   const SCEV *TripCountSC =
701       SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
702   if (isa<SCEVCouldNotCompute>(TripCountSC)) {
703     LLVM_DEBUG(dbgs() << "Could not compute trip count SCEV.\n");
704     return false;
705   }
706 
707   BasicBlock *PreHeader = L->getLoopPreheader();
708   BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
709   const DataLayout &DL = Header->getModule()->getDataLayout();
710   SCEVExpander Expander(*SE, DL, "loop-unroll");
711   if (!AllowExpensiveTripCount &&
712       Expander.isHighCostExpansion(TripCountSC, L, SCEVCheapExpansionBudget,
713                                    TTI, PreHeaderBR)) {
714     LLVM_DEBUG(dbgs() << "High cost for expanding trip count scev!\n");
715     return false;
716   }
717 
718   // This constraint lets us deal with an overflowing trip count easily; see the
719   // comment on ModVal below.
720   if (Log2_32(Count) > BEWidth) {
721     LLVM_DEBUG(
722         dbgs()
723         << "Count failed constraint on overflow trip count calculation.\n");
724     return false;
725   }
726 
727   // Loop structure is the following:
728   //
729   // PreHeader
730   //   Header
731   //   ...
732   //   Latch
733   // LatchExit
734 
735   BasicBlock *NewPreHeader;
736   BasicBlock *NewExit = nullptr;
737   BasicBlock *PrologExit = nullptr;
738   BasicBlock *EpilogPreHeader = nullptr;
739   BasicBlock *PrologPreHeader = nullptr;
740 
741   if (UseEpilogRemainder) {
742     // If epilog remainder
743     // Split PreHeader to insert a branch around loop for unrolling.
744     NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI);
745     NewPreHeader->setName(PreHeader->getName() + ".new");
746     // Split LatchExit to create phi nodes from branch above.
747     NewExit = SplitBlockPredecessors(LatchExit, {Latch}, ".unr-lcssa", DT, LI,
748                                      nullptr, PreserveLCSSA);
749     // NewExit gets its DebugLoc from LatchExit, which is not part of the
750     // original Loop.
751     // Fix this by setting Loop's DebugLoc to NewExit.
752     auto *NewExitTerminator = NewExit->getTerminator();
753     NewExitTerminator->setDebugLoc(Header->getTerminator()->getDebugLoc());
754     // Split NewExit to insert epilog remainder loop.
755     EpilogPreHeader = SplitBlock(NewExit, NewExitTerminator, DT, LI);
756     EpilogPreHeader->setName(Header->getName() + ".epil.preheader");
757   } else {
758     // If prolog remainder
759     // Split the original preheader twice to insert prolog remainder loop
760     PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI);
761     PrologPreHeader->setName(Header->getName() + ".prol.preheader");
762     PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(),
763                             DT, LI);
764     PrologExit->setName(Header->getName() + ".prol.loopexit");
765     // Split PrologExit to get NewPreHeader.
766     NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI);
767     NewPreHeader->setName(PreHeader->getName() + ".new");
768   }
769   // Loop structure should be the following:
770   //  Epilog             Prolog
771   //
772   // PreHeader         PreHeader
773   // *NewPreHeader     *PrologPreHeader
774   //   Header          *PrologExit
775   //   ...             *NewPreHeader
776   //   Latch             Header
777   // *NewExit            ...
778   // *EpilogPreHeader    Latch
779   // LatchExit              LatchExit
780 
781   // Calculate conditions for branch around loop for unrolling
782   // in epilog case and around prolog remainder loop in prolog case.
783   // Compute the number of extra iterations required, which is:
784   //  extra iterations = run-time trip count % loop unroll factor
785   PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
786   Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
787                                             PreHeaderBR);
788   Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(),
789                                           PreHeaderBR);
790   IRBuilder<> B(PreHeaderBR);
791   Value * const ModVal = CreateTripRemainder(B, BECount, TripCount, Count);
792 
793   Value *BranchVal =
794       UseEpilogRemainder ? B.CreateICmpULT(BECount,
795                                            ConstantInt::get(BECount->getType(),
796                                                             Count - 1)) :
797                            B.CreateIsNotNull(ModVal, "lcmp.mod");
798   BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader;
799   BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit;
800   // Branch to either remainder (extra iterations) loop or unrolling loop.
801   B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop);
802   PreHeaderBR->eraseFromParent();
803   if (DT) {
804     if (UseEpilogRemainder)
805       DT->changeImmediateDominator(NewExit, PreHeader);
806     else
807       DT->changeImmediateDominator(PrologExit, PreHeader);
808   }
809   Function *F = Header->getParent();
810   // Get an ordered list of blocks in the loop to help with the ordering of the
811   // cloned blocks in the prolog/epilog code
812   LoopBlocksDFS LoopBlocks(L);
813   LoopBlocks.perform(LI);
814 
815   //
816   // For each extra loop iteration, create a copy of the loop's basic blocks
817   // and generate a condition that branches to the copy depending on the
818   // number of 'left over' iterations.
819   //
820   std::vector<BasicBlock *> NewBlocks;
821   ValueToValueMapTy VMap;
822 
823   // For unroll factor 2 remainder loop will have 1 iterations.
824   // Do not create 1 iteration loop.
825   bool CreateRemainderLoop = (Count != 2);
826 
827   // Clone all the basic blocks in the loop. If Count is 2, we don't clone
828   // the loop, otherwise we create a cloned loop to execute the extra
829   // iterations. This function adds the appropriate CFG connections.
830   BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit;
831   BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
832   Loop *remainderLoop = CloneLoopBlocks(
833       L, ModVal, CreateRemainderLoop, UseEpilogRemainder, UnrollRemainder,
834       InsertTop, InsertBot,
835       NewPreHeader, NewBlocks, LoopBlocks, VMap, DT, LI);
836 
837   // Assign the maximum possible trip count as the back edge weight for the
838   // remainder loop if the original loop comes with a branch weight.
839   if (remainderLoop && !UnrollRemainder)
840     updateLatchBranchWeightsForRemainderLoop(L, remainderLoop, Count);
841 
842   // Insert the cloned blocks into the function.
843   F->getBasicBlockList().splice(InsertBot->getIterator(),
844                                 F->getBasicBlockList(),
845                                 NewBlocks[0]->getIterator(),
846                                 F->end());
847 
848   // Now the loop blocks are cloned and the other exiting blocks from the
849   // remainder are connected to the original Loop's exit blocks. The remaining
850   // work is to update the phi nodes in the original loop, and take in the
851   // values from the cloned region.
852   for (auto *BB : OtherExits) {
853     // Given we preserve LCSSA form, we know that the values used outside the
854     // loop will be used through these phi nodes at the exit blocks that are
855     // transformed below.
856     for (PHINode &PN : BB->phis()) {
857      unsigned oldNumOperands = PN.getNumIncomingValues();
858      // Add the incoming values from the remainder code to the end of the phi
859      // node.
860      for (unsigned i = 0; i < oldNumOperands; i++){
861        auto *PredBB =PN.getIncomingBlock(i);
862        if (PredBB == Latch)
863          // The latch exit is handled seperately, see connectX
864          continue;
865        if (!L->contains(PredBB))
866          // Even if we had dedicated exits, the code above inserted an
867          // extra branch which can reach the latch exit.
868          continue;
869 
870        auto *V = PN.getIncomingValue(i);
871        if (Instruction *I = dyn_cast<Instruction>(V))
872          if (L->contains(I))
873            V = VMap.lookup(I);
874        PN.addIncoming(V, cast<BasicBlock>(VMap[PredBB]));
875      }
876    }
877 #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
878     for (BasicBlock *SuccBB : successors(BB)) {
879       assert(!(any_of(OtherExits,
880                       [SuccBB](BasicBlock *EB) { return EB == SuccBB; }) ||
881                SuccBB == LatchExit) &&
882              "Breaks the definition of dedicated exits!");
883     }
884 #endif
885   }
886 
887   // Update the immediate dominator of the exit blocks and blocks that are
888   // reachable from the exit blocks. This is needed because we now have paths
889   // from both the original loop and the remainder code reaching the exit
890   // blocks. While the IDom of these exit blocks were from the original loop,
891   // now the IDom is the preheader (which decides whether the original loop or
892   // remainder code should run).
893   if (DT && !L->getExitingBlock()) {
894     SmallVector<BasicBlock *, 16> ChildrenToUpdate;
895     // NB! We have to examine the dom children of all loop blocks, not just
896     // those which are the IDom of the exit blocks. This is because blocks
897     // reachable from the exit blocks can have their IDom as the nearest common
898     // dominator of the exit blocks.
899     for (auto *BB : L->blocks()) {
900       auto *DomNodeBB = DT->getNode(BB);
901       for (auto *DomChild : DomNodeBB->children()) {
902         auto *DomChildBB = DomChild->getBlock();
903         if (!L->contains(LI->getLoopFor(DomChildBB)))
904           ChildrenToUpdate.push_back(DomChildBB);
905       }
906     }
907     for (auto *BB : ChildrenToUpdate)
908       DT->changeImmediateDominator(BB, PreHeader);
909   }
910 
911   // Loop structure should be the following:
912   //  Epilog             Prolog
913   //
914   // PreHeader         PreHeader
915   // NewPreHeader      PrologPreHeader
916   //   Header            PrologHeader
917   //   ...               ...
918   //   Latch             PrologLatch
919   // NewExit           PrologExit
920   // EpilogPreHeader   NewPreHeader
921   //   EpilogHeader      Header
922   //   ...               ...
923   //   EpilogLatch       Latch
924   // LatchExit              LatchExit
925 
926   // Rewrite the cloned instruction operands to use the values created when the
927   // clone is created.
928   for (BasicBlock *BB : NewBlocks) {
929     for (Instruction &I : *BB) {
930       RemapInstruction(&I, VMap,
931                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
932     }
933   }
934 
935   if (UseEpilogRemainder) {
936     // Connect the epilog code to the original loop and update the
937     // PHI functions.
938     ConnectEpilog(L, ModVal, NewExit, LatchExit, PreHeader,
939                   EpilogPreHeader, NewPreHeader, VMap, DT, LI,
940                   PreserveLCSSA);
941 
942     // Update counter in loop for unrolling.
943     // I should be multiply of Count.
944     IRBuilder<> B2(NewPreHeader->getTerminator());
945     Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter");
946     BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
947     B2.SetInsertPoint(LatchBR);
948     PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter",
949                                       Header->getFirstNonPHI());
950     Value *IdxSub =
951         B2.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
952                      NewIdx->getName() + ".nsub");
953     Value *IdxCmp;
954     if (LatchBR->getSuccessor(0) == Header)
955       IdxCmp = B2.CreateIsNotNull(IdxSub, NewIdx->getName() + ".ncmp");
956     else
957       IdxCmp = B2.CreateIsNull(IdxSub, NewIdx->getName() + ".ncmp");
958     NewIdx->addIncoming(TestVal, NewPreHeader);
959     NewIdx->addIncoming(IdxSub, Latch);
960     LatchBR->setCondition(IdxCmp);
961   } else {
962     // Connect the prolog code to the original loop and update the
963     // PHI functions.
964     ConnectProlog(L, BECount, Count, PrologExit, LatchExit, PreHeader,
965                   NewPreHeader, VMap, DT, LI, PreserveLCSSA);
966   }
967 
968   // If this loop is nested, then the loop unroller changes the code in the any
969   // of its parent loops, so the Scalar Evolution pass needs to be run again.
970   SE->forgetTopmostLoop(L);
971 
972   // Verify that the Dom Tree is correct.
973 #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
974   if (DT)
975     assert(DT->verify(DominatorTree::VerificationLevel::Full));
976 #endif
977 
978   // Canonicalize to LoopSimplifyForm both original and remainder loops. We
979   // cannot rely on the LoopUnrollPass to do this because it only does
980   // canonicalization for parent/subloops and not the sibling loops.
981   if (OtherExits.size() > 0) {
982     // Generate dedicated exit blocks for the original loop, to preserve
983     // LoopSimplifyForm.
984     formDedicatedExitBlocks(L, DT, LI, nullptr, PreserveLCSSA);
985     // Generate dedicated exit blocks for the remainder loop if one exists, to
986     // preserve LoopSimplifyForm.
987     if (remainderLoop)
988       formDedicatedExitBlocks(remainderLoop, DT, LI, nullptr, PreserveLCSSA);
989   }
990 
991   auto UnrollResult = LoopUnrollResult::Unmodified;
992   if (remainderLoop && UnrollRemainder) {
993     LLVM_DEBUG(dbgs() << "Unrolling remainder loop\n");
994     UnrollResult =
995         UnrollLoop(remainderLoop,
996                    {/*Count*/ Count - 1, /*Force*/ false, /*Runtime*/ false,
997                     /*AllowExpensiveTripCount*/ false,
998                     /*UnrollRemainder*/ false, ForgetAllSCEV},
999                    LI, SE, DT, AC, TTI, /*ORE*/ nullptr, PreserveLCSSA);
1000   }
1001 
1002   if (ResultLoop && UnrollResult != LoopUnrollResult::FullyUnrolled)
1003     *ResultLoop = remainderLoop;
1004   NumRuntimeUnrolled++;
1005   return true;
1006 }
1007