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