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