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