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, std::vector<BasicBlock *> Blocks,
112                                      LoopInfo *LI) {
113   for (BasicBlock *BB : Blocks) {
114     if (LI->getLoopFor(BB) == L)
115       continue;
116     for (Instruction &I : *BB) {
117       for (Use &U : I.operands()) {
118         if (auto Def = dyn_cast<Instruction>(U)) {
119           Loop *DefLoop = LI->getLoopFor(Def->getParent());
120           if (!DefLoop)
121             continue;
122           if (DefLoop->contains(L))
123             return true;
124         }
125       }
126     }
127   }
128   return false;
129 }
130 
131 /// Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary
132 /// and adds a mapping from the original loop to the new loop to NewLoops.
133 /// Returns nullptr if no new loop was created and a pointer to the
134 /// original loop OriginalBB was part of otherwise.
135 const Loop* llvm::addClonedBlockToLoopInfo(BasicBlock *OriginalBB,
136                                            BasicBlock *ClonedBB, LoopInfo *LI,
137                                            NewLoopsMap &NewLoops) {
138   // Figure out which loop New is in.
139   const Loop *OldLoop = LI->getLoopFor(OriginalBB);
140   assert(OldLoop && "Should (at least) be in the loop being unrolled!");
141 
142   Loop *&NewLoop = NewLoops[OldLoop];
143   if (!NewLoop) {
144     // Found a new sub-loop.
145     assert(OriginalBB == OldLoop->getHeader() &&
146            "Header should be first in RPO");
147 
148     NewLoop = LI->AllocateLoop();
149     Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
150 
151     if (NewLoopParent)
152       NewLoopParent->addChildLoop(NewLoop);
153     else
154       LI->addTopLevelLoop(NewLoop);
155 
156     NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
157     return OldLoop;
158   } else {
159     NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
160     return nullptr;
161   }
162 }
163 
164 /// The function chooses which type of unroll (epilog or prolog) is more
165 /// profitabale.
166 /// Epilog unroll is more profitable when there is PHI that starts from
167 /// constant.  In this case epilog will leave PHI start from constant,
168 /// but prolog will convert it to non-constant.
169 ///
170 /// loop:
171 ///   PN = PHI [I, Latch], [CI, PreHeader]
172 ///   I = foo(PN)
173 ///   ...
174 ///
175 /// Epilog unroll case.
176 /// loop:
177 ///   PN = PHI [I2, Latch], [CI, PreHeader]
178 ///   I1 = foo(PN)
179 ///   I2 = foo(I1)
180 ///   ...
181 /// Prolog unroll case.
182 ///   NewPN = PHI [PrologI, Prolog], [CI, PreHeader]
183 /// loop:
184 ///   PN = PHI [I2, Latch], [NewPN, PreHeader]
185 ///   I1 = foo(PN)
186 ///   I2 = foo(I1)
187 ///   ...
188 ///
189 static bool isEpilogProfitable(Loop *L) {
190   BasicBlock *PreHeader = L->getLoopPreheader();
191   BasicBlock *Header = L->getHeader();
192   assert(PreHeader && Header);
193   for (const PHINode &PN : Header->phis()) {
194     if (isa<ConstantInt>(PN.getIncomingValueForBlock(PreHeader)))
195       return true;
196   }
197   return false;
198 }
199 
200 /// Perform some cleanup and simplifications on loops after unrolling. It is
201 /// useful to simplify the IV's in the new loop, as well as do a quick
202 /// simplify/dce pass of the instructions.
203 void llvm::simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI,
204                                    ScalarEvolution *SE, DominatorTree *DT,
205                                    AssumptionCache *AC,
206                                    const TargetTransformInfo *TTI) {
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, TTI, 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                                   const TargetTransformInfo *TTI,
286                                   OptimizationRemarkEmitter *ORE,
287                                   bool PreserveLCSSA, Loop **RemainderLoop) {
288 
289   BasicBlock *Preheader = L->getLoopPreheader();
290   if (!Preheader) {
291     LLVM_DEBUG(dbgs() << "  Can't unroll; loop preheader-insertion failed.\n");
292     return LoopUnrollResult::Unmodified;
293   }
294 
295   BasicBlock *LatchBlock = L->getLoopLatch();
296   if (!LatchBlock) {
297     LLVM_DEBUG(dbgs() << "  Can't unroll; loop exit-block-insertion failed.\n");
298     return LoopUnrollResult::Unmodified;
299   }
300 
301   // Loops with indirectbr cannot be cloned.
302   if (!L->isSafeToClone()) {
303     LLVM_DEBUG(dbgs() << "  Can't unroll; Loop body cannot be cloned.\n");
304     return LoopUnrollResult::Unmodified;
305   }
306 
307   // The current loop unroll pass can unroll loops that have
308   // (1) single latch; and
309   // (2a) latch is an exiting block; or
310   // (2b) latch is unconditional and there exists a single exiting block.
311   // FIXME: The implementation can be extended to work with more complicated
312   // cases, e.g. loops with multiple latches.
313   BasicBlock *Header = L->getHeader();
314   BranchInst *LatchBI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
315 
316   // A conditional branch which exits the loop, which can be optimized to an
317   // unconditional branch in the unrolled loop in some cases.
318   BranchInst *ExitingBI = nullptr;
319   bool LatchIsExiting = L->isLoopExiting(LatchBlock);
320   if (LatchIsExiting)
321     ExitingBI = LatchBI;
322   else if (BasicBlock *ExitingBlock = L->getExitingBlock())
323     ExitingBI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
324   if (!LatchBI || !ExitingBI) {
325     LLVM_DEBUG(dbgs() << "  Can't unroll; loop not terminated by a conditional "
326                          "branch in latch or a single exiting block.\n");
327     return LoopUnrollResult::Unmodified;
328   }
329   if (LatchBI->isConditional() && LatchBI != ExitingBI) {
330     LLVM_DEBUG(
331         dbgs() << "Can't unroll; a conditional latch must exit the loop");
332     return LoopUnrollResult::Unmodified;
333   }
334   LLVM_DEBUG(dbgs() << "  Exiting Block = " << ExitingBI->getParent()->getName()
335                     << "\n");
336 
337   if (Header->hasAddressTaken()) {
338     // The loop-rotate pass can be helpful to avoid this in many cases.
339     LLVM_DEBUG(
340         dbgs() << "  Won't unroll loop: address of header block is taken.\n");
341     return LoopUnrollResult::Unmodified;
342   }
343 
344   if (ULO.TripCount != 0)
345     LLVM_DEBUG(dbgs() << "  Trip Count = " << ULO.TripCount << "\n");
346   if (ULO.TripMultiple != 1)
347     LLVM_DEBUG(dbgs() << "  Trip Multiple = " << ULO.TripMultiple << "\n");
348 
349   // Effectively "DCE" unrolled iterations that are beyond the tripcount
350   // and will never be executed.
351   if (ULO.TripCount != 0 && ULO.Count > ULO.TripCount)
352     ULO.Count = ULO.TripCount;
353 
354   // Don't enter the unroll code if there is nothing to do.
355   if (ULO.TripCount == 0 && ULO.Count < 2 && ULO.PeelCount == 0) {
356     LLVM_DEBUG(dbgs() << "Won't unroll; almost nothing to do\n");
357     return LoopUnrollResult::Unmodified;
358   }
359 
360   assert(ULO.Count > 0);
361   assert(ULO.TripMultiple > 0);
362   assert(ULO.TripCount == 0 || ULO.TripCount % ULO.TripMultiple == 0);
363 
364   // Are we eliminating the loop control altogether?
365   bool CompletelyUnroll = ULO.Count == ULO.TripCount;
366   SmallVector<BasicBlock *, 4> ExitBlocks;
367   L->getExitBlocks(ExitBlocks);
368   std::vector<BasicBlock*> OriginalLoopBlocks = L->getBlocks();
369 
370   // Go through all exits of L and see if there are any phi-nodes there. We just
371   // conservatively assume that they're inserted to preserve LCSSA form, which
372   // means that complete unrolling might break this form. We need to either fix
373   // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
374   // now we just recompute LCSSA for the outer loop, but it should be possible
375   // to fix it in-place.
376   bool NeedToFixLCSSA = PreserveLCSSA && CompletelyUnroll &&
377                         any_of(ExitBlocks, [](const BasicBlock *BB) {
378                           return isa<PHINode>(BB->begin());
379                         });
380 
381   // We assume a run-time trip count if the compiler cannot
382   // figure out the loop trip count and the unroll-runtime
383   // flag is specified.
384   bool RuntimeTripCount =
385       (ULO.TripCount == 0 && ULO.Count > 0 && ULO.AllowRuntime);
386 
387   assert((!RuntimeTripCount || !ULO.PeelCount) &&
388          "Did not expect runtime trip-count unrolling "
389          "and peeling for the same loop");
390 
391   bool Peeled = false;
392   if (ULO.PeelCount) {
393     Peeled = peelLoop(L, ULO.PeelCount, LI, SE, DT, AC, PreserveLCSSA);
394 
395     // Successful peeling may result in a change in the loop preheader/trip
396     // counts. If we later unroll the loop, we want these to be updated.
397     if (Peeled) {
398       // According to our guards and profitability checks the only
399       // meaningful exit should be latch block. Other exits go to deopt,
400       // so we do not worry about them.
401       BasicBlock *ExitingBlock = L->getLoopLatch();
402       assert(ExitingBlock && "Loop without exiting block?");
403       assert(L->isLoopExiting(ExitingBlock) && "Latch is not exiting?");
404       Preheader = L->getLoopPreheader();
405       ULO.TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
406       ULO.TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
407     }
408   }
409 
410   // Loops containing convergent instructions must have a count that divides
411   // their TripMultiple.
412   LLVM_DEBUG(
413       {
414         bool HasConvergent = false;
415         for (auto &BB : L->blocks())
416           for (auto &I : *BB)
417             if (auto *CB = dyn_cast<CallBase>(&I))
418               HasConvergent |= CB->isConvergent();
419         assert((!HasConvergent || ULO.TripMultiple % ULO.Count == 0) &&
420                "Unroll count must divide trip multiple if loop contains a "
421                "convergent operation.");
422       });
423 
424   bool EpilogProfitability =
425       UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog
426                                               : isEpilogProfitable(L);
427 
428   if (RuntimeTripCount && ULO.TripMultiple % ULO.Count != 0 &&
429       !UnrollRuntimeLoopRemainder(L, ULO.Count, ULO.AllowExpensiveTripCount,
430                                   EpilogProfitability, ULO.UnrollRemainder,
431                                   ULO.ForgetAllSCEV, LI, SE, DT, AC, TTI,
432                                   PreserveLCSSA, RemainderLoop)) {
433     if (ULO.Force)
434       RuntimeTripCount = false;
435     else {
436       LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be "
437                            "generated when assuming runtime trip count\n");
438       return LoopUnrollResult::Unmodified;
439     }
440   }
441 
442   // If we know the trip count, we know the multiple...
443   unsigned BreakoutTrip = 0;
444   if (ULO.TripCount != 0) {
445     BreakoutTrip = ULO.TripCount % ULO.Count;
446     ULO.TripMultiple = 0;
447   } else {
448     // Figure out what multiple to use.
449     BreakoutTrip = ULO.TripMultiple =
450         (unsigned)GreatestCommonDivisor64(ULO.Count, ULO.TripMultiple);
451   }
452 
453   using namespace ore;
454   // Report the unrolling decision.
455   if (CompletelyUnroll) {
456     LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
457                       << " with trip count " << ULO.TripCount << "!\n");
458     if (ORE)
459       ORE->emit([&]() {
460         return OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(),
461                                   L->getHeader())
462                << "completely unrolled loop with "
463                << NV("UnrollCount", ULO.TripCount) << " iterations";
464       });
465   } else if (ULO.PeelCount) {
466     LLVM_DEBUG(dbgs() << "PEELING loop %" << Header->getName()
467                       << " with iteration count " << ULO.PeelCount << "!\n");
468     if (ORE)
469       ORE->emit([&]() {
470         return OptimizationRemark(DEBUG_TYPE, "Peeled", L->getStartLoc(),
471                                   L->getHeader())
472                << " peeled loop by " << NV("PeelCount", ULO.PeelCount)
473                << " iterations";
474       });
475   } else {
476     auto DiagBuilder = [&]() {
477       OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
478                               L->getHeader());
479       return Diag << "unrolled loop by a factor of "
480                   << NV("UnrollCount", ULO.Count);
481     };
482 
483     LLVM_DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() << " by "
484                       << ULO.Count);
485     if (ULO.TripMultiple == 0 || BreakoutTrip != ULO.TripMultiple) {
486       LLVM_DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
487       if (ORE)
488         ORE->emit([&]() {
489           return DiagBuilder() << " with a breakout at trip "
490                                << NV("BreakoutTrip", BreakoutTrip);
491         });
492     } else if (ULO.TripMultiple != 1) {
493       LLVM_DEBUG(dbgs() << " with " << ULO.TripMultiple << " trips per branch");
494       if (ORE)
495         ORE->emit([&]() {
496           return DiagBuilder()
497                  << " with " << NV("TripMultiple", ULO.TripMultiple)
498                  << " trips per branch";
499         });
500     } else if (RuntimeTripCount) {
501       LLVM_DEBUG(dbgs() << " with run-time trip count");
502       if (ORE)
503         ORE->emit(
504             [&]() { return DiagBuilder() << " with run-time trip count"; });
505     }
506     LLVM_DEBUG(dbgs() << "!\n");
507   }
508 
509   // We are going to make changes to this loop. SCEV may be keeping cached info
510   // about it, in particular about backedge taken count. The changes we make
511   // are guaranteed to invalidate this information for our loop. It is tempting
512   // to only invalidate the loop being unrolled, but it is incorrect as long as
513   // all exiting branches from all inner loops have impact on the outer loops,
514   // and if something changes inside them then any of outer loops may also
515   // change. When we forget outermost loop, we also forget all contained loops
516   // and this is what we need here.
517   if (SE) {
518     if (ULO.ForgetAllSCEV)
519       SE->forgetAllLoops();
520     else
521       SE->forgetTopmostLoop(L);
522   }
523 
524   if (!LatchIsExiting)
525     ++NumUnrolledNotLatch;
526   bool ContinueOnTrue = L->contains(ExitingBI->getSuccessor(0));
527   BasicBlock *LoopExit = ExitingBI->getSuccessor(ContinueOnTrue);
528 
529   // For the first iteration of the loop, we should use the precloned values for
530   // PHI nodes.  Insert associations now.
531   ValueToValueMapTy LastValueMap;
532   std::vector<PHINode*> OrigPHINode;
533   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
534     OrigPHINode.push_back(cast<PHINode>(I));
535   }
536 
537   std::vector<BasicBlock *> Headers;
538   std::vector<BasicBlock *> ExitingBlocks;
539   std::vector<BasicBlock *> ExitingSucc;
540   std::vector<BasicBlock *> Latches;
541   Headers.push_back(Header);
542   Latches.push_back(LatchBlock);
543   ExitingBlocks.push_back(ExitingBI->getParent());
544   ExitingSucc.push_back(ExitingBI->getSuccessor(!ContinueOnTrue));
545 
546   // The current on-the-fly SSA update requires blocks to be processed in
547   // reverse postorder so that LastValueMap contains the correct value at each
548   // exit.
549   LoopBlocksDFS DFS(L);
550   DFS.perform(LI);
551 
552   // Stash the DFS iterators before adding blocks to the loop.
553   LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
554   LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
555 
556   std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
557 
558   // Loop Unrolling might create new loops. While we do preserve LoopInfo, we
559   // might break loop-simplified form for these loops (as they, e.g., would
560   // share the same exit blocks). We'll keep track of loops for which we can
561   // break this so that later we can re-simplify them.
562   SmallSetVector<Loop *, 4> LoopsToSimplify;
563   for (Loop *SubLoop : *L)
564     LoopsToSimplify.insert(SubLoop);
565 
566   if (Header->getParent()->isDebugInfoForProfiling())
567     for (BasicBlock *BB : L->getBlocks())
568       for (Instruction &I : *BB)
569         if (!isa<DbgInfoIntrinsic>(&I))
570           if (const DILocation *DIL = I.getDebugLoc()) {
571             auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.Count);
572             if (NewDIL)
573               I.setDebugLoc(NewDIL.getValue());
574             else
575               LLVM_DEBUG(dbgs()
576                          << "Failed to create new discriminator: "
577                          << DIL->getFilename() << " Line: " << DIL->getLine());
578           }
579 
580   for (unsigned It = 1; It != ULO.Count; ++It) {
581     SmallVector<BasicBlock *, 8> NewBlocks;
582     SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
583     NewLoops[L] = L;
584 
585     for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
586       ValueToValueMapTy VMap;
587       BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
588       Header->getParent()->getBasicBlockList().push_back(New);
589 
590       assert((*BB != Header || LI->getLoopFor(*BB) == L) &&
591              "Header should not be in a sub-loop");
592       // Tell LI about New.
593       const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
594       if (OldLoop)
595         LoopsToSimplify.insert(NewLoops[OldLoop]);
596 
597       if (*BB == Header)
598         // Loop over all of the PHI nodes in the block, changing them to use
599         // the incoming values from the previous block.
600         for (PHINode *OrigPHI : OrigPHINode) {
601           PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
602           Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
603           if (Instruction *InValI = dyn_cast<Instruction>(InVal))
604             if (It > 1 && L->contains(InValI))
605               InVal = LastValueMap[InValI];
606           VMap[OrigPHI] = InVal;
607           New->getInstList().erase(NewPHI);
608         }
609 
610       // Update our running map of newest clones
611       LastValueMap[*BB] = New;
612       for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
613            VI != VE; ++VI)
614         LastValueMap[VI->first] = VI->second;
615 
616       // Add phi entries for newly created values to all exit blocks.
617       for (BasicBlock *Succ : successors(*BB)) {
618         if (L->contains(Succ))
619           continue;
620         for (PHINode &PHI : Succ->phis()) {
621           Value *Incoming = PHI.getIncomingValueForBlock(*BB);
622           ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
623           if (It != LastValueMap.end())
624             Incoming = It->second;
625           PHI.addIncoming(Incoming, New);
626         }
627       }
628       // Keep track of new headers and latches as we create them, so that
629       // we can insert the proper branches later.
630       if (*BB == Header)
631         Headers.push_back(New);
632       if (*BB == LatchBlock)
633         Latches.push_back(New);
634 
635       // Keep track of the exiting block and its successor block contained in
636       // the loop for the current iteration.
637       if (*BB == ExitingBlocks[0])
638         ExitingBlocks.push_back(New);
639       if (*BB == ExitingSucc[0])
640         ExitingSucc.push_back(New);
641 
642       NewBlocks.push_back(New);
643       UnrolledLoopBlocks.push_back(New);
644 
645       // Update DomTree: since we just copy the loop body, and each copy has a
646       // dedicated entry block (copy of the header block), this header's copy
647       // dominates all copied blocks. That means, dominance relations in the
648       // copied body are the same as in the original body.
649       if (DT) {
650         if (*BB == Header)
651           DT->addNewBlock(New, Latches[It - 1]);
652         else {
653           auto BBDomNode = DT->getNode(*BB);
654           auto BBIDom = BBDomNode->getIDom();
655           BasicBlock *OriginalBBIDom = BBIDom->getBlock();
656           DT->addNewBlock(
657               New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
658         }
659       }
660     }
661 
662     // Remap all instructions in the most recent iteration
663     remapInstructionsInBlocks(NewBlocks, LastValueMap);
664     for (BasicBlock *NewBlock : NewBlocks) {
665       for (Instruction &I : *NewBlock) {
666         if (auto *II = dyn_cast<IntrinsicInst>(&I))
667           if (II->getIntrinsicID() == Intrinsic::assume)
668             AC->registerAssumption(II);
669       }
670     }
671   }
672 
673   // Loop over the PHI nodes in the original block, setting incoming values.
674   for (PHINode *PN : OrigPHINode) {
675     if (CompletelyUnroll) {
676       PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
677       Header->getInstList().erase(PN);
678     } else if (ULO.Count > 1) {
679       Value *InVal = PN->removeIncomingValue(LatchBlock, false);
680       // If this value was defined in the loop, take the value defined by the
681       // last iteration of the loop.
682       if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
683         if (L->contains(InValI))
684           InVal = LastValueMap[InVal];
685       }
686       assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
687       PN->addIncoming(InVal, Latches.back());
688     }
689   }
690 
691   auto setDest = [](BasicBlock *Src, BasicBlock *Dest, BasicBlock *BlockInLoop,
692                     bool NeedConditional, bool ContinueOnTrue,
693                     bool IsDestLoopExit) {
694     auto *Term = cast<BranchInst>(Src->getTerminator());
695     if (NeedConditional) {
696       // Update the conditional branch's successor for the following
697       // iteration.
698       Term->setSuccessor(!ContinueOnTrue, Dest);
699     } else {
700       // Remove phi operands at this loop exit
701       if (!IsDestLoopExit) {
702         BasicBlock *BB = Src;
703         for (BasicBlock *Succ : successors(BB)) {
704           // Preserve the incoming value from BB if we are jumping to the block
705           // in the current loop.
706           if (Succ == BlockInLoop)
707             continue;
708           for (PHINode &Phi : Succ->phis())
709             Phi.removeIncomingValue(BB, false);
710         }
711       }
712       // Replace the conditional branch with an unconditional one.
713       BranchInst::Create(Dest, Term);
714       Term->eraseFromParent();
715     }
716   };
717 
718   // Connect latches of the unrolled iterations to the headers of the next
719   // iteration. If the latch is also the exiting block, the conditional branch
720   // may have to be preserved.
721   for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
722     // The branch destination.
723     unsigned j = (i + 1) % e;
724     BasicBlock *Dest = Headers[j];
725     bool NeedConditional = LatchIsExiting;
726 
727     if (LatchIsExiting) {
728       if (RuntimeTripCount && j != 0)
729         NeedConditional = false;
730 
731       // For a complete unroll, make the last iteration end with a branch
732       // to the exit block.
733       if (CompletelyUnroll) {
734         if (j == 0)
735           Dest = LoopExit;
736         // If using trip count upper bound to completely unroll, we need to
737         // keep the conditional branch except the last one because the loop
738         // may exit after any iteration.
739         assert(NeedConditional &&
740                "NeedCondition cannot be modified by both complete "
741                "unrolling and runtime unrolling");
742         NeedConditional =
743             (ULO.PreserveCondBr && j && !(ULO.PreserveOnlyFirst && i != 0));
744       } else if (j != BreakoutTrip &&
745                  (ULO.TripMultiple == 0 || j % ULO.TripMultiple != 0)) {
746         // If we know the trip count or a multiple of it, we can safely use an
747         // unconditional branch for some iterations.
748         NeedConditional = false;
749       }
750     }
751 
752     setDest(Latches[i], Dest, Headers[i], NeedConditional, ContinueOnTrue,
753             Dest == LoopExit);
754   }
755 
756   if (!LatchIsExiting) {
757     // If the latch is not exiting, we may be able to simplify the conditional
758     // branches in the unrolled exiting blocks.
759     for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
760       // The branch destination.
761       unsigned j = (i + 1) % e;
762       bool NeedConditional = true;
763 
764       if (RuntimeTripCount && j != 0)
765         NeedConditional = false;
766 
767       if (CompletelyUnroll)
768         // We cannot drop the conditional branch for the last condition, as we
769         // may have to execute the loop body depending on the condition.
770         NeedConditional = j == 0 || ULO.PreserveCondBr;
771       else if (j != BreakoutTrip &&
772                (ULO.TripMultiple == 0 || j % ULO.TripMultiple != 0))
773         // If we know the trip count or a multiple of it, we can safely use an
774         // unconditional branch for some iterations.
775         NeedConditional = false;
776 
777       // Conditional branches from non-latch exiting block have successors
778       // either in the same loop iteration or outside the loop. The branches are
779       // already correct.
780       if (NeedConditional)
781         continue;
782       setDest(ExitingBlocks[i], ExitingSucc[i], ExitingSucc[i], NeedConditional,
783               ContinueOnTrue, false);
784     }
785 
786     // When completely unrolling, the last latch becomes unreachable.
787     if (CompletelyUnroll) {
788       BranchInst *Term = cast<BranchInst>(Latches.back()->getTerminator());
789       new UnreachableInst(Term->getContext(), Term);
790       Term->eraseFromParent();
791     }
792   }
793 
794   // Update dominators of blocks we might reach through exits.
795   // Immediate dominator of such block might change, because we add more
796   // routes which can lead to the exit: we can now reach it from the copied
797   // iterations too.
798   if (DT && ULO.Count > 1) {
799     for (auto *BB : OriginalLoopBlocks) {
800       auto *BBDomNode = DT->getNode(BB);
801       SmallVector<BasicBlock *, 16> ChildrenToUpdate;
802       for (auto *ChildDomNode : BBDomNode->getChildren()) {
803         auto *ChildBB = ChildDomNode->getBlock();
804         if (!L->contains(ChildBB))
805           ChildrenToUpdate.push_back(ChildBB);
806       }
807       BasicBlock *NewIDom;
808       BasicBlock *&TermBlock = ExitingBlocks[0];
809       auto &TermBlocks = ExitingBlocks;
810       if (BB == TermBlock) {
811         // The latch is special because we emit unconditional branches in
812         // some cases where the original loop contained a conditional branch.
813         // Since the latch is always at the bottom of the loop, if the latch
814         // dominated an exit before unrolling, the new dominator of that exit
815         // must also be a latch.  Specifically, the dominator is the first
816         // latch which ends in a conditional branch, or the last latch if
817         // there is no such latch.
818         // For loops exiting from non latch exiting block, we limit the
819         // supported loops to have a single exiting block.
820         NewIDom = TermBlocks.back();
821         for (unsigned i = 0, e = TermBlocks.size(); i != e; ++i) {
822           Instruction *Term = TermBlocks[i]->getTerminator();
823           if (isa<BranchInst>(Term) && cast<BranchInst>(Term)->isConditional()) {
824             NewIDom = DT->findNearestCommonDominator(TermBlocks[i], Latches[i]);
825             break;
826           }
827         }
828       } else {
829         // The new idom of the block will be the nearest common dominator
830         // of all copies of the previous idom. This is equivalent to the
831         // nearest common dominator of the previous idom and the first latch,
832         // which dominates all copies of the previous idom.
833         NewIDom = DT->findNearestCommonDominator(BB, LatchBlock);
834       }
835       for (auto *ChildBB : ChildrenToUpdate)
836         DT->changeImmediateDominator(ChildBB, NewIDom);
837     }
838   }
839 
840   assert(!DT || !UnrollVerifyDomtree ||
841          DT->verify(DominatorTree::VerificationLevel::Fast));
842 
843   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
844   // Merge adjacent basic blocks, if possible.
845   for (BasicBlock *Latch : Latches) {
846     BranchInst *Term = dyn_cast<BranchInst>(Latch->getTerminator());
847     assert((Term ||
848             (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
849            "Need a branch as terminator, except when fully unrolling with "
850            "unconditional latch");
851     if (Term && Term->isUnconditional()) {
852       BasicBlock *Dest = Term->getSuccessor(0);
853       BasicBlock *Fold = Dest->getUniquePredecessor();
854       if (MergeBlockIntoPredecessor(Dest, &DTU, LI)) {
855         // Dest has been folded into Fold. Update our worklists accordingly.
856         std::replace(Latches.begin(), Latches.end(), Dest, Fold);
857         UnrolledLoopBlocks.erase(std::remove(UnrolledLoopBlocks.begin(),
858                                              UnrolledLoopBlocks.end(), Dest),
859                                  UnrolledLoopBlocks.end());
860       }
861     }
862   }
863   // Apply updates to the DomTree.
864   DT = &DTU.getDomTree();
865 
866   // At this point, the code is well formed.  We now simplify the unrolled loop,
867   // doing constant propagation and dead code elimination as we go.
868   simplifyLoopAfterUnroll(L, !CompletelyUnroll && (ULO.Count > 1 || Peeled), LI,
869                           SE, DT, AC, TTI);
870 
871   NumCompletelyUnrolled += CompletelyUnroll;
872   ++NumUnrolled;
873 
874   Loop *OuterL = L->getParentLoop();
875   // Update LoopInfo if the loop is completely removed.
876   if (CompletelyUnroll)
877     LI->erase(L);
878 
879   // After complete unrolling most of the blocks should be contained in OuterL.
880   // However, some of them might happen to be out of OuterL (e.g. if they
881   // precede a loop exit). In this case we might need to insert PHI nodes in
882   // order to preserve LCSSA form.
883   // We don't need to check this if we already know that we need to fix LCSSA
884   // form.
885   // TODO: For now we just recompute LCSSA for the outer loop in this case, but
886   // it should be possible to fix it in-place.
887   if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
888     NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
889 
890   // If we have a pass and a DominatorTree we should re-simplify impacted loops
891   // to ensure subsequent analyses can rely on this form. We want to simplify
892   // at least one layer outside of the loop that was unrolled so that any
893   // changes to the parent loop exposed by the unrolling are considered.
894   if (DT) {
895     if (OuterL) {
896       // OuterL includes all loops for which we can break loop-simplify, so
897       // it's sufficient to simplify only it (it'll recursively simplify inner
898       // loops too).
899       if (NeedToFixLCSSA) {
900         // LCSSA must be performed on the outermost affected loop. The unrolled
901         // loop's last loop latch is guaranteed to be in the outermost loop
902         // after LoopInfo's been updated by LoopInfo::erase.
903         Loop *LatchLoop = LI->getLoopFor(Latches.back());
904         Loop *FixLCSSALoop = OuterL;
905         if (!FixLCSSALoop->contains(LatchLoop))
906           while (FixLCSSALoop->getParentLoop() != LatchLoop)
907             FixLCSSALoop = FixLCSSALoop->getParentLoop();
908 
909         formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE);
910       } else if (PreserveLCSSA) {
911         assert(OuterL->isLCSSAForm(*DT) &&
912                "Loops should be in LCSSA form after loop-unroll.");
913       }
914 
915       // TODO: That potentially might be compile-time expensive. We should try
916       // to fix the loop-simplified form incrementally.
917       simplifyLoop(OuterL, DT, LI, SE, AC, nullptr, PreserveLCSSA);
918     } else {
919       // Simplify loops for which we might've broken loop-simplify form.
920       for (Loop *SubLoop : LoopsToSimplify)
921         simplifyLoop(SubLoop, DT, LI, SE, AC, nullptr, PreserveLCSSA);
922     }
923   }
924 
925   return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
926                           : LoopUnrollResult::PartiallyUnrolled;
927 }
928 
929 /// Given an llvm.loop loop id metadata node, returns the loop hint metadata
930 /// node with the given name (for example, "llvm.loop.unroll.count"). If no
931 /// such metadata node exists, then nullptr is returned.
932 MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
933   // First operand should refer to the loop id itself.
934   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
935   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
936 
937   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
938     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
939     if (!MD)
940       continue;
941 
942     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
943     if (!S)
944       continue;
945 
946     if (Name.equals(S->getString()))
947       return MD;
948   }
949   return nullptr;
950 }
951