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