xref: /llvm-project/llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp (revision 3567d3d2ecad91a135de45841f130a480d722006)
1 //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass implements a simple loop unroller.  It works best when loops have
11 // been canonicalized by the -indvars pass, allowing it to determine the trip
12 // counts of loops easily.
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/Analysis/AssumptionCache.h"
18 #include "llvm/Analysis/CodeMetrics.h"
19 #include "llvm/Analysis/GlobalsModRef.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/Analysis/LoopUnrollAnalyzer.h"
23 #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
24 #include "llvm/Analysis/ProfileSummaryInfo.h"
25 #include "llvm/Analysis/ScalarEvolution.h"
26 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/InstVisitor.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Metadata.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Transforms/Scalar.h"
36 #include "llvm/Transforms/Scalar/LoopPassManager.h"
37 #include "llvm/Transforms/Utils/LoopUtils.h"
38 #include "llvm/Transforms/Utils/UnrollLoop.h"
39 #include <climits>
40 #include <utility>
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "loop-unroll"
45 
46 static cl::opt<unsigned>
47     UnrollThreshold("unroll-threshold", cl::Hidden,
48                     cl::desc("The cost threshold for loop unrolling"));
49 
50 static cl::opt<unsigned> UnrollPartialThreshold(
51     "unroll-partial-threshold", cl::Hidden,
52     cl::desc("The cost threshold for partial loop unrolling"));
53 
54 static cl::opt<unsigned> UnrollMaxPercentThresholdBoost(
55     "unroll-max-percent-threshold-boost", cl::init(400), cl::Hidden,
56     cl::desc("The maximum 'boost' (represented as a percentage >= 100) applied "
57              "to the threshold when aggressively unrolling a loop due to the "
58              "dynamic cost savings. If completely unrolling a loop will reduce "
59              "the total runtime from X to Y, we boost the loop unroll "
60              "threshold to DefaultThreshold*std::min(MaxPercentThresholdBoost, "
61              "X/Y). This limit avoids excessive code bloat."));
62 
63 static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
64     "unroll-max-iteration-count-to-analyze", cl::init(10), cl::Hidden,
65     cl::desc("Don't allow loop unrolling to simulate more than this number of"
66              "iterations when checking full unroll profitability"));
67 
68 static cl::opt<unsigned> UnrollCount(
69     "unroll-count", cl::Hidden,
70     cl::desc("Use this unroll count for all loops including those with "
71              "unroll_count pragma values, for testing purposes"));
72 
73 static cl::opt<unsigned> UnrollMaxCount(
74     "unroll-max-count", cl::Hidden,
75     cl::desc("Set the max unroll count for partial and runtime unrolling, for"
76              "testing purposes"));
77 
78 static cl::opt<unsigned> UnrollFullMaxCount(
79     "unroll-full-max-count", cl::Hidden,
80     cl::desc(
81         "Set the max unroll count for full unrolling, for testing purposes"));
82 
83 static cl::opt<unsigned> UnrollPeelCount(
84     "unroll-peel-count", cl::Hidden,
85     cl::desc("Set the unroll peeling count, for testing purposes"));
86 
87 static cl::opt<bool>
88     UnrollAllowPartial("unroll-allow-partial", cl::Hidden,
89                        cl::desc("Allows loops to be partially unrolled until "
90                                 "-unroll-threshold loop size is reached."));
91 
92 static cl::opt<bool> UnrollAllowRemainder(
93     "unroll-allow-remainder", cl::Hidden,
94     cl::desc("Allow generation of a loop remainder (extra iterations) "
95              "when unrolling a loop."));
96 
97 static cl::opt<bool>
98     UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::Hidden,
99                   cl::desc("Unroll loops with run-time trip counts"));
100 
101 static cl::opt<unsigned> UnrollMaxUpperBound(
102     "unroll-max-upperbound", cl::init(8), cl::Hidden,
103     cl::desc(
104         "The max of trip count upper bound that is considered in unrolling"));
105 
106 static cl::opt<unsigned> PragmaUnrollThreshold(
107     "pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
108     cl::desc("Unrolled size limit for loops with an unroll(full) or "
109              "unroll_count pragma."));
110 
111 static cl::opt<unsigned> FlatLoopTripCountThreshold(
112     "flat-loop-tripcount-threshold", cl::init(5), cl::Hidden,
113     cl::desc("If the runtime tripcount for the loop is lower than the "
114              "threshold, the loop is considered as flat and will be less "
115              "aggressively unrolled."));
116 
117 static cl::opt<bool>
118     UnrollAllowPeeling("unroll-allow-peeling", cl::init(true), cl::Hidden,
119                        cl::desc("Allows loops to be peeled when the dynamic "
120                                 "trip count is known to be low."));
121 
122 static cl::opt<bool> UnrollUnrollRemainder(
123   "unroll-remainder", cl::Hidden,
124   cl::desc("Allow the loop remainder to be unrolled."));
125 
126 // This option isn't ever intended to be enabled, it serves to allow
127 // experiments to check the assumptions about when this kind of revisit is
128 // necessary.
129 static cl::opt<bool> UnrollRevisitChildLoops(
130     "unroll-revisit-child-loops", cl::Hidden,
131     cl::desc("Enqueue and re-visit child loops in the loop PM after unrolling. "
132              "This shouldn't typically be needed as child loops (or their "
133              "clones) were already visited."));
134 
135 /// A magic value for use with the Threshold parameter to indicate
136 /// that the loop unroll should be performed regardless of how much
137 /// code expansion would result.
138 static const unsigned NoThreshold = UINT_MAX;
139 
140 /// Gather the various unrolling parameters based on the defaults, compiler
141 /// flags, TTI overrides and user specified parameters.
142 static TargetTransformInfo::UnrollingPreferences gatherUnrollingPreferences(
143     Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, int OptLevel,
144     Optional<unsigned> UserThreshold, Optional<unsigned> UserCount,
145     Optional<bool> UserAllowPartial, Optional<bool> UserRuntime,
146     Optional<bool> UserUpperBound, Optional<bool> UserAllowPeeling) {
147   TargetTransformInfo::UnrollingPreferences UP;
148 
149   // Set up the defaults
150   UP.Threshold = OptLevel > 2 ? 300 : 150;
151   UP.MaxPercentThresholdBoost = 400;
152   UP.OptSizeThreshold = 0;
153   UP.PartialThreshold = 150;
154   UP.PartialOptSizeThreshold = 0;
155   UP.Count = 0;
156   UP.PeelCount = 0;
157   UP.DefaultUnrollRuntimeCount = 8;
158   UP.MaxCount = UINT_MAX;
159   UP.FullUnrollMaxCount = UINT_MAX;
160   UP.BEInsns = 2;
161   UP.Partial = false;
162   UP.Runtime = false;
163   UP.AllowRemainder = true;
164   UP.UnrollRemainder = false;
165   UP.AllowExpensiveTripCount = false;
166   UP.Force = false;
167   UP.UpperBound = false;
168   UP.AllowPeeling = true;
169 
170   // Override with any target specific settings
171   TTI.getUnrollingPreferences(L, SE, UP);
172 
173   // Apply size attributes
174   if (L->getHeader()->getParent()->optForSize()) {
175     UP.Threshold = UP.OptSizeThreshold;
176     UP.PartialThreshold = UP.PartialOptSizeThreshold;
177   }
178 
179   // Apply any user values specified by cl::opt
180   if (UnrollThreshold.getNumOccurrences() > 0)
181     UP.Threshold = UnrollThreshold;
182   if (UnrollPartialThreshold.getNumOccurrences() > 0)
183     UP.PartialThreshold = UnrollPartialThreshold;
184   if (UnrollMaxPercentThresholdBoost.getNumOccurrences() > 0)
185     UP.MaxPercentThresholdBoost = UnrollMaxPercentThresholdBoost;
186   if (UnrollMaxCount.getNumOccurrences() > 0)
187     UP.MaxCount = UnrollMaxCount;
188   if (UnrollFullMaxCount.getNumOccurrences() > 0)
189     UP.FullUnrollMaxCount = UnrollFullMaxCount;
190   if (UnrollPeelCount.getNumOccurrences() > 0)
191     UP.PeelCount = UnrollPeelCount;
192   if (UnrollAllowPartial.getNumOccurrences() > 0)
193     UP.Partial = UnrollAllowPartial;
194   if (UnrollAllowRemainder.getNumOccurrences() > 0)
195     UP.AllowRemainder = UnrollAllowRemainder;
196   if (UnrollRuntime.getNumOccurrences() > 0)
197     UP.Runtime = UnrollRuntime;
198   if (UnrollMaxUpperBound == 0)
199     UP.UpperBound = false;
200   if (UnrollAllowPeeling.getNumOccurrences() > 0)
201     UP.AllowPeeling = UnrollAllowPeeling;
202   if (UnrollUnrollRemainder.getNumOccurrences() > 0)
203     UP.UnrollRemainder = UnrollUnrollRemainder;
204 
205   // Apply user values provided by argument
206   if (UserThreshold.hasValue()) {
207     UP.Threshold = *UserThreshold;
208     UP.PartialThreshold = *UserThreshold;
209   }
210   if (UserCount.hasValue())
211     UP.Count = *UserCount;
212   if (UserAllowPartial.hasValue())
213     UP.Partial = *UserAllowPartial;
214   if (UserRuntime.hasValue())
215     UP.Runtime = *UserRuntime;
216   if (UserUpperBound.hasValue())
217     UP.UpperBound = *UserUpperBound;
218   if (UserAllowPeeling.hasValue())
219     UP.AllowPeeling = *UserAllowPeeling;
220 
221   return UP;
222 }
223 
224 namespace {
225 /// A struct to densely store the state of an instruction after unrolling at
226 /// each iteration.
227 ///
228 /// This is designed to work like a tuple of <Instruction *, int> for the
229 /// purposes of hashing and lookup, but to be able to associate two boolean
230 /// states with each key.
231 struct UnrolledInstState {
232   Instruction *I;
233   int Iteration : 30;
234   unsigned IsFree : 1;
235   unsigned IsCounted : 1;
236 };
237 
238 /// Hashing and equality testing for a set of the instruction states.
239 struct UnrolledInstStateKeyInfo {
240   typedef DenseMapInfo<Instruction *> PtrInfo;
241   typedef DenseMapInfo<std::pair<Instruction *, int>> PairInfo;
242   static inline UnrolledInstState getEmptyKey() {
243     return {PtrInfo::getEmptyKey(), 0, 0, 0};
244   }
245   static inline UnrolledInstState getTombstoneKey() {
246     return {PtrInfo::getTombstoneKey(), 0, 0, 0};
247   }
248   static inline unsigned getHashValue(const UnrolledInstState &S) {
249     return PairInfo::getHashValue({S.I, S.Iteration});
250   }
251   static inline bool isEqual(const UnrolledInstState &LHS,
252                              const UnrolledInstState &RHS) {
253     return PairInfo::isEqual({LHS.I, LHS.Iteration}, {RHS.I, RHS.Iteration});
254   }
255 };
256 }
257 
258 namespace {
259 struct EstimatedUnrollCost {
260   /// \brief The estimated cost after unrolling.
261   unsigned UnrolledCost;
262 
263   /// \brief The estimated dynamic cost of executing the instructions in the
264   /// rolled form.
265   unsigned RolledDynamicCost;
266 };
267 }
268 
269 /// \brief Figure out if the loop is worth full unrolling.
270 ///
271 /// Complete loop unrolling can make some loads constant, and we need to know
272 /// if that would expose any further optimization opportunities.  This routine
273 /// estimates this optimization.  It computes cost of unrolled loop
274 /// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By
275 /// dynamic cost we mean that we won't count costs of blocks that are known not
276 /// to be executed (i.e. if we have a branch in the loop and we know that at the
277 /// given iteration its condition would be resolved to true, we won't add up the
278 /// cost of the 'false'-block).
279 /// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If
280 /// the analysis failed (no benefits expected from the unrolling, or the loop is
281 /// too big to analyze), the returned value is None.
282 static Optional<EstimatedUnrollCost>
283 analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, DominatorTree &DT,
284                       ScalarEvolution &SE, const TargetTransformInfo &TTI,
285                       unsigned MaxUnrolledLoopSize) {
286   // We want to be able to scale offsets by the trip count and add more offsets
287   // to them without checking for overflows, and we already don't want to
288   // analyze *massive* trip counts, so we force the max to be reasonably small.
289   assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) &&
290          "The unroll iterations max is too large!");
291 
292   // Only analyze inner loops. We can't properly estimate cost of nested loops
293   // and we won't visit inner loops again anyway.
294   if (!L->empty())
295     return None;
296 
297   // Don't simulate loops with a big or unknown tripcount
298   if (!UnrollMaxIterationsCountToAnalyze || !TripCount ||
299       TripCount > UnrollMaxIterationsCountToAnalyze)
300     return None;
301 
302   SmallSetVector<BasicBlock *, 16> BBWorklist;
303   SmallSetVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitWorklist;
304   DenseMap<Value *, Constant *> SimplifiedValues;
305   SmallVector<std::pair<Value *, Constant *>, 4> SimplifiedInputValues;
306 
307   // The estimated cost of the unrolled form of the loop. We try to estimate
308   // this by simplifying as much as we can while computing the estimate.
309   unsigned UnrolledCost = 0;
310 
311   // We also track the estimated dynamic (that is, actually executed) cost in
312   // the rolled form. This helps identify cases when the savings from unrolling
313   // aren't just exposing dead control flows, but actual reduced dynamic
314   // instructions due to the simplifications which we expect to occur after
315   // unrolling.
316   unsigned RolledDynamicCost = 0;
317 
318   // We track the simplification of each instruction in each iteration. We use
319   // this to recursively merge costs into the unrolled cost on-demand so that
320   // we don't count the cost of any dead code. This is essentially a map from
321   // <instruction, int> to <bool, bool>, but stored as a densely packed struct.
322   DenseSet<UnrolledInstState, UnrolledInstStateKeyInfo> InstCostMap;
323 
324   // A small worklist used to accumulate cost of instructions from each
325   // observable and reached root in the loop.
326   SmallVector<Instruction *, 16> CostWorklist;
327 
328   // PHI-used worklist used between iterations while accumulating cost.
329   SmallVector<Instruction *, 4> PHIUsedList;
330 
331   // Helper function to accumulate cost for instructions in the loop.
332   auto AddCostRecursively = [&](Instruction &RootI, int Iteration) {
333     assert(Iteration >= 0 && "Cannot have a negative iteration!");
334     assert(CostWorklist.empty() && "Must start with an empty cost list");
335     assert(PHIUsedList.empty() && "Must start with an empty phi used list");
336     CostWorklist.push_back(&RootI);
337     for (;; --Iteration) {
338       do {
339         Instruction *I = CostWorklist.pop_back_val();
340 
341         // InstCostMap only uses I and Iteration as a key, the other two values
342         // don't matter here.
343         auto CostIter = InstCostMap.find({I, Iteration, 0, 0});
344         if (CostIter == InstCostMap.end())
345           // If an input to a PHI node comes from a dead path through the loop
346           // we may have no cost data for it here. What that actually means is
347           // that it is free.
348           continue;
349         auto &Cost = *CostIter;
350         if (Cost.IsCounted)
351           // Already counted this instruction.
352           continue;
353 
354         // Mark that we are counting the cost of this instruction now.
355         Cost.IsCounted = true;
356 
357         // If this is a PHI node in the loop header, just add it to the PHI set.
358         if (auto *PhiI = dyn_cast<PHINode>(I))
359           if (PhiI->getParent() == L->getHeader()) {
360             assert(Cost.IsFree && "Loop PHIs shouldn't be evaluated as they "
361                                   "inherently simplify during unrolling.");
362             if (Iteration == 0)
363               continue;
364 
365             // Push the incoming value from the backedge into the PHI used list
366             // if it is an in-loop instruction. We'll use this to populate the
367             // cost worklist for the next iteration (as we count backwards).
368             if (auto *OpI = dyn_cast<Instruction>(
369                     PhiI->getIncomingValueForBlock(L->getLoopLatch())))
370               if (L->contains(OpI))
371                 PHIUsedList.push_back(OpI);
372             continue;
373           }
374 
375         // First accumulate the cost of this instruction.
376         if (!Cost.IsFree) {
377           UnrolledCost += TTI.getUserCost(I);
378           DEBUG(dbgs() << "Adding cost of instruction (iteration " << Iteration
379                        << "): ");
380           DEBUG(I->dump());
381         }
382 
383         // We must count the cost of every operand which is not free,
384         // recursively. If we reach a loop PHI node, simply add it to the set
385         // to be considered on the next iteration (backwards!).
386         for (Value *Op : I->operands()) {
387           // Check whether this operand is free due to being a constant or
388           // outside the loop.
389           auto *OpI = dyn_cast<Instruction>(Op);
390           if (!OpI || !L->contains(OpI))
391             continue;
392 
393           // Otherwise accumulate its cost.
394           CostWorklist.push_back(OpI);
395         }
396       } while (!CostWorklist.empty());
397 
398       if (PHIUsedList.empty())
399         // We've exhausted the search.
400         break;
401 
402       assert(Iteration > 0 &&
403              "Cannot track PHI-used values past the first iteration!");
404       CostWorklist.append(PHIUsedList.begin(), PHIUsedList.end());
405       PHIUsedList.clear();
406     }
407   };
408 
409   // Ensure that we don't violate the loop structure invariants relied on by
410   // this analysis.
411   assert(L->isLoopSimplifyForm() && "Must put loop into normal form first.");
412   assert(L->isLCSSAForm(DT) &&
413          "Must have loops in LCSSA form to track live-out values.");
414 
415   DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n");
416 
417   // Simulate execution of each iteration of the loop counting instructions,
418   // which would be simplified.
419   // Since the same load will take different values on different iterations,
420   // we literally have to go through all loop's iterations.
421   for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
422     DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n");
423 
424     // Prepare for the iteration by collecting any simplified entry or backedge
425     // inputs.
426     for (Instruction &I : *L->getHeader()) {
427       auto *PHI = dyn_cast<PHINode>(&I);
428       if (!PHI)
429         break;
430 
431       // The loop header PHI nodes must have exactly two input: one from the
432       // loop preheader and one from the loop latch.
433       assert(
434           PHI->getNumIncomingValues() == 2 &&
435           "Must have an incoming value only for the preheader and the latch.");
436 
437       Value *V = PHI->getIncomingValueForBlock(
438           Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch());
439       Constant *C = dyn_cast<Constant>(V);
440       if (Iteration != 0 && !C)
441         C = SimplifiedValues.lookup(V);
442       if (C)
443         SimplifiedInputValues.push_back({PHI, C});
444     }
445 
446     // Now clear and re-populate the map for the next iteration.
447     SimplifiedValues.clear();
448     while (!SimplifiedInputValues.empty())
449       SimplifiedValues.insert(SimplifiedInputValues.pop_back_val());
450 
451     UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SE, L);
452 
453     BBWorklist.clear();
454     BBWorklist.insert(L->getHeader());
455     // Note that we *must not* cache the size, this loop grows the worklist.
456     for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
457       BasicBlock *BB = BBWorklist[Idx];
458 
459       // Visit all instructions in the given basic block and try to simplify
460       // it.  We don't change the actual IR, just count optimization
461       // opportunities.
462       for (Instruction &I : *BB) {
463         if (isa<DbgInfoIntrinsic>(I))
464           continue;
465 
466         // Track this instruction's expected baseline cost when executing the
467         // rolled loop form.
468         RolledDynamicCost += TTI.getUserCost(&I);
469 
470         // Visit the instruction to analyze its loop cost after unrolling,
471         // and if the visitor returns true, mark the instruction as free after
472         // unrolling and continue.
473         bool IsFree = Analyzer.visit(I);
474         bool Inserted = InstCostMap.insert({&I, (int)Iteration,
475                                            (unsigned)IsFree,
476                                            /*IsCounted*/ false}).second;
477         (void)Inserted;
478         assert(Inserted && "Cannot have a state for an unvisited instruction!");
479 
480         if (IsFree)
481           continue;
482 
483         // Can't properly model a cost of a call.
484         // FIXME: With a proper cost model we should be able to do it.
485         if(isa<CallInst>(&I))
486           return None;
487 
488         // If the instruction might have a side-effect recursively account for
489         // the cost of it and all the instructions leading up to it.
490         if (I.mayHaveSideEffects())
491           AddCostRecursively(I, Iteration);
492 
493         // If unrolled body turns out to be too big, bail out.
494         if (UnrolledCost > MaxUnrolledLoopSize) {
495           DEBUG(dbgs() << "  Exceeded threshold.. exiting.\n"
496                        << "  UnrolledCost: " << UnrolledCost
497                        << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize
498                        << "\n");
499           return None;
500         }
501       }
502 
503       TerminatorInst *TI = BB->getTerminator();
504 
505       // Add in the live successors by first checking whether we have terminator
506       // that may be simplified based on the values simplified by this call.
507       BasicBlock *KnownSucc = nullptr;
508       if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
509         if (BI->isConditional()) {
510           if (Constant *SimpleCond =
511                   SimplifiedValues.lookup(BI->getCondition())) {
512             // Just take the first successor if condition is undef
513             if (isa<UndefValue>(SimpleCond))
514               KnownSucc = BI->getSuccessor(0);
515             else if (ConstantInt *SimpleCondVal =
516                          dyn_cast<ConstantInt>(SimpleCond))
517               KnownSucc = BI->getSuccessor(SimpleCondVal->isZero() ? 1 : 0);
518           }
519         }
520       } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
521         if (Constant *SimpleCond =
522                 SimplifiedValues.lookup(SI->getCondition())) {
523           // Just take the first successor if condition is undef
524           if (isa<UndefValue>(SimpleCond))
525             KnownSucc = SI->getSuccessor(0);
526           else if (ConstantInt *SimpleCondVal =
527                        dyn_cast<ConstantInt>(SimpleCond))
528             KnownSucc = SI->findCaseValue(SimpleCondVal)->getCaseSuccessor();
529         }
530       }
531       if (KnownSucc) {
532         if (L->contains(KnownSucc))
533           BBWorklist.insert(KnownSucc);
534         else
535           ExitWorklist.insert({BB, KnownSucc});
536         continue;
537       }
538 
539       // Add BB's successors to the worklist.
540       for (BasicBlock *Succ : successors(BB))
541         if (L->contains(Succ))
542           BBWorklist.insert(Succ);
543         else
544           ExitWorklist.insert({BB, Succ});
545       AddCostRecursively(*TI, Iteration);
546     }
547 
548     // If we found no optimization opportunities on the first iteration, we
549     // won't find them on later ones too.
550     if (UnrolledCost == RolledDynamicCost) {
551       DEBUG(dbgs() << "  No opportunities found.. exiting.\n"
552                    << "  UnrolledCost: " << UnrolledCost << "\n");
553       return None;
554     }
555   }
556 
557   while (!ExitWorklist.empty()) {
558     BasicBlock *ExitingBB, *ExitBB;
559     std::tie(ExitingBB, ExitBB) = ExitWorklist.pop_back_val();
560 
561     for (Instruction &I : *ExitBB) {
562       auto *PN = dyn_cast<PHINode>(&I);
563       if (!PN)
564         break;
565 
566       Value *Op = PN->getIncomingValueForBlock(ExitingBB);
567       if (auto *OpI = dyn_cast<Instruction>(Op))
568         if (L->contains(OpI))
569           AddCostRecursively(*OpI, TripCount - 1);
570     }
571   }
572 
573   DEBUG(dbgs() << "Analysis finished:\n"
574                << "UnrolledCost: " << UnrolledCost << ", "
575                << "RolledDynamicCost: " << RolledDynamicCost << "\n");
576   return {{UnrolledCost, RolledDynamicCost}};
577 }
578 
579 /// ApproximateLoopSize - Approximate the size of the loop.
580 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
581                                     bool &NotDuplicatable, bool &Convergent,
582                                     const TargetTransformInfo &TTI,
583                                     AssumptionCache *AC, unsigned BEInsns) {
584   SmallPtrSet<const Value *, 32> EphValues;
585   CodeMetrics::collectEphemeralValues(L, AC, EphValues);
586 
587   CodeMetrics Metrics;
588   for (BasicBlock *BB : L->blocks())
589     Metrics.analyzeBasicBlock(BB, TTI, EphValues);
590   NumCalls = Metrics.NumInlineCandidates;
591   NotDuplicatable = Metrics.notDuplicatable;
592   Convergent = Metrics.convergent;
593 
594   unsigned LoopSize = Metrics.NumInsts;
595 
596   // Don't allow an estimate of size zero.  This would allows unrolling of loops
597   // with huge iteration counts, which is a compile time problem even if it's
598   // not a problem for code quality. Also, the code using this size may assume
599   // that each loop has at least three instructions (likely a conditional
600   // branch, a comparison feeding that branch, and some kind of loop increment
601   // feeding that comparison instruction).
602   LoopSize = std::max(LoopSize, BEInsns + 1);
603 
604   return LoopSize;
605 }
606 
607 // Returns the loop hint metadata node with the given name (for example,
608 // "llvm.loop.unroll.count").  If no such metadata node exists, then nullptr is
609 // returned.
610 static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
611   if (MDNode *LoopID = L->getLoopID())
612     return GetUnrollMetadata(LoopID, Name);
613   return nullptr;
614 }
615 
616 // Returns true if the loop has an unroll(full) pragma.
617 static bool HasUnrollFullPragma(const Loop *L) {
618   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
619 }
620 
621 // Returns true if the loop has an unroll(enable) pragma. This metadata is used
622 // for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives.
623 static bool HasUnrollEnablePragma(const Loop *L) {
624   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.enable");
625 }
626 
627 // Returns true if the loop has an unroll(disable) pragma.
628 static bool HasUnrollDisablePragma(const Loop *L) {
629   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
630 }
631 
632 // Returns true if the loop has an runtime unroll(disable) pragma.
633 static bool HasRuntimeUnrollDisablePragma(const Loop *L) {
634   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
635 }
636 
637 // If loop has an unroll_count pragma return the (necessarily
638 // positive) value from the pragma.  Otherwise return 0.
639 static unsigned UnrollCountPragmaValue(const Loop *L) {
640   MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
641   if (MD) {
642     assert(MD->getNumOperands() == 2 &&
643            "Unroll count hint metadata should have two operands.");
644     unsigned Count =
645         mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
646     assert(Count >= 1 && "Unroll count must be positive.");
647     return Count;
648   }
649   return 0;
650 }
651 
652 // Remove existing unroll metadata and add unroll disable metadata to
653 // indicate the loop has already been unrolled.  This prevents a loop
654 // from being unrolled more than is directed by a pragma if the loop
655 // unrolling pass is run more than once (which it generally is).
656 static void SetLoopAlreadyUnrolled(Loop *L) {
657   MDNode *LoopID = L->getLoopID();
658   // First remove any existing loop unrolling metadata.
659   SmallVector<Metadata *, 4> MDs;
660   // Reserve first location for self reference to the LoopID metadata node.
661   MDs.push_back(nullptr);
662 
663   if (LoopID) {
664     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
665       bool IsUnrollMetadata = false;
666       MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
667       if (MD) {
668         const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
669         IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
670       }
671       if (!IsUnrollMetadata)
672         MDs.push_back(LoopID->getOperand(i));
673     }
674   }
675 
676   // Add unroll(disable) metadata to disable future unrolling.
677   LLVMContext &Context = L->getHeader()->getContext();
678   SmallVector<Metadata *, 1> DisableOperands;
679   DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
680   MDNode *DisableNode = MDNode::get(Context, DisableOperands);
681   MDs.push_back(DisableNode);
682 
683   MDNode *NewLoopID = MDNode::get(Context, MDs);
684   // Set operand 0 to refer to the loop id itself.
685   NewLoopID->replaceOperandWith(0, NewLoopID);
686   L->setLoopID(NewLoopID);
687 }
688 
689 // Computes the boosting factor for complete unrolling.
690 // If fully unrolling the loop would save a lot of RolledDynamicCost, it would
691 // be beneficial to fully unroll the loop even if unrolledcost is large. We
692 // use (RolledDynamicCost / UnrolledCost) to model the unroll benefits to adjust
693 // the unroll threshold.
694 static unsigned getFullUnrollBoostingFactor(const EstimatedUnrollCost &Cost,
695                                             unsigned MaxPercentThresholdBoost) {
696   if (Cost.RolledDynamicCost >= UINT_MAX / 100)
697     return 100;
698   else if (Cost.UnrolledCost != 0)
699     // The boosting factor is RolledDynamicCost / UnrolledCost
700     return std::min(100 * Cost.RolledDynamicCost / Cost.UnrolledCost,
701                     MaxPercentThresholdBoost);
702   else
703     return MaxPercentThresholdBoost;
704 }
705 
706 // Returns loop size estimation for unrolled loop.
707 static uint64_t getUnrolledLoopSize(
708     unsigned LoopSize,
709     TargetTransformInfo::UnrollingPreferences &UP) {
710   assert(LoopSize >= UP.BEInsns && "LoopSize should not be less than BEInsns!");
711   return (uint64_t)(LoopSize - UP.BEInsns) * UP.Count + UP.BEInsns;
712 }
713 
714 // Returns true if unroll count was set explicitly.
715 // Calculates unroll count and writes it to UP.Count.
716 static bool computeUnrollCount(
717     Loop *L, const TargetTransformInfo &TTI, DominatorTree &DT, LoopInfo *LI,
718     ScalarEvolution &SE, OptimizationRemarkEmitter *ORE, unsigned &TripCount,
719     unsigned MaxTripCount, unsigned &TripMultiple, unsigned LoopSize,
720     TargetTransformInfo::UnrollingPreferences &UP, bool &UseUpperBound) {
721   // Check for explicit Count.
722   // 1st priority is unroll count set by "unroll-count" option.
723   bool UserUnrollCount = UnrollCount.getNumOccurrences() > 0;
724   if (UserUnrollCount) {
725     UP.Count = UnrollCount;
726     UP.AllowExpensiveTripCount = true;
727     UP.Force = true;
728     if (UP.AllowRemainder && getUnrolledLoopSize(LoopSize, UP) < UP.Threshold)
729       return true;
730   }
731 
732   // 2nd priority is unroll count set by pragma.
733   unsigned PragmaCount = UnrollCountPragmaValue(L);
734   if (PragmaCount > 0) {
735     UP.Count = PragmaCount;
736     UP.Runtime = true;
737     UP.AllowExpensiveTripCount = true;
738     UP.Force = true;
739     if (UP.AllowRemainder &&
740         getUnrolledLoopSize(LoopSize, UP) < PragmaUnrollThreshold)
741       return true;
742   }
743   bool PragmaFullUnroll = HasUnrollFullPragma(L);
744   if (PragmaFullUnroll && TripCount != 0) {
745     UP.Count = TripCount;
746     if (getUnrolledLoopSize(LoopSize, UP) < PragmaUnrollThreshold)
747       return false;
748   }
749 
750   bool PragmaEnableUnroll = HasUnrollEnablePragma(L);
751   bool ExplicitUnroll = PragmaCount > 0 || PragmaFullUnroll ||
752                         PragmaEnableUnroll || UserUnrollCount;
753 
754   if (ExplicitUnroll && TripCount != 0) {
755     // If the loop has an unrolling pragma, we want to be more aggressive with
756     // unrolling limits. Set thresholds to at least the PragmaThreshold value
757     // which is larger than the default limits.
758     UP.Threshold = std::max<unsigned>(UP.Threshold, PragmaUnrollThreshold);
759     UP.PartialThreshold =
760         std::max<unsigned>(UP.PartialThreshold, PragmaUnrollThreshold);
761   }
762 
763   // 3rd priority is full unroll count.
764   // Full unroll makes sense only when TripCount or its upper bound could be
765   // statically calculated.
766   // Also we need to check if we exceed FullUnrollMaxCount.
767   // If using the upper bound to unroll, TripMultiple should be set to 1 because
768   // we do not know when loop may exit.
769   // MaxTripCount and ExactTripCount cannot both be non zero since we only
770   // compute the former when the latter is zero.
771   unsigned ExactTripCount = TripCount;
772   assert((ExactTripCount == 0 || MaxTripCount == 0) &&
773          "ExtractTripCound and MaxTripCount cannot both be non zero.");
774   unsigned FullUnrollTripCount = ExactTripCount ? ExactTripCount : MaxTripCount;
775   UP.Count = FullUnrollTripCount;
776   if (FullUnrollTripCount && FullUnrollTripCount <= UP.FullUnrollMaxCount) {
777     // When computing the unrolled size, note that BEInsns are not replicated
778     // like the rest of the loop body.
779     if (getUnrolledLoopSize(LoopSize, UP) < UP.Threshold) {
780       UseUpperBound = (MaxTripCount == FullUnrollTripCount);
781       TripCount = FullUnrollTripCount;
782       TripMultiple = UP.UpperBound ? 1 : TripMultiple;
783       return ExplicitUnroll;
784     } else {
785       // The loop isn't that small, but we still can fully unroll it if that
786       // helps to remove a significant number of instructions.
787       // To check that, run additional analysis on the loop.
788       if (Optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost(
789               L, FullUnrollTripCount, DT, SE, TTI,
790               UP.Threshold * UP.MaxPercentThresholdBoost / 100)) {
791         unsigned Boost =
792             getFullUnrollBoostingFactor(*Cost, UP.MaxPercentThresholdBoost);
793         if (Cost->UnrolledCost < UP.Threshold * Boost / 100) {
794           UseUpperBound = (MaxTripCount == FullUnrollTripCount);
795           TripCount = FullUnrollTripCount;
796           TripMultiple = UP.UpperBound ? 1 : TripMultiple;
797           return ExplicitUnroll;
798         }
799       }
800     }
801   }
802 
803   // 4th priority is loop peeling
804   computePeelCount(L, LoopSize, UP, TripCount);
805   if (UP.PeelCount) {
806     UP.Runtime = false;
807     UP.Count = 1;
808     return ExplicitUnroll;
809   }
810 
811   // 5th priority is partial unrolling.
812   // Try partial unroll only when TripCount could be staticaly calculated.
813   if (TripCount) {
814     UP.Partial |= ExplicitUnroll;
815     if (!UP.Partial) {
816       DEBUG(dbgs() << "  will not try to unroll partially because "
817                    << "-unroll-allow-partial not given\n");
818       UP.Count = 0;
819       return false;
820     }
821     if (UP.Count == 0)
822       UP.Count = TripCount;
823     if (UP.PartialThreshold != NoThreshold) {
824       // Reduce unroll count to be modulo of TripCount for partial unrolling.
825       if (getUnrolledLoopSize(LoopSize, UP) > UP.PartialThreshold)
826         UP.Count =
827             (std::max(UP.PartialThreshold, UP.BEInsns + 1) - UP.BEInsns) /
828             (LoopSize - UP.BEInsns);
829       if (UP.Count > UP.MaxCount)
830         UP.Count = UP.MaxCount;
831       while (UP.Count != 0 && TripCount % UP.Count != 0)
832         UP.Count--;
833       if (UP.AllowRemainder && UP.Count <= 1) {
834         // If there is no Count that is modulo of TripCount, set Count to
835         // largest power-of-two factor that satisfies the threshold limit.
836         // As we'll create fixup loop, do the type of unrolling only if
837         // remainder loop is allowed.
838         UP.Count = UP.DefaultUnrollRuntimeCount;
839         while (UP.Count != 0 &&
840                getUnrolledLoopSize(LoopSize, UP) > UP.PartialThreshold)
841           UP.Count >>= 1;
842       }
843       if (UP.Count < 2) {
844         if (PragmaEnableUnroll)
845           ORE->emit(
846               OptimizationRemarkMissed(DEBUG_TYPE, "UnrollAsDirectedTooLarge",
847                                        L->getStartLoc(), L->getHeader())
848               << "Unable to unroll loop as directed by unroll(enable) pragma "
849                  "because unrolled size is too large.");
850         UP.Count = 0;
851       }
852     } else {
853       UP.Count = TripCount;
854     }
855     if (UP.Count > UP.MaxCount)
856       UP.Count = UP.MaxCount;
857     if ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount &&
858         UP.Count != TripCount)
859       ORE->emit(
860           OptimizationRemarkMissed(DEBUG_TYPE, "FullUnrollAsDirectedTooLarge",
861                                    L->getStartLoc(), L->getHeader())
862           << "Unable to fully unroll loop as directed by unroll pragma because "
863              "unrolled size is too large.");
864     return ExplicitUnroll;
865   }
866   assert(TripCount == 0 &&
867          "All cases when TripCount is constant should be covered here.");
868   if (PragmaFullUnroll)
869     ORE->emit(
870         OptimizationRemarkMissed(DEBUG_TYPE,
871                                  "CantFullUnrollAsDirectedRuntimeTripCount",
872                                  L->getStartLoc(), L->getHeader())
873         << "Unable to fully unroll loop as directed by unroll(full) pragma "
874            "because loop has a runtime trip count.");
875 
876   // 6th priority is runtime unrolling.
877   // Don't unroll a runtime trip count loop when it is disabled.
878   if (HasRuntimeUnrollDisablePragma(L)) {
879     UP.Count = 0;
880     return false;
881   }
882 
883   // Check if the runtime trip count is too small when profile is available.
884   if (L->getHeader()->getParent()->getEntryCount()) {
885     if (auto ProfileTripCount = getLoopEstimatedTripCount(L)) {
886       if (*ProfileTripCount < FlatLoopTripCountThreshold)
887         return false;
888       else
889         UP.AllowExpensiveTripCount = true;
890     }
891   }
892 
893   // Reduce count based on the type of unrolling and the threshold values.
894   UP.Runtime |= PragmaEnableUnroll || PragmaCount > 0 || UserUnrollCount;
895   if (!UP.Runtime) {
896     DEBUG(dbgs() << "  will not try to unroll loop with runtime trip count "
897                  << "-unroll-runtime not given\n");
898     UP.Count = 0;
899     return false;
900   }
901   if (UP.Count == 0)
902     UP.Count = UP.DefaultUnrollRuntimeCount;
903 
904   // Reduce unroll count to be the largest power-of-two factor of
905   // the original count which satisfies the threshold limit.
906   while (UP.Count != 0 &&
907          getUnrolledLoopSize(LoopSize, UP) > UP.PartialThreshold)
908     UP.Count >>= 1;
909 
910 #ifndef NDEBUG
911   unsigned OrigCount = UP.Count;
912 #endif
913 
914   if (!UP.AllowRemainder && UP.Count != 0 && (TripMultiple % UP.Count) != 0) {
915     while (UP.Count != 0 && TripMultiple % UP.Count != 0)
916       UP.Count >>= 1;
917     DEBUG(dbgs() << "Remainder loop is restricted (that could architecture "
918                     "specific or because the loop contains a convergent "
919                     "instruction), so unroll count must divide the trip "
920                     "multiple, "
921                  << TripMultiple << ".  Reducing unroll count from "
922                  << OrigCount << " to " << UP.Count << ".\n");
923     using namespace ore;
924     if (PragmaCount > 0 && !UP.AllowRemainder)
925       ORE->emit(
926           OptimizationRemarkMissed(DEBUG_TYPE,
927                                    "DifferentUnrollCountFromDirected",
928                                    L->getStartLoc(), L->getHeader())
929           << "Unable to unroll loop the number of times directed by "
930              "unroll_count pragma because remainder loop is restricted "
931              "(that could architecture specific or because the loop "
932              "contains a convergent instruction) and so must have an unroll "
933              "count that divides the loop trip multiple of "
934           << NV("TripMultiple", TripMultiple) << ".  Unrolling instead "
935           << NV("UnrollCount", UP.Count) << " time(s).");
936   }
937 
938   if (UP.Count > UP.MaxCount)
939     UP.Count = UP.MaxCount;
940   DEBUG(dbgs() << "  partially unrolling with count: " << UP.Count << "\n");
941   if (UP.Count < 2)
942     UP.Count = 0;
943   return ExplicitUnroll;
944 }
945 
946 static bool tryToUnrollLoop(
947     Loop *L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution &SE,
948     const TargetTransformInfo &TTI, AssumptionCache &AC,
949     OptimizationRemarkEmitter &ORE, bool PreserveLCSSA, int OptLevel,
950     Optional<unsigned> ProvidedCount, Optional<unsigned> ProvidedThreshold,
951     Optional<bool> ProvidedAllowPartial, Optional<bool> ProvidedRuntime,
952     Optional<bool> ProvidedUpperBound, Optional<bool> ProvidedAllowPeeling) {
953   DEBUG(dbgs() << "Loop Unroll: F[" << L->getHeader()->getParent()->getName()
954                << "] Loop %" << L->getHeader()->getName() << "\n");
955   if (HasUnrollDisablePragma(L))
956     return false;
957   if (!L->isLoopSimplifyForm()) {
958     DEBUG(
959         dbgs() << "  Not unrolling loop which is not in loop-simplify form.\n");
960     return false;
961   }
962 
963   unsigned NumInlineCandidates;
964   bool NotDuplicatable;
965   bool Convergent;
966   TargetTransformInfo::UnrollingPreferences UP = gatherUnrollingPreferences(
967       L, SE, TTI, OptLevel, ProvidedThreshold, ProvidedCount,
968       ProvidedAllowPartial, ProvidedRuntime, ProvidedUpperBound,
969       ProvidedAllowPeeling);
970   // Exit early if unrolling is disabled.
971   if (UP.Threshold == 0 && (!UP.Partial || UP.PartialThreshold == 0))
972     return false;
973   unsigned LoopSize = ApproximateLoopSize(
974       L, NumInlineCandidates, NotDuplicatable, Convergent, TTI, &AC, UP.BEInsns);
975   DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
976   if (NotDuplicatable) {
977     DEBUG(dbgs() << "  Not unrolling loop which contains non-duplicatable"
978                  << " instructions.\n");
979     return false;
980   }
981   if (NumInlineCandidates != 0) {
982     DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
983     return false;
984   }
985 
986   // Find trip count and trip multiple if count is not available
987   unsigned TripCount = 0;
988   unsigned MaxTripCount = 0;
989   unsigned TripMultiple = 1;
990   // If there are multiple exiting blocks but one of them is the latch, use the
991   // latch for the trip count estimation. Otherwise insist on a single exiting
992   // block for the trip count estimation.
993   BasicBlock *ExitingBlock = L->getLoopLatch();
994   if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
995     ExitingBlock = L->getExitingBlock();
996   if (ExitingBlock) {
997     TripCount = SE.getSmallConstantTripCount(L, ExitingBlock);
998     TripMultiple = SE.getSmallConstantTripMultiple(L, ExitingBlock);
999   }
1000 
1001   // If the loop contains a convergent operation, the prelude we'd add
1002   // to do the first few instructions before we hit the unrolled loop
1003   // is unsafe -- it adds a control-flow dependency to the convergent
1004   // operation.  Therefore restrict remainder loop (try unrollig without).
1005   //
1006   // TODO: This is quite conservative.  In practice, convergent_op()
1007   // is likely to be called unconditionally in the loop.  In this
1008   // case, the program would be ill-formed (on most architectures)
1009   // unless n were the same on all threads in a thread group.
1010   // Assuming n is the same on all threads, any kind of unrolling is
1011   // safe.  But currently llvm's notion of convergence isn't powerful
1012   // enough to express this.
1013   if (Convergent)
1014     UP.AllowRemainder = false;
1015 
1016   // Try to find the trip count upper bound if we cannot find the exact trip
1017   // count.
1018   bool MaxOrZero = false;
1019   if (!TripCount) {
1020     MaxTripCount = SE.getSmallConstantMaxTripCount(L);
1021     MaxOrZero = SE.isBackedgeTakenCountMaxOrZero(L);
1022     // We can unroll by the upper bound amount if it's generally allowed or if
1023     // we know that the loop is executed either the upper bound or zero times.
1024     // (MaxOrZero unrolling keeps only the first loop test, so the number of
1025     // loop tests remains the same compared to the non-unrolled version, whereas
1026     // the generic upper bound unrolling keeps all but the last loop test so the
1027     // number of loop tests goes up which may end up being worse on targets with
1028     // constriained branch predictor resources so is controlled by an option.)
1029     // In addition we only unroll small upper bounds.
1030     if (!(UP.UpperBound || MaxOrZero) || MaxTripCount > UnrollMaxUpperBound) {
1031       MaxTripCount = 0;
1032     }
1033   }
1034 
1035   // computeUnrollCount() decides whether it is beneficial to use upper bound to
1036   // fully unroll the loop.
1037   bool UseUpperBound = false;
1038   bool IsCountSetExplicitly =
1039       computeUnrollCount(L, TTI, DT, LI, SE, &ORE, TripCount, MaxTripCount,
1040                          TripMultiple, LoopSize, UP, UseUpperBound);
1041   if (!UP.Count)
1042     return false;
1043   // Unroll factor (Count) must be less or equal to TripCount.
1044   if (TripCount && UP.Count > TripCount)
1045     UP.Count = TripCount;
1046 
1047   // Unroll the loop.
1048   LoopUnrollResult UnrollStatus = UnrollLoop(
1049       L, UP.Count, TripCount, UP.Force, UP.Runtime, UP.AllowExpensiveTripCount,
1050       UseUpperBound, MaxOrZero, TripMultiple, UP.PeelCount, UP.UnrollRemainder,
1051       LI, &SE, &DT, &AC, &ORE, PreserveLCSSA);
1052   if (UnrollStatus == LoopUnrollResult::Unmodified)
1053     return false;
1054 
1055   // If loop has an unroll count pragma or unrolled by explicitly set count
1056   // mark loop as unrolled to prevent unrolling beyond that requested.
1057   // If the loop was peeled, we already "used up" the profile information
1058   // we had, so we don't want to unroll or peel again.
1059   if (UnrollStatus != LoopUnrollResult::FullyUnrolled &&
1060       (IsCountSetExplicitly || UP.PeelCount))
1061     SetLoopAlreadyUnrolled(L);
1062 
1063   return true;
1064 }
1065 
1066 namespace {
1067 class LoopUnroll : public LoopPass {
1068 public:
1069   static char ID; // Pass ID, replacement for typeid
1070   LoopUnroll(int OptLevel = 2, Optional<unsigned> Threshold = None,
1071              Optional<unsigned> Count = None,
1072              Optional<bool> AllowPartial = None, Optional<bool> Runtime = None,
1073              Optional<bool> UpperBound = None,
1074              Optional<bool> AllowPeeling = None)
1075       : LoopPass(ID), OptLevel(OptLevel), ProvidedCount(std::move(Count)),
1076         ProvidedThreshold(Threshold), ProvidedAllowPartial(AllowPartial),
1077         ProvidedRuntime(Runtime), ProvidedUpperBound(UpperBound),
1078         ProvidedAllowPeeling(AllowPeeling) {
1079     initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
1080   }
1081 
1082   int OptLevel;
1083   Optional<unsigned> ProvidedCount;
1084   Optional<unsigned> ProvidedThreshold;
1085   Optional<bool> ProvidedAllowPartial;
1086   Optional<bool> ProvidedRuntime;
1087   Optional<bool> ProvidedUpperBound;
1088   Optional<bool> ProvidedAllowPeeling;
1089 
1090   bool runOnLoop(Loop *L, LPPassManager &) override {
1091     if (skipLoop(L))
1092       return false;
1093 
1094     Function &F = *L->getHeader()->getParent();
1095 
1096     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1097     LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1098     ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1099     const TargetTransformInfo &TTI =
1100         getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1101     auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1102     // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
1103     // pass.  Function analyses need to be preserved across loop transformations
1104     // but ORE cannot be preserved (see comment before the pass definition).
1105     OptimizationRemarkEmitter ORE(&F);
1106     bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
1107 
1108     return tryToUnrollLoop(L, DT, LI, SE, TTI, AC, ORE, PreserveLCSSA, OptLevel,
1109                            ProvidedCount, ProvidedThreshold,
1110                            ProvidedAllowPartial, ProvidedRuntime,
1111                            ProvidedUpperBound, ProvidedAllowPeeling);
1112   }
1113 
1114   /// This transformation requires natural loop information & requires that
1115   /// loop preheaders be inserted into the CFG...
1116   ///
1117   void getAnalysisUsage(AnalysisUsage &AU) const override {
1118     AU.addRequired<AssumptionCacheTracker>();
1119     AU.addRequired<TargetTransformInfoWrapperPass>();
1120     // FIXME: Loop passes are required to preserve domtree, and for now we just
1121     // recreate dom info if anything gets unrolled.
1122     getLoopAnalysisUsage(AU);
1123   }
1124 };
1125 }
1126 
1127 char LoopUnroll::ID = 0;
1128 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
1129 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1130 INITIALIZE_PASS_DEPENDENCY(LoopPass)
1131 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1132 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
1133 
1134 Pass *llvm::createLoopUnrollPass(int OptLevel, int Threshold, int Count,
1135                                  int AllowPartial, int Runtime, int UpperBound,
1136                                  int AllowPeeling) {
1137   // TODO: It would make more sense for this function to take the optionals
1138   // directly, but that's dangerous since it would silently break out of tree
1139   // callers.
1140   return new LoopUnroll(
1141       OptLevel, Threshold == -1 ? None : Optional<unsigned>(Threshold),
1142       Count == -1 ? None : Optional<unsigned>(Count),
1143       AllowPartial == -1 ? None : Optional<bool>(AllowPartial),
1144       Runtime == -1 ? None : Optional<bool>(Runtime),
1145       UpperBound == -1 ? None : Optional<bool>(UpperBound),
1146       AllowPeeling == -1 ? None : Optional<bool>(AllowPeeling));
1147 }
1148 
1149 Pass *llvm::createSimpleLoopUnrollPass(int OptLevel) {
1150   return llvm::createLoopUnrollPass(OptLevel, -1, -1, 0, 0, 0, 0);
1151 }
1152 
1153 PreservedAnalyses LoopFullUnrollPass::run(Loop &L, LoopAnalysisManager &AM,
1154                                           LoopStandardAnalysisResults &AR,
1155                                           LPMUpdater &Updater) {
1156   const auto &FAM =
1157       AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
1158   Function *F = L.getHeader()->getParent();
1159 
1160   auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
1161   // FIXME: This should probably be optional rather than required.
1162   if (!ORE)
1163     report_fatal_error(
1164         "LoopFullUnrollPass: OptimizationRemarkEmitterAnalysis not "
1165         "cached at a higher level");
1166 
1167   // Keep track of the previous loop structure so we can identify new loops
1168   // created by unrolling.
1169   Loop *ParentL = L.getParentLoop();
1170   SmallPtrSet<Loop *, 4> OldLoops;
1171   if (ParentL)
1172     OldLoops.insert(ParentL->begin(), ParentL->end());
1173   else
1174     OldLoops.insert(AR.LI.begin(), AR.LI.end());
1175 
1176   bool Changed =
1177       tryToUnrollLoop(&L, AR.DT, &AR.LI, AR.SE, AR.TTI, AR.AC, *ORE,
1178                       /*PreserveLCSSA*/ true, OptLevel, /*Count*/ None,
1179                       /*Threshold*/ None, /*AllowPartial*/ false,
1180                       /*Runtime*/ false, /*UpperBound*/ false,
1181                       /*AllowPeeling*/ false);
1182   if (!Changed)
1183     return PreservedAnalyses::all();
1184 
1185   // The parent must not be damaged by unrolling!
1186 #ifndef NDEBUG
1187   if (ParentL)
1188     ParentL->verifyLoop();
1189 #endif
1190 
1191   // Unrolling can do several things to introduce new loops into a loop nest:
1192   // - Full unrolling clones child loops within the current loop but then
1193   //   removes the current loop making all of the children appear to be new
1194   //   sibling loops.
1195   //
1196   // When a new loop appears as a sibling loop after fully unrolling,
1197   // its nesting structure has fundamentally changed and we want to revisit
1198   // it to reflect that.
1199   //
1200   // When unrolling has removed the current loop, we need to tell the
1201   // infrastructure that it is gone.
1202   //
1203   // Finally, we support a debugging/testing mode where we revisit child loops
1204   // as well. These are not expected to require further optimizations as either
1205   // they or the loop they were cloned from have been directly visited already.
1206   // But the debugging mode allows us to check this assumption.
1207   bool IsCurrentLoopValid = false;
1208   SmallVector<Loop *, 4> SibLoops;
1209   if (ParentL)
1210     SibLoops.append(ParentL->begin(), ParentL->end());
1211   else
1212     SibLoops.append(AR.LI.begin(), AR.LI.end());
1213   erase_if(SibLoops, [&](Loop *SibLoop) {
1214     if (SibLoop == &L) {
1215       IsCurrentLoopValid = true;
1216       return true;
1217     }
1218 
1219     // Otherwise erase the loop from the list if it was in the old loops.
1220     return OldLoops.count(SibLoop) != 0;
1221   });
1222   Updater.addSiblingLoops(SibLoops);
1223 
1224   if (!IsCurrentLoopValid) {
1225     Updater.markLoopAsDeleted(L);
1226   } else {
1227     // We can only walk child loops if the current loop remained valid.
1228     if (UnrollRevisitChildLoops) {
1229       // Walk *all* of the child loops.
1230       SmallVector<Loop *, 4> ChildLoops(L.begin(), L.end());
1231       Updater.addChildLoops(ChildLoops);
1232     }
1233   }
1234 
1235   return getLoopPassPreservedAnalyses();
1236 }
1237 
1238 template <typename RangeT>
1239 static SmallVector<Loop *, 8> appendLoopsToWorklist(RangeT &&Loops) {
1240   SmallVector<Loop *, 8> Worklist;
1241   // We use an internal worklist to build up the preorder traversal without
1242   // recursion.
1243   SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist;
1244 
1245   for (Loop *RootL : Loops) {
1246     assert(PreOrderLoops.empty() && "Must start with an empty preorder walk.");
1247     assert(PreOrderWorklist.empty() &&
1248            "Must start with an empty preorder walk worklist.");
1249     PreOrderWorklist.push_back(RootL);
1250     do {
1251       Loop *L = PreOrderWorklist.pop_back_val();
1252       PreOrderWorklist.append(L->begin(), L->end());
1253       PreOrderLoops.push_back(L);
1254     } while (!PreOrderWorklist.empty());
1255 
1256     Worklist.append(PreOrderLoops.begin(), PreOrderLoops.end());
1257     PreOrderLoops.clear();
1258   }
1259   return Worklist;
1260 }
1261 
1262 PreservedAnalyses LoopUnrollPass::run(Function &F,
1263                                       FunctionAnalysisManager &AM) {
1264   auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
1265   auto &LI = AM.getResult<LoopAnalysis>(F);
1266   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
1267   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1268   auto &AC = AM.getResult<AssumptionAnalysis>(F);
1269   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1270 
1271   LoopAnalysisManager *LAM = nullptr;
1272   if (auto *LAMProxy = AM.getCachedResult<LoopAnalysisManagerFunctionProxy>(F))
1273     LAM = &LAMProxy->getManager();
1274 
1275   const ModuleAnalysisManager &MAM =
1276       AM.getResult<ModuleAnalysisManagerFunctionProxy>(F).getManager();
1277   ProfileSummaryInfo *PSI =
1278       MAM.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
1279 
1280   bool Changed = false;
1281 
1282   // The unroller requires loops to be in simplified form, and also needs LCSSA.
1283   // Since simplification may add new inner loops, it has to run before the
1284   // legality and profitability checks. This means running the loop unroller
1285   // will simplify all loops, regardless of whether anything end up being
1286   // unrolled.
1287   for (auto &L : LI) {
1288     Changed |= simplifyLoop(L, &DT, &LI, &SE, &AC, false /* PreserveLCSSA */);
1289     Changed |= formLCSSARecursively(*L, DT, &LI, &SE);
1290   }
1291 
1292   SmallVector<Loop *, 8> Worklist = appendLoopsToWorklist(LI);
1293 
1294   while (!Worklist.empty()) {
1295     // Because the LoopInfo stores the loops in RPO, we walk the worklist
1296     // from back to front so that we work forward across the CFG, which
1297     // for unrolling is only needed to get optimization remarks emitted in
1298     // a forward order.
1299     Loop &L = *Worklist.pop_back_val();
1300     Loop *ParentL = L.getParentLoop();
1301 
1302     // The API here is quite complex to call, but there are only two interesting
1303     // states we support: partial and full (or "simple") unrolling. However, to
1304     // enable these things we actually pass "None" in for the optional to avoid
1305     // providing an explicit choice.
1306     Optional<bool> AllowPartialParam, RuntimeParam, UpperBoundParam,
1307         AllowPeeling;
1308     // Check if the profile summary indicates that the profiled application
1309     // has a huge working set size, in which case we disable peeling to avoid
1310     // bloating it further.
1311     if (PSI && PSI->hasHugeWorkingSetSize())
1312       AllowPeeling = false;
1313     bool CurChanged =
1314         tryToUnrollLoop(&L, DT, &LI, SE, TTI, AC, ORE,
1315                         /*PreserveLCSSA*/ true, OptLevel, /*Count*/ None,
1316                         /*Threshold*/ None, AllowPartialParam, RuntimeParam,
1317                         UpperBoundParam, AllowPeeling);
1318     Changed |= CurChanged;
1319 
1320     // The parent must not be damaged by unrolling!
1321 #ifndef NDEBUG
1322     if (CurChanged && ParentL)
1323       ParentL->verifyLoop();
1324 #endif
1325 
1326     // Walk the parent or top-level loops after unrolling to check whether we
1327     // actually removed a loop, and if so clear any cached analysis results for
1328     // it. We have to do this immediately as the next unrolling could allocate
1329     // a new loop object that ends up with the same address as the deleted loop
1330     // object causing cache collisions.
1331     if (LAM) {
1332       bool IsCurLoopValid =
1333           ParentL
1334               ? llvm::any_of(*ParentL, [&](Loop *SibL) { return SibL == &L; })
1335               : llvm::any_of(LI, [&](Loop *SibL) { return SibL == &L; });
1336       if (!IsCurLoopValid)
1337         LAM->clear(L);
1338     }
1339   }
1340 
1341   if (!Changed)
1342     return PreservedAnalyses::all();
1343 
1344   return getLoopPassPreservedAnalyses();
1345 }
1346