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/Constants.h"
39 #include "llvm/IR/DebugInfoMetadata.h"
40 #include "llvm/IR/DebugLoc.h"
41 #include "llvm/IR/DiagnosticInfo.h"
42 #include "llvm/IR/Dominators.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/Instruction.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/IntrinsicInst.h"
47 #include "llvm/IR/Metadata.h"
48 #include "llvm/IR/Module.h"
49 #include "llvm/IR/Use.h"
50 #include "llvm/IR/User.h"
51 #include "llvm/IR/ValueHandle.h"
52 #include "llvm/IR/ValueMap.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/GenericDomTree.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
60 #include "llvm/Transforms/Utils/Cloning.h"
61 #include "llvm/Transforms/Utils/Local.h"
62 #include "llvm/Transforms/Utils/LoopSimplify.h"
63 #include "llvm/Transforms/Utils/LoopUtils.h"
64 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
65 #include "llvm/Transforms/Utils/UnrollLoop.h"
66 #include "llvm/Transforms/Utils/ValueMapper.h"
67 #include <algorithm>
68 #include <assert.h>
69 #include <type_traits>
70 #include <vector>
71 
72 namespace llvm {
73 class DataLayout;
74 class Value;
75 } // namespace llvm
76 
77 using namespace llvm;
78 
79 #define DEBUG_TYPE "loop-unroll"
80 
81 // TODO: Should these be here or in LoopUnroll?
82 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
83 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
84 STATISTIC(NumUnrolledNotLatch, "Number of loops unrolled without a conditional "
85                                "latch (completely or otherwise)");
86 
87 static cl::opt<bool>
88 UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden,
89                     cl::desc("Allow runtime unrolled loops to be unrolled "
90                              "with epilog instead of prolog."));
91 
92 static cl::opt<bool>
93 UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden,
94                     cl::desc("Verify domtree after unrolling"),
95 #ifdef EXPENSIVE_CHECKS
96     cl::init(true)
97 #else
98     cl::init(false)
99 #endif
100                     );
101 
102 /// Check if unrolling created a situation where we need to insert phi nodes to
103 /// preserve LCSSA form.
104 /// \param Blocks is a vector of basic blocks representing unrolled loop.
105 /// \param L is the outer loop.
106 /// It's possible that some of the blocks are in L, and some are not. In this
107 /// case, if there is a use is outside L, and definition is inside L, we need to
108 /// insert a phi-node, otherwise LCSSA will be broken.
109 /// The function is just a helper function for llvm::UnrollLoop that returns
110 /// true if this situation occurs, indicating that LCSSA needs to be fixed.
111 static bool needToInsertPhisForLCSSA(Loop *L,
112                                      const 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 (const 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                                    const TargetTransformInfo *TTI) {
208   // Simplify any new induction variables in the partially unrolled loop.
209   if (SE && SimplifyIVs) {
210     SmallVector<WeakTrackingVH, 16> DeadInsts;
211     simplifyLoopIVs(L, SE, DT, LI, TTI, DeadInsts);
212 
213     // Aggressively clean up dead instructions that simplifyLoopIVs already
214     // identified. Any remaining should be cleaned up below.
215     while (!DeadInsts.empty()) {
216       Value *V = DeadInsts.pop_back_val();
217       if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))
218         RecursivelyDeleteTriviallyDeadInstructions(Inst);
219     }
220   }
221 
222   // At this point, the code is well formed.  Perform constprop, instsimplify,
223   // and dce.
224   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
225   SmallVector<WeakTrackingVH, 16> DeadInsts;
226   for (BasicBlock *BB : L->getBlocks()) {
227     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
228       Instruction *Inst = &*I++;
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         DeadInsts.emplace_back(Inst);
234     }
235     // We can't do recursive deletion until we're done iterating, as we might
236     // have a phi which (potentially indirectly) uses instructions later in
237     // the block we're iterating through.
238     RecursivelyDeleteTriviallyDeadInstructions(DeadInsts);
239   }
240 }
241 
242 /// Unroll the given loop by Count. The loop must be in LCSSA form.  Unrolling
243 /// can only fail when the loop's latch block is not terminated by a conditional
244 /// branch instruction. However, if the trip count (and multiple) are not known,
245 /// loop unrolling will mostly produce more code that is no faster.
246 ///
247 /// TripCount is an upper bound on the number of times the loop header runs.
248 /// Note that the trip count does not need to be exact, it can be any upper
249 /// bound on the true trip count.
250 ///
251 /// Similarly, TripMultiple divides the number of times that the LatchBlock may
252 /// execute without exiting the loop.
253 ///
254 /// If AllowRuntime is true then UnrollLoop will consider unrolling loops that
255 /// have a runtime (i.e. not compile time constant) trip count.  Unrolling these
256 /// loops require a unroll "prologue" that runs "RuntimeTripCount % Count"
257 /// iterations before branching into the unrolled loop.  UnrollLoop will not
258 /// runtime-unroll the loop if computing RuntimeTripCount will be expensive and
259 /// AllowExpensiveTripCount is false.
260 ///
261 /// The LoopInfo Analysis that is passed will be kept consistent.
262 ///
263 /// This utility preserves LoopInfo. It will also preserve ScalarEvolution and
264 /// DominatorTree if they are non-null.
265 ///
266 /// If RemainderLoop is non-null, it will receive the remainder loop (if
267 /// required and not fully unrolled).
268 LoopUnrollResult llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
269                                   ScalarEvolution *SE, DominatorTree *DT,
270                                   AssumptionCache *AC,
271                                   const TargetTransformInfo *TTI,
272                                   OptimizationRemarkEmitter *ORE,
273                                   bool PreserveLCSSA, Loop **RemainderLoop) {
274   assert(DT && "DomTree is required");
275 
276   if (!L->getLoopPreheader()) {
277     LLVM_DEBUG(dbgs() << "  Can't unroll; loop preheader-insertion failed.\n");
278     return LoopUnrollResult::Unmodified;
279   }
280 
281   if (!L->getLoopLatch()) {
282     LLVM_DEBUG(dbgs() << "  Can't unroll; loop exit-block-insertion failed.\n");
283     return LoopUnrollResult::Unmodified;
284   }
285 
286   // Loops with indirectbr cannot be cloned.
287   if (!L->isSafeToClone()) {
288     LLVM_DEBUG(dbgs() << "  Can't unroll; Loop body cannot be cloned.\n");
289     return LoopUnrollResult::Unmodified;
290   }
291 
292   if (L->getHeader()->hasAddressTaken()) {
293     // The loop-rotate pass can be helpful to avoid this in many cases.
294     LLVM_DEBUG(
295         dbgs() << "  Won't unroll loop: address of header block is taken.\n");
296     return LoopUnrollResult::Unmodified;
297   }
298 
299   if (ULO.TripCount != 0)
300     LLVM_DEBUG(dbgs() << "  Trip Count = " << ULO.TripCount << "\n");
301   if (ULO.TripMultiple != 1)
302     LLVM_DEBUG(dbgs() << "  Trip Multiple = " << ULO.TripMultiple << "\n");
303 
304   // Don't enter the unroll code if there is nothing to do.
305   if (ULO.TripCount == 0 && ULO.Count < 2) {
306     LLVM_DEBUG(dbgs() << "Won't unroll; almost nothing to do\n");
307     return LoopUnrollResult::Unmodified;
308   }
309 
310   assert(ULO.Count > 0);
311   assert(ULO.TripMultiple > 0);
312   assert(ULO.TripCount == 0 || ULO.TripCount % ULO.TripMultiple == 0);
313 
314   // All these values should be taken only after peeling because they might have
315   // changed.
316   BasicBlock *Preheader = L->getLoopPreheader();
317   BasicBlock *Header = L->getHeader();
318   BasicBlock *LatchBlock = L->getLoopLatch();
319   SmallVector<BasicBlock *, 4> ExitBlocks;
320   L->getExitBlocks(ExitBlocks);
321   std::vector<BasicBlock *> OriginalLoopBlocks = L->getBlocks();
322 
323   const unsigned MaxTripCount = SE->getSmallConstantMaxTripCount(L);
324   const bool MaxOrZero = SE->isBackedgeTakenCountMaxOrZero(L);
325 
326   // Effectively "DCE" unrolled iterations that are beyond the max tripcount
327   // and will never be executed.
328   if (MaxTripCount && ULO.Count > MaxTripCount)
329     ULO.Count = MaxTripCount;
330 
331   // Are we eliminating the loop control altogether?  Note that we can know
332   // we're eliminating the backedge without knowing exactly which iteration
333   // of the unrolled body exits.
334   const bool CompletelyUnroll = ULO.Count == MaxTripCount;
335 
336   const bool PreserveOnlyFirst = CompletelyUnroll && MaxOrZero;
337 
338   // We assume a run-time trip count if the compiler cannot
339   // figure out the loop trip count and the unroll-runtime
340   // flag is specified.
341   bool RuntimeTripCount =
342       !CompletelyUnroll && ULO.TripCount == 0 && ULO.AllowRuntime;
343 
344   // Go through all exits of L and see if there are any phi-nodes there. We just
345   // conservatively assume that they're inserted to preserve LCSSA form, which
346   // means that complete unrolling might break this form. We need to either fix
347   // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
348   // now we just recompute LCSSA for the outer loop, but it should be possible
349   // to fix it in-place.
350   bool NeedToFixLCSSA =
351       PreserveLCSSA && CompletelyUnroll &&
352       any_of(ExitBlocks,
353              [](const BasicBlock *BB) { return isa<PHINode>(BB->begin()); });
354 
355   // The current loop unroll pass can unroll loops that have
356   // (1) single latch; and
357   // (2a) latch is unconditional; or
358   // (2b) latch is conditional and is an exiting block
359   // FIXME: The implementation can be extended to work with more complicated
360   // cases, e.g. loops with multiple latches.
361   BranchInst *LatchBI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
362 
363   // A conditional branch which exits the loop, which can be optimized to an
364   // unconditional branch in the unrolled loop in some cases.
365   BranchInst *ExitingBI = nullptr;
366   bool LatchIsExiting = L->isLoopExiting(LatchBlock);
367   if (LatchIsExiting)
368     ExitingBI = LatchBI;
369   else if (BasicBlock *ExitingBlock = L->getExitingBlock())
370     ExitingBI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
371   if (!LatchBI || (LatchBI->isConditional() && !LatchIsExiting)) {
372     LLVM_DEBUG(
373         dbgs() << "Can't unroll; a conditional latch must exit the loop");
374     return LoopUnrollResult::Unmodified;
375   }
376   LLVM_DEBUG({
377     if (ExitingBI)
378       dbgs() << "  Exiting Block = " << ExitingBI->getParent()->getName()
379              << "\n";
380     else
381       dbgs() << "  No single exiting block\n";
382   });
383 
384   // Warning: ExactTripCount is the exact trip count for the block ending in
385   // ExitingBI, not neccessarily an exact exit count *for the loop*.  The
386   // distinction comes when we have an exiting latch, but the loop exits
387   // through another exit first.
388   const unsigned ExactTripCount = ExitingBI ?
389     SE->getSmallConstantTripCount(L,ExitingBI->getParent()) : 0;
390 
391   // Loops containing convergent instructions must have a count that divides
392   // their TripMultiple.
393   LLVM_DEBUG(
394       {
395         bool HasConvergent = false;
396         for (auto &BB : L->blocks())
397           for (auto &I : *BB)
398             if (auto *CB = dyn_cast<CallBase>(&I))
399               HasConvergent |= CB->isConvergent();
400         assert((!HasConvergent || ULO.TripMultiple % ULO.Count == 0) &&
401                "Unroll count must divide trip multiple if loop contains a "
402                "convergent operation.");
403       });
404 
405   bool EpilogProfitability =
406       UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog
407                                               : isEpilogProfitable(L);
408 
409   if (RuntimeTripCount && ULO.TripMultiple % ULO.Count != 0 &&
410       !UnrollRuntimeLoopRemainder(L, ULO.Count, ULO.AllowExpensiveTripCount,
411                                   EpilogProfitability, ULO.UnrollRemainder,
412                                   ULO.ForgetAllSCEV, LI, SE, DT, AC, TTI,
413                                   PreserveLCSSA, RemainderLoop)) {
414     if (ULO.Force)
415       RuntimeTripCount = false;
416     else {
417       LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be "
418                            "generated when assuming runtime trip count\n");
419       return LoopUnrollResult::Unmodified;
420     }
421   }
422 
423   // If we know the trip count, we know the multiple...
424   unsigned BreakoutTrip = 0;
425   if (ULO.TripCount != 0) {
426     BreakoutTrip = ULO.TripCount % ULO.Count;
427     ULO.TripMultiple = 0;
428   } else {
429     // Figure out what multiple to use.
430     BreakoutTrip = ULO.TripMultiple =
431         (unsigned)GreatestCommonDivisor64(ULO.Count, ULO.TripMultiple);
432   }
433 
434   using namespace ore;
435   // Report the unrolling decision.
436   if (CompletelyUnroll) {
437     LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
438                       << " with trip count " << ULO.TripCount << "!\n");
439     if (ORE)
440       ORE->emit([&]() {
441         return OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(),
442                                   L->getHeader())
443                << "completely unrolled loop with "
444                << NV("UnrollCount", ULO.TripCount) << " iterations";
445       });
446   } else {
447     auto DiagBuilder = [&]() {
448       OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
449                               L->getHeader());
450       return Diag << "unrolled loop by a factor of "
451                   << NV("UnrollCount", ULO.Count);
452     };
453 
454     LLVM_DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() << " by "
455                       << ULO.Count);
456     if (ULO.TripMultiple == 0 || BreakoutTrip != ULO.TripMultiple) {
457       LLVM_DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
458       if (ORE)
459         ORE->emit([&]() {
460           return DiagBuilder() << " with a breakout at trip "
461                                << NV("BreakoutTrip", BreakoutTrip);
462         });
463     } else if (ULO.TripMultiple != 1) {
464       LLVM_DEBUG(dbgs() << " with " << ULO.TripMultiple << " trips per branch");
465       if (ORE)
466         ORE->emit([&]() {
467           return DiagBuilder()
468                  << " with " << NV("TripMultiple", ULO.TripMultiple)
469                  << " trips per branch";
470         });
471     } else if (RuntimeTripCount) {
472       LLVM_DEBUG(dbgs() << " with run-time trip count");
473       if (ORE)
474         ORE->emit(
475             [&]() { return DiagBuilder() << " with run-time trip count"; });
476     }
477     LLVM_DEBUG(dbgs() << "!\n");
478   }
479 
480   // We are going to make changes to this loop. SCEV may be keeping cached info
481   // about it, in particular about backedge taken count. The changes we make
482   // are guaranteed to invalidate this information for our loop. It is tempting
483   // to only invalidate the loop being unrolled, but it is incorrect as long as
484   // all exiting branches from all inner loops have impact on the outer loops,
485   // and if something changes inside them then any of outer loops may also
486   // change. When we forget outermost loop, we also forget all contained loops
487   // and this is what we need here.
488   if (SE) {
489     if (ULO.ForgetAllSCEV)
490       SE->forgetAllLoops();
491     else
492       SE->forgetTopmostLoop(L);
493   }
494 
495   if (!LatchIsExiting)
496     ++NumUnrolledNotLatch;
497 
498   // For the first iteration of the loop, we should use the precloned values for
499   // PHI nodes.  Insert associations now.
500   ValueToValueMapTy LastValueMap;
501   std::vector<PHINode*> OrigPHINode;
502   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
503     OrigPHINode.push_back(cast<PHINode>(I));
504   }
505 
506   std::vector<BasicBlock *> Headers;
507   std::vector<BasicBlock *> ExitingBlocks;
508   std::vector<BasicBlock *> Latches;
509   Headers.push_back(Header);
510   Latches.push_back(LatchBlock);
511   if (ExitingBI)
512     ExitingBlocks.push_back(ExitingBI->getParent());
513 
514   // The current on-the-fly SSA update requires blocks to be processed in
515   // reverse postorder so that LastValueMap contains the correct value at each
516   // exit.
517   LoopBlocksDFS DFS(L);
518   DFS.perform(LI);
519 
520   // Stash the DFS iterators before adding blocks to the loop.
521   LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
522   LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
523 
524   std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
525 
526   // Loop Unrolling might create new loops. While we do preserve LoopInfo, we
527   // might break loop-simplified form for these loops (as they, e.g., would
528   // share the same exit blocks). We'll keep track of loops for which we can
529   // break this so that later we can re-simplify them.
530   SmallSetVector<Loop *, 4> LoopsToSimplify;
531   for (Loop *SubLoop : *L)
532     LoopsToSimplify.insert(SubLoop);
533 
534   // When a FSDiscriminator is enabled, we don't need to add the multiply
535   // factors to the discriminators.
536   if (Header->getParent()->isDebugInfoForProfiling() && !EnableFSDiscriminator)
537     for (BasicBlock *BB : L->getBlocks())
538       for (Instruction &I : *BB)
539         if (!isa<DbgInfoIntrinsic>(&I))
540           if (const DILocation *DIL = I.getDebugLoc()) {
541             auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.Count);
542             if (NewDIL)
543               I.setDebugLoc(NewDIL.getValue());
544             else
545               LLVM_DEBUG(dbgs()
546                          << "Failed to create new discriminator: "
547                          << DIL->getFilename() << " Line: " << DIL->getLine());
548           }
549 
550   // Identify what noalias metadata is inside the loop: if it is inside the
551   // loop, the associated metadata must be cloned for each iteration.
552   SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes;
553   identifyNoAliasScopesToClone(L->getBlocks(), LoopLocalNoAliasDeclScopes);
554 
555   for (unsigned It = 1; It != ULO.Count; ++It) {
556     SmallVector<BasicBlock *, 8> NewBlocks;
557     SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
558     NewLoops[L] = L;
559 
560     for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
561       ValueToValueMapTy VMap;
562       BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
563       Header->getParent()->getBasicBlockList().push_back(New);
564 
565       assert((*BB != Header || LI->getLoopFor(*BB) == L) &&
566              "Header should not be in a sub-loop");
567       // Tell LI about New.
568       const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
569       if (OldLoop)
570         LoopsToSimplify.insert(NewLoops[OldLoop]);
571 
572       if (*BB == Header)
573         // Loop over all of the PHI nodes in the block, changing them to use
574         // the incoming values from the previous block.
575         for (PHINode *OrigPHI : OrigPHINode) {
576           PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
577           Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
578           if (Instruction *InValI = dyn_cast<Instruction>(InVal))
579             if (It > 1 && L->contains(InValI))
580               InVal = LastValueMap[InValI];
581           VMap[OrigPHI] = InVal;
582           New->getInstList().erase(NewPHI);
583         }
584 
585       // Update our running map of newest clones
586       LastValueMap[*BB] = New;
587       for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
588            VI != VE; ++VI)
589         LastValueMap[VI->first] = VI->second;
590 
591       // Add phi entries for newly created values to all exit blocks.
592       for (BasicBlock *Succ : successors(*BB)) {
593         if (L->contains(Succ))
594           continue;
595         for (PHINode &PHI : Succ->phis()) {
596           Value *Incoming = PHI.getIncomingValueForBlock(*BB);
597           ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
598           if (It != LastValueMap.end())
599             Incoming = It->second;
600           PHI.addIncoming(Incoming, New);
601         }
602       }
603       // Keep track of new headers and latches as we create them, so that
604       // we can insert the proper branches later.
605       if (*BB == Header)
606         Headers.push_back(New);
607       if (*BB == LatchBlock)
608         Latches.push_back(New);
609 
610       // Keep track of the exiting block and its successor block contained in
611       // the loop for the current iteration.
612       if (ExitingBI)
613         if (*BB == ExitingBlocks[0])
614           ExitingBlocks.push_back(New);
615 
616       NewBlocks.push_back(New);
617       UnrolledLoopBlocks.push_back(New);
618 
619       // Update DomTree: since we just copy the loop body, and each copy has a
620       // dedicated entry block (copy of the header block), this header's copy
621       // dominates all copied blocks. That means, dominance relations in the
622       // copied body are the same as in the original body.
623       if (*BB == Header)
624         DT->addNewBlock(New, Latches[It - 1]);
625       else {
626         auto BBDomNode = DT->getNode(*BB);
627         auto BBIDom = BBDomNode->getIDom();
628         BasicBlock *OriginalBBIDom = BBIDom->getBlock();
629         DT->addNewBlock(
630             New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
631       }
632     }
633 
634     // Remap all instructions in the most recent iteration
635     remapInstructionsInBlocks(NewBlocks, LastValueMap);
636     for (BasicBlock *NewBlock : NewBlocks)
637       for (Instruction &I : *NewBlock)
638         if (auto *II = dyn_cast<AssumeInst>(&I))
639           AC->registerAssumption(II);
640 
641     {
642       // Identify what other metadata depends on the cloned version. After
643       // cloning, replace the metadata with the corrected version for both
644       // memory instructions and noalias intrinsics.
645       std::string ext = (Twine("It") + Twine(It)).str();
646       cloneAndAdaptNoAliasScopes(LoopLocalNoAliasDeclScopes, NewBlocks,
647                                  Header->getContext(), ext);
648     }
649   }
650 
651   // Loop over the PHI nodes in the original block, setting incoming values.
652   for (PHINode *PN : OrigPHINode) {
653     if (CompletelyUnroll) {
654       PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
655       Header->getInstList().erase(PN);
656     } else if (ULO.Count > 1) {
657       Value *InVal = PN->removeIncomingValue(LatchBlock, false);
658       // If this value was defined in the loop, take the value defined by the
659       // last iteration of the loop.
660       if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
661         if (L->contains(InValI))
662           InVal = LastValueMap[InVal];
663       }
664       assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
665       PN->addIncoming(InVal, Latches.back());
666     }
667   }
668 
669   // Connect latches of the unrolled iterations to the headers of the next
670   // iteration. Currently they point to the header of the same iteration.
671   for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
672     unsigned j = (i + 1) % e;
673     Latches[i]->getTerminator()->replaceSuccessorWith(Headers[i], Headers[j]);
674   }
675 
676   // Update dominators of blocks we might reach through exits.
677   // Immediate dominator of such block might change, because we add more
678   // routes which can lead to the exit: we can now reach it from the copied
679   // iterations too.
680   if (ULO.Count > 1) {
681     for (auto *BB : OriginalLoopBlocks) {
682       auto *BBDomNode = DT->getNode(BB);
683       SmallVector<BasicBlock *, 16> ChildrenToUpdate;
684       for (auto *ChildDomNode : BBDomNode->children()) {
685         auto *ChildBB = ChildDomNode->getBlock();
686         if (!L->contains(ChildBB))
687           ChildrenToUpdate.push_back(ChildBB);
688       }
689       // The new idom of the block will be the nearest common dominator
690       // of all copies of the previous idom. This is equivalent to the
691       // nearest common dominator of the previous idom and the first latch,
692       // which dominates all copies of the previous idom.
693       BasicBlock *NewIDom = DT->findNearestCommonDominator(BB, LatchBlock);
694       for (auto *ChildBB : ChildrenToUpdate)
695         DT->changeImmediateDominator(ChildBB, NewIDom);
696     }
697   }
698 
699   assert(!UnrollVerifyDomtree ||
700          DT->verify(DominatorTree::VerificationLevel::Fast));
701 
702   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
703 
704   if (ExitingBI) {
705     auto SetDest = [&](BasicBlock *Src, bool WillExit, bool ExitOnTrue) {
706       auto *Term = cast<BranchInst>(Src->getTerminator());
707       const unsigned Idx = ExitOnTrue ^ WillExit;
708       BasicBlock *Dest = Term->getSuccessor(Idx);
709       BasicBlock *DeadSucc = Term->getSuccessor(1-Idx);
710 
711       // Remove predecessors from all non-Dest successors.
712       DeadSucc->removePredecessor(Src, /* KeepOneInputPHIs */ true);
713 
714       // Replace the conditional branch with an unconditional one.
715       BranchInst::Create(Dest, Term);
716       Term->eraseFromParent();
717 
718       DTU.applyUpdates({{DominatorTree::Delete, Src, DeadSucc}});
719     };
720 
721     auto WillExit = [&](unsigned i, unsigned j) -> Optional<bool> {
722       if (CompletelyUnroll) {
723         if (PreserveOnlyFirst) {
724           if (i == 0)
725             return None;
726           return j == 0;
727         }
728         // Complete (but possibly inexact) unrolling
729         if (j == 0)
730           return true;
731         // Warning: ExactTripCount is the trip count of the exiting
732         // block which ends in ExitingBI, not neccessarily the loop.
733         if (ExactTripCount && j != ExactTripCount)
734           return false;
735         return None;
736       }
737 
738       if (RuntimeTripCount && j != 0)
739         return false;
740 
741       if (j != BreakoutTrip &&
742           (ULO.TripMultiple == 0 || j % ULO.TripMultiple != 0)) {
743         // If we know the trip count or a multiple of it, we can safely use an
744         // unconditional branch for some iterations.
745         return false;
746       }
747       return None;
748     };
749 
750     // Fold branches for iterations where we know that they will exit or not
751     // exit.
752     bool ExitOnTrue = !L->contains(ExitingBI->getSuccessor(0));
753     for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
754       // The branch destination.
755       unsigned j = (i + 1) % e;
756       Optional<bool> KnownWillExit = WillExit(i, j);
757       if (!KnownWillExit)
758         continue;
759 
760       // TODO: Also fold known-exiting branches for non-latch exits.
761       if (*KnownWillExit && !LatchIsExiting)
762         continue;
763 
764       SetDest(ExitingBlocks[i], *KnownWillExit, ExitOnTrue);
765     }
766   }
767 
768 
769   // When completely unrolling, the last latch becomes unreachable.
770   if (!LatchIsExiting && CompletelyUnroll)
771     changeToUnreachable(Latches.back()->getTerminator(), /* UseTrap */ false,
772                         PreserveLCSSA, &DTU);
773 
774   // Merge adjacent basic blocks, if possible.
775   for (BasicBlock *Latch : Latches) {
776     BranchInst *Term = dyn_cast<BranchInst>(Latch->getTerminator());
777     assert((Term ||
778             (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
779            "Need a branch as terminator, except when fully unrolling with "
780            "unconditional latch");
781     if (Term && Term->isUnconditional()) {
782       BasicBlock *Dest = Term->getSuccessor(0);
783       BasicBlock *Fold = Dest->getUniquePredecessor();
784       if (MergeBlockIntoPredecessor(Dest, &DTU, LI)) {
785         // Dest has been folded into Fold. Update our worklists accordingly.
786         std::replace(Latches.begin(), Latches.end(), Dest, Fold);
787         llvm::erase_value(UnrolledLoopBlocks, Dest);
788       }
789     }
790   }
791   // Apply updates to the DomTree.
792   DT = &DTU.getDomTree();
793 
794   // At this point, the code is well formed.  We now simplify the unrolled loop,
795   // doing constant propagation and dead code elimination as we go.
796   simplifyLoopAfterUnroll(L, !CompletelyUnroll && ULO.Count > 1, LI, SE, DT, AC,
797                           TTI);
798 
799   NumCompletelyUnrolled += CompletelyUnroll;
800   ++NumUnrolled;
801 
802   Loop *OuterL = L->getParentLoop();
803   // Update LoopInfo if the loop is completely removed.
804   if (CompletelyUnroll)
805     LI->erase(L);
806 
807   // After complete unrolling most of the blocks should be contained in OuterL.
808   // However, some of them might happen to be out of OuterL (e.g. if they
809   // precede a loop exit). In this case we might need to insert PHI nodes in
810   // order to preserve LCSSA form.
811   // We don't need to check this if we already know that we need to fix LCSSA
812   // form.
813   // TODO: For now we just recompute LCSSA for the outer loop in this case, but
814   // it should be possible to fix it in-place.
815   if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
816     NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
817 
818   // Make sure that loop-simplify form is preserved. We want to simplify
819   // at least one layer outside of the loop that was unrolled so that any
820   // changes to the parent loop exposed by the unrolling are considered.
821   if (OuterL) {
822     // OuterL includes all loops for which we can break loop-simplify, so
823     // it's sufficient to simplify only it (it'll recursively simplify inner
824     // loops too).
825     if (NeedToFixLCSSA) {
826       // LCSSA must be performed on the outermost affected loop. The unrolled
827       // loop's last loop latch is guaranteed to be in the outermost loop
828       // after LoopInfo's been updated by LoopInfo::erase.
829       Loop *LatchLoop = LI->getLoopFor(Latches.back());
830       Loop *FixLCSSALoop = OuterL;
831       if (!FixLCSSALoop->contains(LatchLoop))
832         while (FixLCSSALoop->getParentLoop() != LatchLoop)
833           FixLCSSALoop = FixLCSSALoop->getParentLoop();
834 
835       formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE);
836     } else if (PreserveLCSSA) {
837       assert(OuterL->isLCSSAForm(*DT) &&
838              "Loops should be in LCSSA form after loop-unroll.");
839     }
840 
841     // TODO: That potentially might be compile-time expensive. We should try
842     // to fix the loop-simplified form incrementally.
843     simplifyLoop(OuterL, DT, LI, SE, AC, nullptr, PreserveLCSSA);
844   } else {
845     // Simplify loops for which we might've broken loop-simplify form.
846     for (Loop *SubLoop : LoopsToSimplify)
847       simplifyLoop(SubLoop, DT, LI, SE, AC, nullptr, PreserveLCSSA);
848   }
849 
850   return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
851                           : LoopUnrollResult::PartiallyUnrolled;
852 }
853 
854 /// Given an llvm.loop loop id metadata node, returns the loop hint metadata
855 /// node with the given name (for example, "llvm.loop.unroll.count"). If no
856 /// such metadata node exists, then nullptr is returned.
857 MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
858   // First operand should refer to the loop id itself.
859   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
860   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
861 
862   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
863     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
864     if (!MD)
865       continue;
866 
867     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
868     if (!S)
869       continue;
870 
871     if (Name.equals(S->getString()))
872       return MD;
873   }
874   return nullptr;
875 }
876