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