1 //===-- UnrollLoop.cpp - 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. It does not define any
10 // actual pass or policy, but provides a single function to perform loop
11 // unrolling.
12 //
13 // The process of unrolling can produce extraneous basic blocks linked with
14 // unconditional branches.  This will be corrected in the future.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/ADT/ilist_iterator.h"
28 #include "llvm/ADT/iterator_range.h"
29 #include "llvm/Analysis/AssumptionCache.h"
30 #include "llvm/Analysis/DomTreeUpdater.h"
31 #include "llvm/Analysis/InstructionSimplify.h"
32 #include "llvm/Analysis/LoopInfo.h"
33 #include "llvm/Analysis/LoopIterator.h"
34 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
35 #include "llvm/Analysis/ScalarEvolution.h"
36 #include "llvm/IR/BasicBlock.h"
37 #include "llvm/IR/CFG.h"
38 #include "llvm/IR/CallSite.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DebugInfoMetadata.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/IR/DiagnosticInfo.h"
43 #include "llvm/IR/Dominators.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/Instruction.h"
46 #include "llvm/IR/Instructions.h"
47 #include "llvm/IR/IntrinsicInst.h"
48 #include "llvm/IR/Metadata.h"
49 #include "llvm/IR/Module.h"
50 #include "llvm/IR/Use.h"
51 #include "llvm/IR/User.h"
52 #include "llvm/IR/ValueHandle.h"
53 #include "llvm/IR/ValueMap.h"
54 #include "llvm/Support/Casting.h"
55 #include "llvm/Support/CommandLine.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/GenericDomTree.h"
58 #include "llvm/Support/MathExtras.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
61 #include "llvm/Transforms/Utils/Cloning.h"
62 #include "llvm/Transforms/Utils/Local.h"
63 #include "llvm/Transforms/Utils/LoopSimplify.h"
64 #include "llvm/Transforms/Utils/LoopUtils.h"
65 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
66 #include "llvm/Transforms/Utils/UnrollLoop.h"
67 #include "llvm/Transforms/Utils/ValueMapper.h"
68 #include <algorithm>
69 #include <assert.h>
70 #include <type_traits>
71 #include <vector>
72 
73 namespace llvm {
74 class DataLayout;
75 class Value;
76 } // namespace llvm
77 
78 using namespace llvm;
79 
80 #define DEBUG_TYPE "loop-unroll"
81 
82 // TODO: Should these be here or in LoopUnroll?
83 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
84 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
85 STATISTIC(NumUnrolledWithHeader, "Number of loops unrolled without a "
86                                  "conditional latch (completely or otherwise)");
87 
88 static cl::opt<bool>
89 UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden,
90                     cl::desc("Allow runtime unrolled loops to be unrolled "
91                              "with epilog instead of prolog."));
92 
93 static cl::opt<bool>
94 UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden,
95                     cl::desc("Verify domtree after unrolling"),
96 #ifdef EXPENSIVE_CHECKS
97     cl::init(true)
98 #else
99     cl::init(false)
100 #endif
101                     );
102 
103 /// Check if unrolling created a situation where we need to insert phi nodes to
104 /// preserve LCSSA form.
105 /// \param Blocks is a vector of basic blocks representing unrolled loop.
106 /// \param L is the outer loop.
107 /// It's possible that some of the blocks are in L, and some are not. In this
108 /// case, if there is a use is outside L, and definition is inside L, we need to
109 /// insert a phi-node, otherwise LCSSA will be broken.
110 /// The function is just a helper function for llvm::UnrollLoop that returns
111 /// true if this situation occurs, indicating that LCSSA needs to be fixed.
112 static bool needToInsertPhisForLCSSA(Loop *L, std::vector<BasicBlock *> Blocks,
113                                      LoopInfo *LI) {
114   for (BasicBlock *BB : Blocks) {
115     if (LI->getLoopFor(BB) == L)
116       continue;
117     for (Instruction &I : *BB) {
118       for (Use &U : I.operands()) {
119         if (auto Def = dyn_cast<Instruction>(U)) {
120           Loop *DefLoop = LI->getLoopFor(Def->getParent());
121           if (!DefLoop)
122             continue;
123           if (DefLoop->contains(L))
124             return true;
125         }
126       }
127     }
128   }
129   return false;
130 }
131 
132 /// Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary
133 /// and adds a mapping from the original loop to the new loop to NewLoops.
134 /// Returns nullptr if no new loop was created and a pointer to the
135 /// original loop OriginalBB was part of otherwise.
136 const Loop* llvm::addClonedBlockToLoopInfo(BasicBlock *OriginalBB,
137                                            BasicBlock *ClonedBB, LoopInfo *LI,
138                                            NewLoopsMap &NewLoops) {
139   // Figure out which loop New is in.
140   const Loop *OldLoop = LI->getLoopFor(OriginalBB);
141   assert(OldLoop && "Should (at least) be in the loop being unrolled!");
142 
143   Loop *&NewLoop = NewLoops[OldLoop];
144   if (!NewLoop) {
145     // Found a new sub-loop.
146     assert(OriginalBB == OldLoop->getHeader() &&
147            "Header should be first in RPO");
148 
149     NewLoop = LI->AllocateLoop();
150     Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
151 
152     if (NewLoopParent)
153       NewLoopParent->addChildLoop(NewLoop);
154     else
155       LI->addTopLevelLoop(NewLoop);
156 
157     NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
158     return OldLoop;
159   } else {
160     NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
161     return nullptr;
162   }
163 }
164 
165 /// The function chooses which type of unroll (epilog or prolog) is more
166 /// profitabale.
167 /// Epilog unroll is more profitable when there is PHI that starts from
168 /// constant.  In this case epilog will leave PHI start from constant,
169 /// but prolog will convert it to non-constant.
170 ///
171 /// loop:
172 ///   PN = PHI [I, Latch], [CI, PreHeader]
173 ///   I = foo(PN)
174 ///   ...
175 ///
176 /// Epilog unroll case.
177 /// loop:
178 ///   PN = PHI [I2, Latch], [CI, PreHeader]
179 ///   I1 = foo(PN)
180 ///   I2 = foo(I1)
181 ///   ...
182 /// Prolog unroll case.
183 ///   NewPN = PHI [PrologI, Prolog], [CI, PreHeader]
184 /// loop:
185 ///   PN = PHI [I2, Latch], [NewPN, PreHeader]
186 ///   I1 = foo(PN)
187 ///   I2 = foo(I1)
188 ///   ...
189 ///
190 static bool isEpilogProfitable(Loop *L) {
191   BasicBlock *PreHeader = L->getLoopPreheader();
192   BasicBlock *Header = L->getHeader();
193   assert(PreHeader && Header);
194   for (const PHINode &PN : Header->phis()) {
195     if (isa<ConstantInt>(PN.getIncomingValueForBlock(PreHeader)))
196       return true;
197   }
198   return false;
199 }
200 
201 /// Perform some cleanup and simplifications on loops after unrolling. It is
202 /// useful to simplify the IV's in the new loop, as well as do a quick
203 /// simplify/dce pass of the instructions.
204 void llvm::simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI,
205                                    ScalarEvolution *SE, DominatorTree *DT,
206                                    AssumptionCache *AC) {
207   // Simplify any new induction variables in the partially unrolled loop.
208   if (SE && SimplifyIVs) {
209     SmallVector<WeakTrackingVH, 16> DeadInsts;
210     simplifyLoopIVs(L, SE, DT, LI, DeadInsts);
211 
212     // Aggressively clean up dead instructions that simplifyLoopIVs already
213     // identified. Any remaining should be cleaned up below.
214     while (!DeadInsts.empty()) {
215       Value *V = DeadInsts.pop_back_val();
216       if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))
217         RecursivelyDeleteTriviallyDeadInstructions(Inst);
218     }
219   }
220 
221   // At this point, the code is well formed.  We now do a quick sweep over the
222   // inserted code, doing constant propagation and dead code elimination as we
223   // go.
224   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
225   for (BasicBlock *BB : L->getBlocks()) {
226     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
227       Instruction *Inst = &*I++;
228 
229       if (Value *V = SimplifyInstruction(Inst, {DL, nullptr, DT, AC}))
230         if (LI->replacementPreservesLCSSAForm(Inst, V))
231           Inst->replaceAllUsesWith(V);
232       if (isInstructionTriviallyDead(Inst))
233         BB->getInstList().erase(Inst);
234     }
235   }
236 
237   // TODO: after peeling or unrolling, previously loop variant conditions are
238   // likely to fold to constants, eagerly propagating those here will require
239   // fewer cleanup passes to be run.  Alternatively, a LoopEarlyCSE might be
240   // appropriate.
241 }
242 
243 /// Unroll the given loop by Count. The loop must be in LCSSA form.  Unrolling
244 /// can only fail when the loop's latch block is not terminated by a conditional
245 /// branch instruction. However, if the trip count (and multiple) are not known,
246 /// loop unrolling will mostly produce more code that is no faster.
247 ///
248 /// TripCount is the upper bound of the iteration on which control exits
249 /// LatchBlock. Control may exit the loop prior to TripCount iterations either
250 /// via an early branch in other loop block or via LatchBlock terminator. This
251 /// is relaxed from the general definition of trip count which is the number of
252 /// times the loop header executes. Note that UnrollLoop assumes that the loop
253 /// counter test is in LatchBlock in order to remove unnecesssary instances of
254 /// the test.  If control can exit the loop from the LatchBlock's terminator
255 /// prior to TripCount iterations, flag PreserveCondBr needs to be set.
256 ///
257 /// PreserveCondBr indicates whether the conditional branch of the LatchBlock
258 /// needs to be preserved.  It is needed when we use trip count upper bound to
259 /// fully unroll the loop. If PreserveOnlyFirst is also set then only the first
260 /// conditional branch needs to be preserved.
261 ///
262 /// Similarly, TripMultiple divides the number of times that the LatchBlock may
263 /// execute without exiting the loop.
264 ///
265 /// If AllowRuntime is true then UnrollLoop will consider unrolling loops that
266 /// have a runtime (i.e. not compile time constant) trip count.  Unrolling these
267 /// loops require a unroll "prologue" that runs "RuntimeTripCount % Count"
268 /// iterations before branching into the unrolled loop.  UnrollLoop will not
269 /// runtime-unroll the loop if computing RuntimeTripCount will be expensive and
270 /// AllowExpensiveTripCount is false.
271 ///
272 /// If we want to perform PGO-based loop peeling, PeelCount is set to the
273 /// number of iterations we want to peel off.
274 ///
275 /// The LoopInfo Analysis that is passed will be kept consistent.
276 ///
277 /// This utility preserves LoopInfo. It will also preserve ScalarEvolution and
278 /// DominatorTree if they are non-null.
279 ///
280 /// If RemainderLoop is non-null, it will receive the remainder loop (if
281 /// required and not fully unrolled).
282 LoopUnrollResult llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
283                                   ScalarEvolution *SE, DominatorTree *DT,
284                                   AssumptionCache *AC,
285                                   OptimizationRemarkEmitter *ORE,
286                                   bool PreserveLCSSA, Loop **RemainderLoop) {
287 
288   BasicBlock *Preheader = L->getLoopPreheader();
289   if (!Preheader) {
290     LLVM_DEBUG(dbgs() << "  Can't unroll; loop preheader-insertion failed.\n");
291     return LoopUnrollResult::Unmodified;
292   }
293 
294   BasicBlock *LatchBlock = L->getLoopLatch();
295   if (!LatchBlock) {
296     LLVM_DEBUG(dbgs() << "  Can't unroll; loop exit-block-insertion failed.\n");
297     return LoopUnrollResult::Unmodified;
298   }
299 
300   // Loops with indirectbr cannot be cloned.
301   if (!L->isSafeToClone()) {
302     LLVM_DEBUG(dbgs() << "  Can't unroll; Loop body cannot be cloned.\n");
303     return LoopUnrollResult::Unmodified;
304   }
305 
306   // The current loop unroll pass can unroll loops with a single latch or header
307   // that's a conditional branch exiting the loop.
308   // FIXME: The implementation can be extended to work with more complicated
309   // cases, e.g. loops with multiple latches.
310   BasicBlock *Header = L->getHeader();
311   BranchInst *HeaderBI = dyn_cast<BranchInst>(Header->getTerminator());
312   BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
313 
314   // FIXME: Support loops without conditional latch and multiple exiting blocks.
315   if (!BI ||
316       (BI->isUnconditional() && (!HeaderBI || HeaderBI->isUnconditional() ||
317                                  L->getExitingBlock() != Header))) {
318     LLVM_DEBUG(dbgs() << "  Can't unroll; loop not terminated by a conditional "
319                          "branch in the latch or header.\n");
320     return LoopUnrollResult::Unmodified;
321   }
322 
323   auto CheckLatchSuccessors = [&](unsigned S1, unsigned S2) {
324     return BI->isConditional() && BI->getSuccessor(S1) == Header &&
325            !L->contains(BI->getSuccessor(S2));
326   };
327 
328   // If we have a conditional latch, it must exit the loop.
329   if (BI && BI->isConditional() && !CheckLatchSuccessors(0, 1) &&
330       !CheckLatchSuccessors(1, 0)) {
331     LLVM_DEBUG(
332         dbgs() << "Can't unroll; a conditional latch must exit the loop");
333     return LoopUnrollResult::Unmodified;
334   }
335 
336   auto CheckHeaderSuccessors = [&](unsigned S1, unsigned S2) {
337     return HeaderBI && HeaderBI->isConditional() &&
338            L->contains(HeaderBI->getSuccessor(S1)) &&
339            !L->contains(HeaderBI->getSuccessor(S2));
340   };
341 
342   // If we do not have a conditional latch, the header must exit the loop.
343   if (BI && !BI->isConditional() && HeaderBI && HeaderBI->isConditional() &&
344       !CheckHeaderSuccessors(0, 1) && !CheckHeaderSuccessors(1, 0)) {
345     LLVM_DEBUG(dbgs() << "Can't unroll; conditional header must exit the loop");
346     return LoopUnrollResult::Unmodified;
347   }
348 
349   if (Header->hasAddressTaken()) {
350     // The loop-rotate pass can be helpful to avoid this in many cases.
351     LLVM_DEBUG(
352         dbgs() << "  Won't unroll loop: address of header block is taken.\n");
353     return LoopUnrollResult::Unmodified;
354   }
355 
356   if (ULO.TripCount != 0)
357     LLVM_DEBUG(dbgs() << "  Trip Count = " << ULO.TripCount << "\n");
358   if (ULO.TripMultiple != 1)
359     LLVM_DEBUG(dbgs() << "  Trip Multiple = " << ULO.TripMultiple << "\n");
360 
361   // Effectively "DCE" unrolled iterations that are beyond the tripcount
362   // and will never be executed.
363   if (ULO.TripCount != 0 && ULO.Count > ULO.TripCount)
364     ULO.Count = ULO.TripCount;
365 
366   // Don't enter the unroll code if there is nothing to do.
367   if (ULO.TripCount == 0 && ULO.Count < 2 && ULO.PeelCount == 0) {
368     LLVM_DEBUG(dbgs() << "Won't unroll; almost nothing to do\n");
369     return LoopUnrollResult::Unmodified;
370   }
371 
372   assert(ULO.Count > 0);
373   assert(ULO.TripMultiple > 0);
374   assert(ULO.TripCount == 0 || ULO.TripCount % ULO.TripMultiple == 0);
375 
376   // Are we eliminating the loop control altogether?
377   bool CompletelyUnroll = ULO.Count == ULO.TripCount;
378   SmallVector<BasicBlock *, 4> ExitBlocks;
379   L->getExitBlocks(ExitBlocks);
380   std::vector<BasicBlock*> OriginalLoopBlocks = L->getBlocks();
381 
382   // Go through all exits of L and see if there are any phi-nodes there. We just
383   // conservatively assume that they're inserted to preserve LCSSA form, which
384   // means that complete unrolling might break this form. We need to either fix
385   // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
386   // now we just recompute LCSSA for the outer loop, but it should be possible
387   // to fix it in-place.
388   bool NeedToFixLCSSA = PreserveLCSSA && CompletelyUnroll &&
389                         any_of(ExitBlocks, [](const BasicBlock *BB) {
390                           return isa<PHINode>(BB->begin());
391                         });
392 
393   // We assume a run-time trip count if the compiler cannot
394   // figure out the loop trip count and the unroll-runtime
395   // flag is specified.
396   bool RuntimeTripCount =
397       (ULO.TripCount == 0 && ULO.Count > 0 && ULO.AllowRuntime);
398 
399   assert((!RuntimeTripCount || !ULO.PeelCount) &&
400          "Did not expect runtime trip-count unrolling "
401          "and peeling for the same loop");
402 
403   bool Peeled = false;
404   if (ULO.PeelCount) {
405     Peeled = peelLoop(L, ULO.PeelCount, LI, SE, DT, AC, PreserveLCSSA);
406 
407     // Successful peeling may result in a change in the loop preheader/trip
408     // counts. If we later unroll the loop, we want these to be updated.
409     if (Peeled) {
410       // According to our guards and profitability checks the only
411       // meaningful exit should be latch block. Other exits go to deopt,
412       // so we do not worry about them.
413       BasicBlock *ExitingBlock = L->getLoopLatch();
414       assert(ExitingBlock && "Loop without exiting block?");
415       assert(L->isLoopExiting(ExitingBlock) && "Latch is not exiting?");
416       Preheader = L->getLoopPreheader();
417       ULO.TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
418       ULO.TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
419     }
420   }
421 
422   // Loops containing convergent instructions must have a count that divides
423   // their TripMultiple.
424   LLVM_DEBUG(
425       {
426         bool HasConvergent = false;
427         for (auto &BB : L->blocks())
428           for (auto &I : *BB)
429             if (auto CS = CallSite(&I))
430               HasConvergent |= CS.isConvergent();
431         assert((!HasConvergent || ULO.TripMultiple % ULO.Count == 0) &&
432                "Unroll count must divide trip multiple if loop contains a "
433                "convergent operation.");
434       });
435 
436   bool EpilogProfitability =
437       UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog
438                                               : isEpilogProfitable(L);
439 
440   if (RuntimeTripCount && ULO.TripMultiple % ULO.Count != 0 &&
441       !UnrollRuntimeLoopRemainder(L, ULO.Count, ULO.AllowExpensiveTripCount,
442                                   EpilogProfitability, ULO.UnrollRemainder,
443                                   ULO.ForgetAllSCEV, LI, SE, DT, AC,
444                                   PreserveLCSSA, RemainderLoop)) {
445     if (ULO.Force)
446       RuntimeTripCount = false;
447     else {
448       LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be "
449                            "generated when assuming runtime trip count\n");
450       return LoopUnrollResult::Unmodified;
451     }
452   }
453 
454   // If we know the trip count, we know the multiple...
455   unsigned BreakoutTrip = 0;
456   if (ULO.TripCount != 0) {
457     BreakoutTrip = ULO.TripCount % ULO.Count;
458     ULO.TripMultiple = 0;
459   } else {
460     // Figure out what multiple to use.
461     BreakoutTrip = ULO.TripMultiple =
462         (unsigned)GreatestCommonDivisor64(ULO.Count, ULO.TripMultiple);
463   }
464 
465   using namespace ore;
466   // Report the unrolling decision.
467   if (CompletelyUnroll) {
468     LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
469                       << " with trip count " << ULO.TripCount << "!\n");
470     if (ORE)
471       ORE->emit([&]() {
472         return OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(),
473                                   L->getHeader())
474                << "completely unrolled loop with "
475                << NV("UnrollCount", ULO.TripCount) << " iterations";
476       });
477   } else if (ULO.PeelCount) {
478     LLVM_DEBUG(dbgs() << "PEELING loop %" << Header->getName()
479                       << " with iteration count " << ULO.PeelCount << "!\n");
480     if (ORE)
481       ORE->emit([&]() {
482         return OptimizationRemark(DEBUG_TYPE, "Peeled", L->getStartLoc(),
483                                   L->getHeader())
484                << " peeled loop by " << NV("PeelCount", ULO.PeelCount)
485                << " iterations";
486       });
487   } else {
488     auto DiagBuilder = [&]() {
489       OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
490                               L->getHeader());
491       return Diag << "unrolled loop by a factor of "
492                   << NV("UnrollCount", ULO.Count);
493     };
494 
495     LLVM_DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() << " by "
496                       << ULO.Count);
497     if (ULO.TripMultiple == 0 || BreakoutTrip != ULO.TripMultiple) {
498       LLVM_DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
499       if (ORE)
500         ORE->emit([&]() {
501           return DiagBuilder() << " with a breakout at trip "
502                                << NV("BreakoutTrip", BreakoutTrip);
503         });
504     } else if (ULO.TripMultiple != 1) {
505       LLVM_DEBUG(dbgs() << " with " << ULO.TripMultiple << " trips per branch");
506       if (ORE)
507         ORE->emit([&]() {
508           return DiagBuilder()
509                  << " with " << NV("TripMultiple", ULO.TripMultiple)
510                  << " trips per branch";
511         });
512     } else if (RuntimeTripCount) {
513       LLVM_DEBUG(dbgs() << " with run-time trip count");
514       if (ORE)
515         ORE->emit(
516             [&]() { return DiagBuilder() << " with run-time trip count"; });
517     }
518     LLVM_DEBUG(dbgs() << "!\n");
519   }
520 
521   // We are going to make changes to this loop. SCEV may be keeping cached info
522   // about it, in particular about backedge taken count. The changes we make
523   // are guaranteed to invalidate this information for our loop. It is tempting
524   // to only invalidate the loop being unrolled, but it is incorrect as long as
525   // all exiting branches from all inner loops have impact on the outer loops,
526   // and if something changes inside them then any of outer loops may also
527   // change. When we forget outermost loop, we also forget all contained loops
528   // and this is what we need here.
529   if (SE) {
530     if (ULO.ForgetAllSCEV)
531       SE->forgetAllLoops();
532     else
533       SE->forgetTopmostLoop(L);
534   }
535 
536   bool ContinueOnTrue;
537   bool LatchIsExiting = BI->isConditional();
538   BasicBlock *LoopExit = nullptr;
539   if (LatchIsExiting) {
540     ContinueOnTrue = L->contains(BI->getSuccessor(0));
541     LoopExit = BI->getSuccessor(ContinueOnTrue);
542   } else {
543     NumUnrolledWithHeader++;
544     ContinueOnTrue = L->contains(HeaderBI->getSuccessor(0));
545     LoopExit = HeaderBI->getSuccessor(ContinueOnTrue);
546   }
547 
548   // For the first iteration of the loop, we should use the precloned values for
549   // PHI nodes.  Insert associations now.
550   ValueToValueMapTy LastValueMap;
551   std::vector<PHINode*> OrigPHINode;
552   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
553     OrigPHINode.push_back(cast<PHINode>(I));
554   }
555 
556   std::vector<BasicBlock *> Headers;
557   std::vector<BasicBlock *> HeaderSucc;
558   std::vector<BasicBlock *> Latches;
559   Headers.push_back(Header);
560   Latches.push_back(LatchBlock);
561 
562   if (!LatchIsExiting) {
563     auto *Term = cast<BranchInst>(Header->getTerminator());
564     if (Term->isUnconditional() || L->contains(Term->getSuccessor(0))) {
565       assert(L->contains(Term->getSuccessor(0)));
566       HeaderSucc.push_back(Term->getSuccessor(0));
567     } else {
568       assert(L->contains(Term->getSuccessor(1)));
569       HeaderSucc.push_back(Term->getSuccessor(1));
570     }
571   }
572 
573   // The current on-the-fly SSA update requires blocks to be processed in
574   // reverse postorder so that LastValueMap contains the correct value at each
575   // exit.
576   LoopBlocksDFS DFS(L);
577   DFS.perform(LI);
578 
579   // Stash the DFS iterators before adding blocks to the loop.
580   LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
581   LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
582 
583   std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
584 
585   // Loop Unrolling might create new loops. While we do preserve LoopInfo, we
586   // might break loop-simplified form for these loops (as they, e.g., would
587   // share the same exit blocks). We'll keep track of loops for which we can
588   // break this so that later we can re-simplify them.
589   SmallSetVector<Loop *, 4> LoopsToSimplify;
590   for (Loop *SubLoop : *L)
591     LoopsToSimplify.insert(SubLoop);
592 
593   if (Header->getParent()->isDebugInfoForProfiling())
594     for (BasicBlock *BB : L->getBlocks())
595       for (Instruction &I : *BB)
596         if (!isa<DbgInfoIntrinsic>(&I))
597           if (const DILocation *DIL = I.getDebugLoc()) {
598             auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.Count);
599             if (NewDIL)
600               I.setDebugLoc(NewDIL.getValue());
601             else
602               LLVM_DEBUG(dbgs()
603                          << "Failed to create new discriminator: "
604                          << DIL->getFilename() << " Line: " << DIL->getLine());
605           }
606 
607   for (unsigned It = 1; It != ULO.Count; ++It) {
608     SmallVector<BasicBlock *, 8> NewBlocks;
609     SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
610     NewLoops[L] = L;
611 
612     for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
613       ValueToValueMapTy VMap;
614       BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
615       Header->getParent()->getBasicBlockList().push_back(New);
616 
617       assert((*BB != Header || LI->getLoopFor(*BB) == L) &&
618              "Header should not be in a sub-loop");
619       // Tell LI about New.
620       const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
621       if (OldLoop)
622         LoopsToSimplify.insert(NewLoops[OldLoop]);
623 
624       if (*BB == Header)
625         // Loop over all of the PHI nodes in the block, changing them to use
626         // the incoming values from the previous block.
627         for (PHINode *OrigPHI : OrigPHINode) {
628           PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
629           Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
630           if (Instruction *InValI = dyn_cast<Instruction>(InVal))
631             if (It > 1 && L->contains(InValI))
632               InVal = LastValueMap[InValI];
633           VMap[OrigPHI] = InVal;
634           New->getInstList().erase(NewPHI);
635         }
636 
637       // Update our running map of newest clones
638       LastValueMap[*BB] = New;
639       for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
640            VI != VE; ++VI)
641         LastValueMap[VI->first] = VI->second;
642 
643       // Add phi entries for newly created values to all exit blocks.
644       for (BasicBlock *Succ : successors(*BB)) {
645         if (L->contains(Succ))
646           continue;
647         for (PHINode &PHI : Succ->phis()) {
648           Value *Incoming = PHI.getIncomingValueForBlock(*BB);
649           ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
650           if (It != LastValueMap.end())
651             Incoming = It->second;
652           PHI.addIncoming(Incoming, New);
653         }
654       }
655       // Keep track of new headers and latches as we create them, so that
656       // we can insert the proper branches later.
657       if (*BB == Header)
658         Headers.push_back(New);
659       if (*BB == LatchBlock)
660         Latches.push_back(New);
661 
662       // Keep track of the successor of the new header in the current iteration.
663       for (auto *Pred : predecessors(*BB))
664         if (Pred == Header) {
665           HeaderSucc.push_back(New);
666           break;
667         }
668 
669       NewBlocks.push_back(New);
670       UnrolledLoopBlocks.push_back(New);
671 
672       // Update DomTree: since we just copy the loop body, and each copy has a
673       // dedicated entry block (copy of the header block), this header's copy
674       // dominates all copied blocks. That means, dominance relations in the
675       // copied body are the same as in the original body.
676       if (DT) {
677         if (*BB == Header)
678           DT->addNewBlock(New, Latches[It - 1]);
679         else {
680           auto BBDomNode = DT->getNode(*BB);
681           auto BBIDom = BBDomNode->getIDom();
682           BasicBlock *OriginalBBIDom = BBIDom->getBlock();
683           DT->addNewBlock(
684               New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
685         }
686       }
687     }
688 
689     // Remap all instructions in the most recent iteration
690     remapInstructionsInBlocks(NewBlocks, LastValueMap);
691     for (BasicBlock *NewBlock : NewBlocks) {
692       for (Instruction &I : *NewBlock) {
693         if (auto *II = dyn_cast<IntrinsicInst>(&I))
694           if (II->getIntrinsicID() == Intrinsic::assume)
695             AC->registerAssumption(II);
696       }
697     }
698   }
699 
700   // Loop over the PHI nodes in the original block, setting incoming values.
701   for (PHINode *PN : OrigPHINode) {
702     if (CompletelyUnroll) {
703       PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
704       Header->getInstList().erase(PN);
705     } else if (ULO.Count > 1) {
706       Value *InVal = PN->removeIncomingValue(LatchBlock, false);
707       // If this value was defined in the loop, take the value defined by the
708       // last iteration of the loop.
709       if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
710         if (L->contains(InValI))
711           InVal = LastValueMap[InVal];
712       }
713       assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
714       PN->addIncoming(InVal, Latches.back());
715     }
716   }
717 
718   auto setDest = [LoopExit, ContinueOnTrue](BasicBlock *Src, BasicBlock *Dest,
719                                             ArrayRef<BasicBlock *> NextBlocks,
720                                             BasicBlock *BlockInLoop,
721                                             bool NeedConditional) {
722     auto *Term = cast<BranchInst>(Src->getTerminator());
723     if (NeedConditional) {
724       // Update the conditional branch's successor for the following
725       // iteration.
726       Term->setSuccessor(!ContinueOnTrue, Dest);
727     } else {
728       // Remove phi operands at this loop exit
729       if (Dest != LoopExit) {
730         BasicBlock *BB = Src;
731         for (BasicBlock *Succ : successors(BB)) {
732           // Preserve the incoming value from BB if we are jumping to the block
733           // in the current loop.
734           if (Succ == BlockInLoop)
735             continue;
736           for (PHINode &Phi : Succ->phis())
737             Phi.removeIncomingValue(BB, false);
738         }
739       }
740       // Replace the conditional branch with an unconditional one.
741       BranchInst::Create(Dest, Term);
742       Term->eraseFromParent();
743     }
744   };
745 
746   // Now that all the basic blocks for the unrolled iterations are in place,
747   // set up the branches to connect them.
748   if (LatchIsExiting) {
749     // Set up latches to branch to the new header in the unrolled iterations or
750     // the loop exit for the last latch in a fully unrolled loop.
751     for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
752       // The branch destination.
753       unsigned j = (i + 1) % e;
754       BasicBlock *Dest = Headers[j];
755       bool NeedConditional = true;
756 
757       if (RuntimeTripCount && j != 0) {
758         NeedConditional = false;
759       }
760 
761       // For a complete unroll, make the last iteration end with a branch
762       // to the exit block.
763       if (CompletelyUnroll) {
764         if (j == 0)
765           Dest = LoopExit;
766         // If using trip count upper bound to completely unroll, we need to keep
767         // the conditional branch except the last one because the loop may exit
768         // after any iteration.
769         assert(NeedConditional &&
770                "NeedCondition cannot be modified by both complete "
771                "unrolling and runtime unrolling");
772         NeedConditional =
773             (ULO.PreserveCondBr && j && !(ULO.PreserveOnlyFirst && i != 0));
774       } else if (j != BreakoutTrip &&
775                  (ULO.TripMultiple == 0 || j % ULO.TripMultiple != 0)) {
776         // If we know the trip count or a multiple of it, we can safely use an
777         // unconditional branch for some iterations.
778         NeedConditional = false;
779       }
780 
781       setDest(Latches[i], Dest, Headers, Headers[i], NeedConditional);
782     }
783   } else {
784     // Setup headers to branch to their new successors in the unrolled
785     // iterations.
786     for (unsigned i = 0, e = Headers.size(); i != e; ++i) {
787       // The branch destination.
788       unsigned j = (i + 1) % e;
789       BasicBlock *Dest = HeaderSucc[i];
790       bool NeedConditional = true;
791 
792       if (RuntimeTripCount && j != 0)
793         NeedConditional = false;
794 
795       if (CompletelyUnroll)
796         // We cannot drop the conditional branch for the last condition, as we
797         // may have to execute the loop body depending on the condition.
798         NeedConditional = j == 0 || ULO.PreserveCondBr;
799       else if (j != BreakoutTrip &&
800                (ULO.TripMultiple == 0 || j % ULO.TripMultiple != 0))
801         // If we know the trip count or a multiple of it, we can safely use an
802         // unconditional branch for some iterations.
803         NeedConditional = false;
804 
805       setDest(Headers[i], Dest, Headers, HeaderSucc[i], NeedConditional);
806     }
807 
808     // Set up latches to branch to the new header in the unrolled iterations or
809     // the loop exit for the last latch in a fully unrolled loop.
810 
811     for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
812       // The original branch was replicated in each unrolled iteration.
813       BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
814 
815       // The branch destination.
816       unsigned j = (i + 1) % e;
817       BasicBlock *Dest = Headers[j];
818 
819       // When completely unrolling, the last latch becomes unreachable.
820       if (CompletelyUnroll && j == 0)
821         new UnreachableInst(Term->getContext(), Term);
822       else
823         // Replace the conditional branch with an unconditional one.
824         BranchInst::Create(Dest, Term);
825 
826       Term->eraseFromParent();
827     }
828   }
829 
830   // Update dominators of blocks we might reach through exits.
831   // Immediate dominator of such block might change, because we add more
832   // routes which can lead to the exit: we can now reach it from the copied
833   // iterations too.
834   if (DT && ULO.Count > 1) {
835     for (auto *BB : OriginalLoopBlocks) {
836       auto *BBDomNode = DT->getNode(BB);
837       SmallVector<BasicBlock *, 16> ChildrenToUpdate;
838       for (auto *ChildDomNode : BBDomNode->getChildren()) {
839         auto *ChildBB = ChildDomNode->getBlock();
840         if (!L->contains(ChildBB))
841           ChildrenToUpdate.push_back(ChildBB);
842       }
843       BasicBlock *NewIDom;
844       BasicBlock *&TermBlock = LatchIsExiting ? LatchBlock : Header;
845       auto &TermBlocks = LatchIsExiting ? Latches : Headers;
846       if (BB == TermBlock) {
847         // The latch is special because we emit unconditional branches in
848         // some cases where the original loop contained a conditional branch.
849         // Since the latch is always at the bottom of the loop, if the latch
850         // dominated an exit before unrolling, the new dominator of that exit
851         // must also be a latch.  Specifically, the dominator is the first
852         // latch which ends in a conditional branch, or the last latch if
853         // there is no such latch.
854         // For loops exiting from the header, we limit the supported loops
855         // to have a single exiting block.
856         NewIDom = TermBlocks.back();
857         for (BasicBlock *Iter : TermBlocks) {
858           Instruction *Term = Iter->getTerminator();
859           if (isa<BranchInst>(Term) && cast<BranchInst>(Term)->isConditional()) {
860             NewIDom = Iter;
861             break;
862           }
863         }
864       } else {
865         // The new idom of the block will be the nearest common dominator
866         // of all copies of the previous idom. This is equivalent to the
867         // nearest common dominator of the previous idom and the first latch,
868         // which dominates all copies of the previous idom.
869         NewIDom = DT->findNearestCommonDominator(BB, LatchBlock);
870       }
871       for (auto *ChildBB : ChildrenToUpdate)
872         DT->changeImmediateDominator(ChildBB, NewIDom);
873     }
874   }
875 
876   assert(!DT || !UnrollVerifyDomtree ||
877          DT->verify(DominatorTree::VerificationLevel::Fast));
878 
879   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
880   // Merge adjacent basic blocks, if possible.
881   for (BasicBlock *Latch : Latches) {
882     BranchInst *Term = dyn_cast<BranchInst>(Latch->getTerminator());
883     assert((Term ||
884             (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
885            "Need a branch as terminator, except when fully unrolling with "
886            "unconditional latch");
887     if (Term && Term->isUnconditional()) {
888       BasicBlock *Dest = Term->getSuccessor(0);
889       BasicBlock *Fold = Dest->getUniquePredecessor();
890       if (MergeBlockIntoPredecessor(Dest, &DTU, LI)) {
891         // Dest has been folded into Fold. Update our worklists accordingly.
892         std::replace(Latches.begin(), Latches.end(), Dest, Fold);
893         UnrolledLoopBlocks.erase(std::remove(UnrolledLoopBlocks.begin(),
894                                              UnrolledLoopBlocks.end(), Dest),
895                                  UnrolledLoopBlocks.end());
896       }
897     }
898   }
899   // Apply updates to the DomTree.
900   DT = &DTU.getDomTree();
901 
902   // At this point, the code is well formed.  We now simplify the unrolled loop,
903   // doing constant propagation and dead code elimination as we go.
904   simplifyLoopAfterUnroll(L, !CompletelyUnroll && (ULO.Count > 1 || Peeled), LI,
905                           SE, DT, AC);
906 
907   NumCompletelyUnrolled += CompletelyUnroll;
908   ++NumUnrolled;
909 
910   Loop *OuterL = L->getParentLoop();
911   // Update LoopInfo if the loop is completely removed.
912   if (CompletelyUnroll)
913     LI->erase(L);
914 
915   // After complete unrolling most of the blocks should be contained in OuterL.
916   // However, some of them might happen to be out of OuterL (e.g. if they
917   // precede a loop exit). In this case we might need to insert PHI nodes in
918   // order to preserve LCSSA form.
919   // We don't need to check this if we already know that we need to fix LCSSA
920   // form.
921   // TODO: For now we just recompute LCSSA for the outer loop in this case, but
922   // it should be possible to fix it in-place.
923   if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
924     NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
925 
926   // If we have a pass and a DominatorTree we should re-simplify impacted loops
927   // to ensure subsequent analyses can rely on this form. We want to simplify
928   // at least one layer outside of the loop that was unrolled so that any
929   // changes to the parent loop exposed by the unrolling are considered.
930   if (DT) {
931     if (OuterL) {
932       // OuterL includes all loops for which we can break loop-simplify, so
933       // it's sufficient to simplify only it (it'll recursively simplify inner
934       // loops too).
935       if (NeedToFixLCSSA) {
936         // LCSSA must be performed on the outermost affected loop. The unrolled
937         // loop's last loop latch is guaranteed to be in the outermost loop
938         // after LoopInfo's been updated by LoopInfo::erase.
939         Loop *LatchLoop = LI->getLoopFor(Latches.back());
940         Loop *FixLCSSALoop = OuterL;
941         if (!FixLCSSALoop->contains(LatchLoop))
942           while (FixLCSSALoop->getParentLoop() != LatchLoop)
943             FixLCSSALoop = FixLCSSALoop->getParentLoop();
944 
945         formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE);
946       } else if (PreserveLCSSA) {
947         assert(OuterL->isLCSSAForm(*DT) &&
948                "Loops should be in LCSSA form after loop-unroll.");
949       }
950 
951       // TODO: That potentially might be compile-time expensive. We should try
952       // to fix the loop-simplified form incrementally.
953       simplifyLoop(OuterL, DT, LI, SE, AC, nullptr, PreserveLCSSA);
954     } else {
955       // Simplify loops for which we might've broken loop-simplify form.
956       for (Loop *SubLoop : LoopsToSimplify)
957         simplifyLoop(SubLoop, DT, LI, SE, AC, nullptr, PreserveLCSSA);
958     }
959   }
960 
961   return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
962                           : LoopUnrollResult::PartiallyUnrolled;
963 }
964 
965 /// Given an llvm.loop loop id metadata node, returns the loop hint metadata
966 /// node with the given name (for example, "llvm.loop.unroll.count"). If no
967 /// such metadata node exists, then nullptr is returned.
968 MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
969   // First operand should refer to the loop id itself.
970   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
971   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
972 
973   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
974     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
975     if (!MD)
976       continue;
977 
978     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
979     if (!S)
980       continue;
981 
982     if (Name.equals(S->getString()))
983       return MD;
984   }
985   return nullptr;
986 }
987