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