xref: /llvm-project/llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp (revision 09e539fcaebb6362795d352cdcf4a818cf4d0d6a)
1 //===- LoopUnroll.cpp - Loop unroller pass --------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements a simple loop unroller.  It works best when loops have
10 // been canonicalized by the -indvars pass, allowing it to determine the trip
11 // counts of loops easily.
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/DenseMapInfo.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/Analysis/AssumptionCache.h"
26 #include "llvm/Analysis/BlockFrequencyInfo.h"
27 #include "llvm/Analysis/CodeMetrics.h"
28 #include "llvm/Analysis/LazyBlockFrequencyInfo.h"
29 #include "llvm/Analysis/LoopAnalysisManager.h"
30 #include "llvm/Analysis/LoopInfo.h"
31 #include "llvm/Analysis/LoopPass.h"
32 #include "llvm/Analysis/LoopUnrollAnalyzer.h"
33 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
34 #include "llvm/Analysis/ProfileSummaryInfo.h"
35 #include "llvm/Analysis/ScalarEvolution.h"
36 #include "llvm/Analysis/TargetTransformInfo.h"
37 #include "llvm/IR/BasicBlock.h"
38 #include "llvm/IR/CFG.h"
39 #include "llvm/IR/Constant.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DiagnosticInfo.h"
42 #include "llvm/IR/Dominators.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/Instruction.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/IntrinsicInst.h"
47 #include "llvm/IR/Metadata.h"
48 #include "llvm/IR/PassManager.h"
49 #include "llvm/Pass.h"
50 #include "llvm/Support/Casting.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Transforms/Scalar.h"
56 #include "llvm/Transforms/Scalar/LoopPassManager.h"
57 #include "llvm/Transforms/Utils.h"
58 #include "llvm/Transforms/Utils/LoopSimplify.h"
59 #include "llvm/Transforms/Utils/LoopUtils.h"
60 #include "llvm/Transforms/Utils/SizeOpts.h"
61 #include "llvm/Transforms/Utils/UnrollLoop.h"
62 #include <algorithm>
63 #include <cassert>
64 #include <cstdint>
65 #include <limits>
66 #include <string>
67 #include <tuple>
68 #include <utility>
69 
70 using namespace llvm;
71 
72 #define DEBUG_TYPE "loop-unroll"
73 
74 static cl::opt<unsigned>
75     UnrollThreshold("unroll-threshold", cl::Hidden,
76                     cl::desc("The cost threshold for loop unrolling"));
77 
78 static cl::opt<unsigned> UnrollPartialThreshold(
79     "unroll-partial-threshold", cl::Hidden,
80     cl::desc("The cost threshold for partial loop unrolling"));
81 
82 static cl::opt<unsigned> UnrollMaxPercentThresholdBoost(
83     "unroll-max-percent-threshold-boost", cl::init(400), cl::Hidden,
84     cl::desc("The maximum 'boost' (represented as a percentage >= 100) applied "
85              "to the threshold when aggressively unrolling a loop due to the "
86              "dynamic cost savings. If completely unrolling a loop will reduce "
87              "the total runtime from X to Y, we boost the loop unroll "
88              "threshold to DefaultThreshold*std::min(MaxPercentThresholdBoost, "
89              "X/Y). This limit avoids excessive code bloat."));
90 
91 static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
92     "unroll-max-iteration-count-to-analyze", cl::init(10), cl::Hidden,
93     cl::desc("Don't allow loop unrolling to simulate more than this number of"
94              "iterations when checking full unroll profitability"));
95 
96 static cl::opt<unsigned> UnrollCount(
97     "unroll-count", cl::Hidden,
98     cl::desc("Use this unroll count for all loops including those with "
99              "unroll_count pragma values, for testing purposes"));
100 
101 static cl::opt<unsigned> UnrollMaxCount(
102     "unroll-max-count", cl::Hidden,
103     cl::desc("Set the max unroll count for partial and runtime unrolling, for"
104              "testing purposes"));
105 
106 static cl::opt<unsigned> UnrollFullMaxCount(
107     "unroll-full-max-count", cl::Hidden,
108     cl::desc(
109         "Set the max unroll count for full unrolling, for testing purposes"));
110 
111 static cl::opt<unsigned> UnrollPeelCount(
112     "unroll-peel-count", cl::Hidden,
113     cl::desc("Set the unroll peeling count, for testing purposes"));
114 
115 static cl::opt<bool>
116     UnrollAllowPartial("unroll-allow-partial", cl::Hidden,
117                        cl::desc("Allows loops to be partially unrolled until "
118                                 "-unroll-threshold loop size is reached."));
119 
120 static cl::opt<bool> UnrollAllowRemainder(
121     "unroll-allow-remainder", cl::Hidden,
122     cl::desc("Allow generation of a loop remainder (extra iterations) "
123              "when unrolling a loop."));
124 
125 static cl::opt<bool>
126     UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::Hidden,
127                   cl::desc("Unroll loops with run-time trip counts"));
128 
129 static cl::opt<unsigned> UnrollMaxUpperBound(
130     "unroll-max-upperbound", cl::init(8), cl::Hidden,
131     cl::desc(
132         "The max of trip count upper bound that is considered in unrolling"));
133 
134 static cl::opt<unsigned> PragmaUnrollThreshold(
135     "pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
136     cl::desc("Unrolled size limit for loops with an unroll(full) or "
137              "unroll_count pragma."));
138 
139 static cl::opt<unsigned> FlatLoopTripCountThreshold(
140     "flat-loop-tripcount-threshold", cl::init(5), cl::Hidden,
141     cl::desc("If the runtime tripcount for the loop is lower than the "
142              "threshold, the loop is considered as flat and will be less "
143              "aggressively unrolled."));
144 
145 static cl::opt<bool>
146     UnrollAllowPeeling("unroll-allow-peeling", cl::init(true), cl::Hidden,
147                        cl::desc("Allows loops to be peeled when the dynamic "
148                                 "trip count is known to be low."));
149 
150 static cl::opt<bool> UnrollUnrollRemainder(
151   "unroll-remainder", cl::Hidden,
152   cl::desc("Allow the loop remainder to be unrolled."));
153 
154 // This option isn't ever intended to be enabled, it serves to allow
155 // experiments to check the assumptions about when this kind of revisit is
156 // necessary.
157 static cl::opt<bool> UnrollRevisitChildLoops(
158     "unroll-revisit-child-loops", cl::Hidden,
159     cl::desc("Enqueue and re-visit child loops in the loop PM after unrolling. "
160              "This shouldn't typically be needed as child loops (or their "
161              "clones) were already visited."));
162 
163 /// A magic value for use with the Threshold parameter to indicate
164 /// that the loop unroll should be performed regardless of how much
165 /// code expansion would result.
166 static const unsigned NoThreshold = std::numeric_limits<unsigned>::max();
167 
168 /// Gather the various unrolling parameters based on the defaults, compiler
169 /// flags, TTI overrides and user specified parameters.
170 TargetTransformInfo::UnrollingPreferences llvm::gatherUnrollingPreferences(
171     Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI,
172     BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, int OptLevel,
173     Optional<unsigned> UserThreshold, Optional<unsigned> UserCount,
174     Optional<bool> UserAllowPartial, Optional<bool> UserRuntime,
175     Optional<bool> UserUpperBound, Optional<bool> UserAllowPeeling) {
176   TargetTransformInfo::UnrollingPreferences UP;
177 
178   // Set up the defaults
179   UP.Threshold = OptLevel > 2 ? 300 : 150;
180   UP.MaxPercentThresholdBoost = 400;
181   UP.OptSizeThreshold = 0;
182   UP.PartialThreshold = 150;
183   UP.PartialOptSizeThreshold = 0;
184   UP.Count = 0;
185   UP.PeelCount = 0;
186   UP.DefaultUnrollRuntimeCount = 8;
187   UP.MaxCount = std::numeric_limits<unsigned>::max();
188   UP.FullUnrollMaxCount = std::numeric_limits<unsigned>::max();
189   UP.BEInsns = 2;
190   UP.Partial = false;
191   UP.Runtime = false;
192   UP.AllowRemainder = true;
193   UP.UnrollRemainder = false;
194   UP.AllowExpensiveTripCount = false;
195   UP.Force = false;
196   UP.UpperBound = false;
197   UP.AllowPeeling = true;
198   UP.UnrollAndJam = false;
199   UP.UnrollAndJamInnerLoopThreshold = 60;
200 
201   // Override with any target specific settings
202   TTI.getUnrollingPreferences(L, SE, UP);
203 
204   // Apply size attributes
205   bool OptForSize = L->getHeader()->getParent()->hasOptSize() ||
206                     llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI);
207   if (OptForSize) {
208     UP.Threshold = UP.OptSizeThreshold;
209     UP.PartialThreshold = UP.PartialOptSizeThreshold;
210   }
211 
212   // Apply any user values specified by cl::opt
213   if (UnrollThreshold.getNumOccurrences() > 0)
214     UP.Threshold = UnrollThreshold;
215   if (UnrollPartialThreshold.getNumOccurrences() > 0)
216     UP.PartialThreshold = UnrollPartialThreshold;
217   if (UnrollMaxPercentThresholdBoost.getNumOccurrences() > 0)
218     UP.MaxPercentThresholdBoost = UnrollMaxPercentThresholdBoost;
219   if (UnrollMaxCount.getNumOccurrences() > 0)
220     UP.MaxCount = UnrollMaxCount;
221   if (UnrollFullMaxCount.getNumOccurrences() > 0)
222     UP.FullUnrollMaxCount = UnrollFullMaxCount;
223   if (UnrollPeelCount.getNumOccurrences() > 0)
224     UP.PeelCount = UnrollPeelCount;
225   if (UnrollAllowPartial.getNumOccurrences() > 0)
226     UP.Partial = UnrollAllowPartial;
227   if (UnrollAllowRemainder.getNumOccurrences() > 0)
228     UP.AllowRemainder = UnrollAllowRemainder;
229   if (UnrollRuntime.getNumOccurrences() > 0)
230     UP.Runtime = UnrollRuntime;
231   if (UnrollMaxUpperBound == 0)
232     UP.UpperBound = false;
233   if (UnrollAllowPeeling.getNumOccurrences() > 0)
234     UP.AllowPeeling = UnrollAllowPeeling;
235   if (UnrollUnrollRemainder.getNumOccurrences() > 0)
236     UP.UnrollRemainder = UnrollUnrollRemainder;
237 
238   // Apply user values provided by argument
239   if (UserThreshold.hasValue()) {
240     UP.Threshold = *UserThreshold;
241     UP.PartialThreshold = *UserThreshold;
242   }
243   if (UserCount.hasValue())
244     UP.Count = *UserCount;
245   if (UserAllowPartial.hasValue())
246     UP.Partial = *UserAllowPartial;
247   if (UserRuntime.hasValue())
248     UP.Runtime = *UserRuntime;
249   if (UserUpperBound.hasValue())
250     UP.UpperBound = *UserUpperBound;
251   if (UserAllowPeeling.hasValue())
252     UP.AllowPeeling = *UserAllowPeeling;
253 
254   return UP;
255 }
256 
257 namespace {
258 
259 /// A struct to densely store the state of an instruction after unrolling at
260 /// each iteration.
261 ///
262 /// This is designed to work like a tuple of <Instruction *, int> for the
263 /// purposes of hashing and lookup, but to be able to associate two boolean
264 /// states with each key.
265 struct UnrolledInstState {
266   Instruction *I;
267   int Iteration : 30;
268   unsigned IsFree : 1;
269   unsigned IsCounted : 1;
270 };
271 
272 /// Hashing and equality testing for a set of the instruction states.
273 struct UnrolledInstStateKeyInfo {
274   using PtrInfo = DenseMapInfo<Instruction *>;
275   using PairInfo = DenseMapInfo<std::pair<Instruction *, int>>;
276 
277   static inline UnrolledInstState getEmptyKey() {
278     return {PtrInfo::getEmptyKey(), 0, 0, 0};
279   }
280 
281   static inline UnrolledInstState getTombstoneKey() {
282     return {PtrInfo::getTombstoneKey(), 0, 0, 0};
283   }
284 
285   static inline unsigned getHashValue(const UnrolledInstState &S) {
286     return PairInfo::getHashValue({S.I, S.Iteration});
287   }
288 
289   static inline bool isEqual(const UnrolledInstState &LHS,
290                              const UnrolledInstState &RHS) {
291     return PairInfo::isEqual({LHS.I, LHS.Iteration}, {RHS.I, RHS.Iteration});
292   }
293 };
294 
295 struct EstimatedUnrollCost {
296   /// The estimated cost after unrolling.
297   unsigned UnrolledCost;
298 
299   /// The estimated dynamic cost of executing the instructions in the
300   /// rolled form.
301   unsigned RolledDynamicCost;
302 };
303 
304 } // end anonymous namespace
305 
306 /// Figure out if the loop is worth full unrolling.
307 ///
308 /// Complete loop unrolling can make some loads constant, and we need to know
309 /// if that would expose any further optimization opportunities.  This routine
310 /// estimates this optimization.  It computes cost of unrolled loop
311 /// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By
312 /// dynamic cost we mean that we won't count costs of blocks that are known not
313 /// to be executed (i.e. if we have a branch in the loop and we know that at the
314 /// given iteration its condition would be resolved to true, we won't add up the
315 /// cost of the 'false'-block).
316 /// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If
317 /// the analysis failed (no benefits expected from the unrolling, or the loop is
318 /// too big to analyze), the returned value is None.
319 static Optional<EstimatedUnrollCost> analyzeLoopUnrollCost(
320     const Loop *L, unsigned TripCount, DominatorTree &DT, ScalarEvolution &SE,
321     const SmallPtrSetImpl<const Value *> &EphValues,
322     const TargetTransformInfo &TTI, unsigned MaxUnrolledLoopSize) {
323   // We want to be able to scale offsets by the trip count and add more offsets
324   // to them without checking for overflows, and we already don't want to
325   // analyze *massive* trip counts, so we force the max to be reasonably small.
326   assert(UnrollMaxIterationsCountToAnalyze <
327              (unsigned)(std::numeric_limits<int>::max() / 2) &&
328          "The unroll iterations max is too large!");
329 
330   // Only analyze inner loops. We can't properly estimate cost of nested loops
331   // and we won't visit inner loops again anyway.
332   if (!L->empty())
333     return None;
334 
335   // Don't simulate loops with a big or unknown tripcount
336   if (!UnrollMaxIterationsCountToAnalyze || !TripCount ||
337       TripCount > UnrollMaxIterationsCountToAnalyze)
338     return None;
339 
340   SmallSetVector<BasicBlock *, 16> BBWorklist;
341   SmallSetVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitWorklist;
342   DenseMap<Value *, Constant *> SimplifiedValues;
343   SmallVector<std::pair<Value *, Constant *>, 4> SimplifiedInputValues;
344 
345   // The estimated cost of the unrolled form of the loop. We try to estimate
346   // this by simplifying as much as we can while computing the estimate.
347   unsigned UnrolledCost = 0;
348 
349   // We also track the estimated dynamic (that is, actually executed) cost in
350   // the rolled form. This helps identify cases when the savings from unrolling
351   // aren't just exposing dead control flows, but actual reduced dynamic
352   // instructions due to the simplifications which we expect to occur after
353   // unrolling.
354   unsigned RolledDynamicCost = 0;
355 
356   // We track the simplification of each instruction in each iteration. We use
357   // this to recursively merge costs into the unrolled cost on-demand so that
358   // we don't count the cost of any dead code. This is essentially a map from
359   // <instruction, int> to <bool, bool>, but stored as a densely packed struct.
360   DenseSet<UnrolledInstState, UnrolledInstStateKeyInfo> InstCostMap;
361 
362   // A small worklist used to accumulate cost of instructions from each
363   // observable and reached root in the loop.
364   SmallVector<Instruction *, 16> CostWorklist;
365 
366   // PHI-used worklist used between iterations while accumulating cost.
367   SmallVector<Instruction *, 4> PHIUsedList;
368 
369   // Helper function to accumulate cost for instructions in the loop.
370   auto AddCostRecursively = [&](Instruction &RootI, int Iteration) {
371     assert(Iteration >= 0 && "Cannot have a negative iteration!");
372     assert(CostWorklist.empty() && "Must start with an empty cost list");
373     assert(PHIUsedList.empty() && "Must start with an empty phi used list");
374     CostWorklist.push_back(&RootI);
375     for (;; --Iteration) {
376       do {
377         Instruction *I = CostWorklist.pop_back_val();
378 
379         // InstCostMap only uses I and Iteration as a key, the other two values
380         // don't matter here.
381         auto CostIter = InstCostMap.find({I, Iteration, 0, 0});
382         if (CostIter == InstCostMap.end())
383           // If an input to a PHI node comes from a dead path through the loop
384           // we may have no cost data for it here. What that actually means is
385           // that it is free.
386           continue;
387         auto &Cost = *CostIter;
388         if (Cost.IsCounted)
389           // Already counted this instruction.
390           continue;
391 
392         // Mark that we are counting the cost of this instruction now.
393         Cost.IsCounted = true;
394 
395         // If this is a PHI node in the loop header, just add it to the PHI set.
396         if (auto *PhiI = dyn_cast<PHINode>(I))
397           if (PhiI->getParent() == L->getHeader()) {
398             assert(Cost.IsFree && "Loop PHIs shouldn't be evaluated as they "
399                                   "inherently simplify during unrolling.");
400             if (Iteration == 0)
401               continue;
402 
403             // Push the incoming value from the backedge into the PHI used list
404             // if it is an in-loop instruction. We'll use this to populate the
405             // cost worklist for the next iteration (as we count backwards).
406             if (auto *OpI = dyn_cast<Instruction>(
407                     PhiI->getIncomingValueForBlock(L->getLoopLatch())))
408               if (L->contains(OpI))
409                 PHIUsedList.push_back(OpI);
410             continue;
411           }
412 
413         // First accumulate the cost of this instruction.
414         if (!Cost.IsFree) {
415           UnrolledCost += TTI.getUserCost(I);
416           LLVM_DEBUG(dbgs() << "Adding cost of instruction (iteration "
417                             << Iteration << "): ");
418           LLVM_DEBUG(I->dump());
419         }
420 
421         // We must count the cost of every operand which is not free,
422         // recursively. If we reach a loop PHI node, simply add it to the set
423         // to be considered on the next iteration (backwards!).
424         for (Value *Op : I->operands()) {
425           // Check whether this operand is free due to being a constant or
426           // outside the loop.
427           auto *OpI = dyn_cast<Instruction>(Op);
428           if (!OpI || !L->contains(OpI))
429             continue;
430 
431           // Otherwise accumulate its cost.
432           CostWorklist.push_back(OpI);
433         }
434       } while (!CostWorklist.empty());
435 
436       if (PHIUsedList.empty())
437         // We've exhausted the search.
438         break;
439 
440       assert(Iteration > 0 &&
441              "Cannot track PHI-used values past the first iteration!");
442       CostWorklist.append(PHIUsedList.begin(), PHIUsedList.end());
443       PHIUsedList.clear();
444     }
445   };
446 
447   // Ensure that we don't violate the loop structure invariants relied on by
448   // this analysis.
449   assert(L->isLoopSimplifyForm() && "Must put loop into normal form first.");
450   assert(L->isLCSSAForm(DT) &&
451          "Must have loops in LCSSA form to track live-out values.");
452 
453   LLVM_DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n");
454 
455   // Simulate execution of each iteration of the loop counting instructions,
456   // which would be simplified.
457   // Since the same load will take different values on different iterations,
458   // we literally have to go through all loop's iterations.
459   for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
460     LLVM_DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n");
461 
462     // Prepare for the iteration by collecting any simplified entry or backedge
463     // inputs.
464     for (Instruction &I : *L->getHeader()) {
465       auto *PHI = dyn_cast<PHINode>(&I);
466       if (!PHI)
467         break;
468 
469       // The loop header PHI nodes must have exactly two input: one from the
470       // loop preheader and one from the loop latch.
471       assert(
472           PHI->getNumIncomingValues() == 2 &&
473           "Must have an incoming value only for the preheader and the latch.");
474 
475       Value *V = PHI->getIncomingValueForBlock(
476           Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch());
477       Constant *C = dyn_cast<Constant>(V);
478       if (Iteration != 0 && !C)
479         C = SimplifiedValues.lookup(V);
480       if (C)
481         SimplifiedInputValues.push_back({PHI, C});
482     }
483 
484     // Now clear and re-populate the map for the next iteration.
485     SimplifiedValues.clear();
486     while (!SimplifiedInputValues.empty())
487       SimplifiedValues.insert(SimplifiedInputValues.pop_back_val());
488 
489     UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SE, L);
490 
491     BBWorklist.clear();
492     BBWorklist.insert(L->getHeader());
493     // Note that we *must not* cache the size, this loop grows the worklist.
494     for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
495       BasicBlock *BB = BBWorklist[Idx];
496 
497       // Visit all instructions in the given basic block and try to simplify
498       // it.  We don't change the actual IR, just count optimization
499       // opportunities.
500       for (Instruction &I : *BB) {
501         // These won't get into the final code - don't even try calculating the
502         // cost for them.
503         if (isa<DbgInfoIntrinsic>(I) || EphValues.count(&I))
504           continue;
505 
506         // Track this instruction's expected baseline cost when executing the
507         // rolled loop form.
508         RolledDynamicCost += TTI.getUserCost(&I);
509 
510         // Visit the instruction to analyze its loop cost after unrolling,
511         // and if the visitor returns true, mark the instruction as free after
512         // unrolling and continue.
513         bool IsFree = Analyzer.visit(I);
514         bool Inserted = InstCostMap.insert({&I, (int)Iteration,
515                                            (unsigned)IsFree,
516                                            /*IsCounted*/ false}).second;
517         (void)Inserted;
518         assert(Inserted && "Cannot have a state for an unvisited instruction!");
519 
520         if (IsFree)
521           continue;
522 
523         // Can't properly model a cost of a call.
524         // FIXME: With a proper cost model we should be able to do it.
525         if (auto *CI = dyn_cast<CallInst>(&I)) {
526           const Function *Callee = CI->getCalledFunction();
527           if (!Callee || TTI.isLoweredToCall(Callee)) {
528             LLVM_DEBUG(dbgs() << "Can't analyze cost of loop with call\n");
529             return None;
530           }
531         }
532 
533         // If the instruction might have a side-effect recursively account for
534         // the cost of it and all the instructions leading up to it.
535         if (I.mayHaveSideEffects())
536           AddCostRecursively(I, Iteration);
537 
538         // If unrolled body turns out to be too big, bail out.
539         if (UnrolledCost > MaxUnrolledLoopSize) {
540           LLVM_DEBUG(dbgs() << "  Exceeded threshold.. exiting.\n"
541                             << "  UnrolledCost: " << UnrolledCost
542                             << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize
543                             << "\n");
544           return None;
545         }
546       }
547 
548       Instruction *TI = BB->getTerminator();
549 
550       // Add in the live successors by first checking whether we have terminator
551       // that may be simplified based on the values simplified by this call.
552       BasicBlock *KnownSucc = nullptr;
553       if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
554         if (BI->isConditional()) {
555           if (Constant *SimpleCond =
556                   SimplifiedValues.lookup(BI->getCondition())) {
557             // Just take the first successor if condition is undef
558             if (isa<UndefValue>(SimpleCond))
559               KnownSucc = BI->getSuccessor(0);
560             else if (ConstantInt *SimpleCondVal =
561                          dyn_cast<ConstantInt>(SimpleCond))
562               KnownSucc = BI->getSuccessor(SimpleCondVal->isZero() ? 1 : 0);
563           }
564         }
565       } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
566         if (Constant *SimpleCond =
567                 SimplifiedValues.lookup(SI->getCondition())) {
568           // Just take the first successor if condition is undef
569           if (isa<UndefValue>(SimpleCond))
570             KnownSucc = SI->getSuccessor(0);
571           else if (ConstantInt *SimpleCondVal =
572                        dyn_cast<ConstantInt>(SimpleCond))
573             KnownSucc = SI->findCaseValue(SimpleCondVal)->getCaseSuccessor();
574         }
575       }
576       if (KnownSucc) {
577         if (L->contains(KnownSucc))
578           BBWorklist.insert(KnownSucc);
579         else
580           ExitWorklist.insert({BB, KnownSucc});
581         continue;
582       }
583 
584       // Add BB's successors to the worklist.
585       for (BasicBlock *Succ : successors(BB))
586         if (L->contains(Succ))
587           BBWorklist.insert(Succ);
588         else
589           ExitWorklist.insert({BB, Succ});
590       AddCostRecursively(*TI, Iteration);
591     }
592 
593     // If we found no optimization opportunities on the first iteration, we
594     // won't find them on later ones too.
595     if (UnrolledCost == RolledDynamicCost) {
596       LLVM_DEBUG(dbgs() << "  No opportunities found.. exiting.\n"
597                         << "  UnrolledCost: " << UnrolledCost << "\n");
598       return None;
599     }
600   }
601 
602   while (!ExitWorklist.empty()) {
603     BasicBlock *ExitingBB, *ExitBB;
604     std::tie(ExitingBB, ExitBB) = ExitWorklist.pop_back_val();
605 
606     for (Instruction &I : *ExitBB) {
607       auto *PN = dyn_cast<PHINode>(&I);
608       if (!PN)
609         break;
610 
611       Value *Op = PN->getIncomingValueForBlock(ExitingBB);
612       if (auto *OpI = dyn_cast<Instruction>(Op))
613         if (L->contains(OpI))
614           AddCostRecursively(*OpI, TripCount - 1);
615     }
616   }
617 
618   LLVM_DEBUG(dbgs() << "Analysis finished:\n"
619                     << "UnrolledCost: " << UnrolledCost << ", "
620                     << "RolledDynamicCost: " << RolledDynamicCost << "\n");
621   return {{UnrolledCost, RolledDynamicCost}};
622 }
623 
624 /// ApproximateLoopSize - Approximate the size of the loop.
625 unsigned llvm::ApproximateLoopSize(
626     const Loop *L, unsigned &NumCalls, bool &NotDuplicatable, bool &Convergent,
627     const TargetTransformInfo &TTI,
628     const SmallPtrSetImpl<const Value *> &EphValues, unsigned BEInsns) {
629   CodeMetrics Metrics;
630   for (BasicBlock *BB : L->blocks())
631     Metrics.analyzeBasicBlock(BB, TTI, EphValues);
632   NumCalls = Metrics.NumInlineCandidates;
633   NotDuplicatable = Metrics.notDuplicatable;
634   Convergent = Metrics.convergent;
635 
636   unsigned LoopSize = Metrics.NumInsts;
637 
638   // Don't allow an estimate of size zero.  This would allows unrolling of loops
639   // with huge iteration counts, which is a compile time problem even if it's
640   // not a problem for code quality. Also, the code using this size may assume
641   // that each loop has at least three instructions (likely a conditional
642   // branch, a comparison feeding that branch, and some kind of loop increment
643   // feeding that comparison instruction).
644   LoopSize = std::max(LoopSize, BEInsns + 1);
645 
646   return LoopSize;
647 }
648 
649 // Returns the loop hint metadata node with the given name (for example,
650 // "llvm.loop.unroll.count").  If no such metadata node exists, then nullptr is
651 // returned.
652 static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
653   if (MDNode *LoopID = L->getLoopID())
654     return GetUnrollMetadata(LoopID, Name);
655   return nullptr;
656 }
657 
658 // Returns true if the loop has an unroll(full) pragma.
659 static bool HasUnrollFullPragma(const Loop *L) {
660   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
661 }
662 
663 // Returns true if the loop has an unroll(enable) pragma. This metadata is used
664 // for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives.
665 static bool HasUnrollEnablePragma(const Loop *L) {
666   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.enable");
667 }
668 
669 // Returns true if the loop has an runtime unroll(disable) pragma.
670 static bool HasRuntimeUnrollDisablePragma(const Loop *L) {
671   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
672 }
673 
674 // If loop has an unroll_count pragma return the (necessarily
675 // positive) value from the pragma.  Otherwise return 0.
676 static unsigned UnrollCountPragmaValue(const Loop *L) {
677   MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
678   if (MD) {
679     assert(MD->getNumOperands() == 2 &&
680            "Unroll count hint metadata should have two operands.");
681     unsigned Count =
682         mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
683     assert(Count >= 1 && "Unroll count must be positive.");
684     return Count;
685   }
686   return 0;
687 }
688 
689 // Computes the boosting factor for complete unrolling.
690 // If fully unrolling the loop would save a lot of RolledDynamicCost, it would
691 // be beneficial to fully unroll the loop even if unrolledcost is large. We
692 // use (RolledDynamicCost / UnrolledCost) to model the unroll benefits to adjust
693 // the unroll threshold.
694 static unsigned getFullUnrollBoostingFactor(const EstimatedUnrollCost &Cost,
695                                             unsigned MaxPercentThresholdBoost) {
696   if (Cost.RolledDynamicCost >= std::numeric_limits<unsigned>::max() / 100)
697     return 100;
698   else if (Cost.UnrolledCost != 0)
699     // The boosting factor is RolledDynamicCost / UnrolledCost
700     return std::min(100 * Cost.RolledDynamicCost / Cost.UnrolledCost,
701                     MaxPercentThresholdBoost);
702   else
703     return MaxPercentThresholdBoost;
704 }
705 
706 // Returns loop size estimation for unrolled loop.
707 static uint64_t getUnrolledLoopSize(
708     unsigned LoopSize,
709     TargetTransformInfo::UnrollingPreferences &UP) {
710   assert(LoopSize >= UP.BEInsns && "LoopSize should not be less than BEInsns!");
711   return (uint64_t)(LoopSize - UP.BEInsns) * UP.Count + UP.BEInsns;
712 }
713 
714 // Returns true if unroll count was set explicitly.
715 // Calculates unroll count and writes it to UP.Count.
716 // Unless IgnoreUser is true, will also use metadata and command-line options
717 // that are specific to to the LoopUnroll pass (which, for instance, are
718 // irrelevant for the LoopUnrollAndJam pass).
719 // FIXME: This function is used by LoopUnroll and LoopUnrollAndJam, but consumes
720 // many LoopUnroll-specific options. The shared functionality should be
721 // refactored into it own function.
722 bool llvm::computeUnrollCount(
723     Loop *L, const TargetTransformInfo &TTI, DominatorTree &DT, LoopInfo *LI,
724     ScalarEvolution &SE, const SmallPtrSetImpl<const Value *> &EphValues,
725     OptimizationRemarkEmitter *ORE, unsigned &TripCount, unsigned MaxTripCount,
726     unsigned &TripMultiple, unsigned LoopSize,
727     TargetTransformInfo::UnrollingPreferences &UP, bool &UseUpperBound) {
728 
729   // Check for explicit Count.
730   // 1st priority is unroll count set by "unroll-count" option.
731   bool UserUnrollCount = UnrollCount.getNumOccurrences() > 0;
732   if (UserUnrollCount) {
733     UP.Count = UnrollCount;
734     UP.AllowExpensiveTripCount = true;
735     UP.Force = true;
736     if (UP.AllowRemainder && getUnrolledLoopSize(LoopSize, UP) < UP.Threshold)
737       return true;
738   }
739 
740   // 2nd priority is unroll count set by pragma.
741   unsigned PragmaCount = UnrollCountPragmaValue(L);
742   if (PragmaCount > 0) {
743     UP.Count = PragmaCount;
744     UP.Runtime = true;
745     UP.AllowExpensiveTripCount = true;
746     UP.Force = true;
747     if ((UP.AllowRemainder || (TripMultiple % PragmaCount == 0)) &&
748         getUnrolledLoopSize(LoopSize, UP) < PragmaUnrollThreshold)
749       return true;
750   }
751   bool PragmaFullUnroll = HasUnrollFullPragma(L);
752   if (PragmaFullUnroll && TripCount != 0) {
753     UP.Count = TripCount;
754     if (getUnrolledLoopSize(LoopSize, UP) < PragmaUnrollThreshold)
755       return false;
756   }
757 
758   bool PragmaEnableUnroll = HasUnrollEnablePragma(L);
759   bool ExplicitUnroll = PragmaCount > 0 || PragmaFullUnroll ||
760                         PragmaEnableUnroll || UserUnrollCount;
761 
762   if (ExplicitUnroll && TripCount != 0) {
763     // If the loop has an unrolling pragma, we want to be more aggressive with
764     // unrolling limits. Set thresholds to at least the PragmaUnrollThreshold
765     // value which is larger than the default limits.
766     UP.Threshold = std::max<unsigned>(UP.Threshold, PragmaUnrollThreshold);
767     UP.PartialThreshold =
768         std::max<unsigned>(UP.PartialThreshold, PragmaUnrollThreshold);
769   }
770 
771   // 3rd priority is full unroll count.
772   // Full unroll makes sense only when TripCount or its upper bound could be
773   // statically calculated.
774   // Also we need to check if we exceed FullUnrollMaxCount.
775   // If using the upper bound to unroll, TripMultiple should be set to 1 because
776   // we do not know when loop may exit.
777   // MaxTripCount and ExactTripCount cannot both be non zero since we only
778   // compute the former when the latter is zero.
779   unsigned ExactTripCount = TripCount;
780   assert((ExactTripCount == 0 || MaxTripCount == 0) &&
781          "ExtractTripCount and MaxTripCount cannot both be non zero.");
782   unsigned FullUnrollTripCount = ExactTripCount ? ExactTripCount : MaxTripCount;
783   UP.Count = FullUnrollTripCount;
784   if (FullUnrollTripCount && FullUnrollTripCount <= UP.FullUnrollMaxCount) {
785     // When computing the unrolled size, note that BEInsns are not replicated
786     // like the rest of the loop body.
787     if (getUnrolledLoopSize(LoopSize, UP) < UP.Threshold) {
788       UseUpperBound = (MaxTripCount == FullUnrollTripCount);
789       TripCount = FullUnrollTripCount;
790       TripMultiple = UP.UpperBound ? 1 : TripMultiple;
791       return ExplicitUnroll;
792     } else {
793       // The loop isn't that small, but we still can fully unroll it if that
794       // helps to remove a significant number of instructions.
795       // To check that, run additional analysis on the loop.
796       if (Optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost(
797               L, FullUnrollTripCount, DT, SE, EphValues, TTI,
798               UP.Threshold * UP.MaxPercentThresholdBoost / 100)) {
799         unsigned Boost =
800             getFullUnrollBoostingFactor(*Cost, UP.MaxPercentThresholdBoost);
801         if (Cost->UnrolledCost < UP.Threshold * Boost / 100) {
802           UseUpperBound = (MaxTripCount == FullUnrollTripCount);
803           TripCount = FullUnrollTripCount;
804           TripMultiple = UP.UpperBound ? 1 : TripMultiple;
805           return ExplicitUnroll;
806         }
807       }
808     }
809   }
810 
811   // 4th priority is loop peeling.
812   computePeelCount(L, LoopSize, UP, TripCount, SE);
813   if (UP.PeelCount) {
814     UP.Runtime = false;
815     UP.Count = 1;
816     return ExplicitUnroll;
817   }
818 
819   // 5th priority is partial unrolling.
820   // Try partial unroll only when TripCount could be statically calculated.
821   if (TripCount) {
822     UP.Partial |= ExplicitUnroll;
823     if (!UP.Partial) {
824       LLVM_DEBUG(dbgs() << "  will not try to unroll partially because "
825                         << "-unroll-allow-partial not given\n");
826       UP.Count = 0;
827       return false;
828     }
829     if (UP.Count == 0)
830       UP.Count = TripCount;
831     if (UP.PartialThreshold != NoThreshold) {
832       // Reduce unroll count to be modulo of TripCount for partial unrolling.
833       if (getUnrolledLoopSize(LoopSize, UP) > UP.PartialThreshold)
834         UP.Count =
835             (std::max(UP.PartialThreshold, UP.BEInsns + 1) - UP.BEInsns) /
836             (LoopSize - UP.BEInsns);
837       if (UP.Count > UP.MaxCount)
838         UP.Count = UP.MaxCount;
839       while (UP.Count != 0 && TripCount % UP.Count != 0)
840         UP.Count--;
841       if (UP.AllowRemainder && UP.Count <= 1) {
842         // If there is no Count that is modulo of TripCount, set Count to
843         // largest power-of-two factor that satisfies the threshold limit.
844         // As we'll create fixup loop, do the type of unrolling only if
845         // remainder loop is allowed.
846         UP.Count = UP.DefaultUnrollRuntimeCount;
847         while (UP.Count != 0 &&
848                getUnrolledLoopSize(LoopSize, UP) > UP.PartialThreshold)
849           UP.Count >>= 1;
850       }
851       if (UP.Count < 2) {
852         if (PragmaEnableUnroll)
853           ORE->emit([&]() {
854             return OptimizationRemarkMissed(DEBUG_TYPE,
855                                             "UnrollAsDirectedTooLarge",
856                                             L->getStartLoc(), L->getHeader())
857                    << "Unable to unroll loop as directed by unroll(enable) "
858                       "pragma "
859                       "because unrolled size is too large.";
860           });
861         UP.Count = 0;
862       }
863     } else {
864       UP.Count = TripCount;
865     }
866     if (UP.Count > UP.MaxCount)
867       UP.Count = UP.MaxCount;
868     if ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount &&
869         UP.Count != TripCount)
870       ORE->emit([&]() {
871         return OptimizationRemarkMissed(DEBUG_TYPE,
872                                         "FullUnrollAsDirectedTooLarge",
873                                         L->getStartLoc(), L->getHeader())
874                << "Unable to fully unroll loop as directed by unroll pragma "
875                   "because "
876                   "unrolled size is too large.";
877       });
878     return ExplicitUnroll;
879   }
880   assert(TripCount == 0 &&
881          "All cases when TripCount is constant should be covered here.");
882   if (PragmaFullUnroll)
883     ORE->emit([&]() {
884       return OptimizationRemarkMissed(
885                  DEBUG_TYPE, "CantFullUnrollAsDirectedRuntimeTripCount",
886                  L->getStartLoc(), L->getHeader())
887              << "Unable to fully unroll loop as directed by unroll(full) "
888                 "pragma "
889                 "because loop has a runtime trip count.";
890     });
891 
892   // 6th priority is runtime unrolling.
893   // Don't unroll a runtime trip count loop when it is disabled.
894   if (HasRuntimeUnrollDisablePragma(L)) {
895     UP.Count = 0;
896     return false;
897   }
898 
899   // Check if the runtime trip count is too small when profile is available.
900   if (L->getHeader()->getParent()->hasProfileData()) {
901     if (auto ProfileTripCount = getLoopEstimatedTripCount(L)) {
902       if (*ProfileTripCount < FlatLoopTripCountThreshold)
903         return false;
904       else
905         UP.AllowExpensiveTripCount = true;
906     }
907   }
908 
909   // Reduce count based on the type of unrolling and the threshold values.
910   UP.Runtime |= PragmaEnableUnroll || PragmaCount > 0 || UserUnrollCount;
911   if (!UP.Runtime) {
912     LLVM_DEBUG(
913         dbgs() << "  will not try to unroll loop with runtime trip count "
914                << "-unroll-runtime not given\n");
915     UP.Count = 0;
916     return false;
917   }
918   if (UP.Count == 0)
919     UP.Count = UP.DefaultUnrollRuntimeCount;
920 
921   // Reduce unroll count to be the largest power-of-two factor of
922   // the original count which satisfies the threshold limit.
923   while (UP.Count != 0 &&
924          getUnrolledLoopSize(LoopSize, UP) > UP.PartialThreshold)
925     UP.Count >>= 1;
926 
927 #ifndef NDEBUG
928   unsigned OrigCount = UP.Count;
929 #endif
930 
931   if (!UP.AllowRemainder && UP.Count != 0 && (TripMultiple % UP.Count) != 0) {
932     while (UP.Count != 0 && TripMultiple % UP.Count != 0)
933       UP.Count >>= 1;
934     LLVM_DEBUG(
935         dbgs() << "Remainder loop is restricted (that could architecture "
936                   "specific or because the loop contains a convergent "
937                   "instruction), so unroll count must divide the trip "
938                   "multiple, "
939                << TripMultiple << ".  Reducing unroll count from " << OrigCount
940                << " to " << UP.Count << ".\n");
941 
942     using namespace ore;
943 
944     if (PragmaCount > 0 && !UP.AllowRemainder)
945       ORE->emit([&]() {
946         return OptimizationRemarkMissed(DEBUG_TYPE,
947                                         "DifferentUnrollCountFromDirected",
948                                         L->getStartLoc(), L->getHeader())
949                << "Unable to unroll loop the number of times directed by "
950                   "unroll_count pragma because remainder loop is restricted "
951                   "(that could architecture specific or because the loop "
952                   "contains a convergent instruction) and so must have an "
953                   "unroll "
954                   "count that divides the loop trip multiple of "
955                << NV("TripMultiple", TripMultiple) << ".  Unrolling instead "
956                << NV("UnrollCount", UP.Count) << " time(s).";
957       });
958   }
959 
960   if (UP.Count > UP.MaxCount)
961     UP.Count = UP.MaxCount;
962   LLVM_DEBUG(dbgs() << "  partially unrolling with count: " << UP.Count
963                     << "\n");
964   if (UP.Count < 2)
965     UP.Count = 0;
966   return ExplicitUnroll;
967 }
968 
969 static LoopUnrollResult tryToUnrollLoop(
970     Loop *L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution &SE,
971     const TargetTransformInfo &TTI, AssumptionCache &AC,
972     OptimizationRemarkEmitter &ORE,
973     BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
974     bool PreserveLCSSA, int OptLevel,
975     bool OnlyWhenForced, bool ForgetAllSCEV, Optional<unsigned> ProvidedCount,
976     Optional<unsigned> ProvidedThreshold, Optional<bool> ProvidedAllowPartial,
977     Optional<bool> ProvidedRuntime, Optional<bool> ProvidedUpperBound,
978     Optional<bool> ProvidedAllowPeeling) {
979   LLVM_DEBUG(dbgs() << "Loop Unroll: F["
980                     << L->getHeader()->getParent()->getName() << "] Loop %"
981                     << L->getHeader()->getName() << "\n");
982   TransformationMode TM = hasUnrollTransformation(L);
983   if (TM & TM_Disable)
984     return LoopUnrollResult::Unmodified;
985   if (!L->isLoopSimplifyForm()) {
986     LLVM_DEBUG(
987         dbgs() << "  Not unrolling loop which is not in loop-simplify form.\n");
988     return LoopUnrollResult::Unmodified;
989   }
990 
991   // When automtatic unrolling is disabled, do not unroll unless overridden for
992   // this loop.
993   if (OnlyWhenForced && !(TM & TM_Enable))
994     return LoopUnrollResult::Unmodified;
995 
996   unsigned NumInlineCandidates;
997   bool NotDuplicatable;
998   bool Convergent;
999   TargetTransformInfo::UnrollingPreferences UP = gatherUnrollingPreferences(
1000       L, SE, TTI, BFI, PSI, OptLevel, ProvidedThreshold, ProvidedCount,
1001       ProvidedAllowPartial, ProvidedRuntime, ProvidedUpperBound,
1002       ProvidedAllowPeeling);
1003   // Exit early if unrolling is disabled.
1004   if (UP.Threshold == 0 && (!UP.Partial || UP.PartialThreshold == 0))
1005     return LoopUnrollResult::Unmodified;
1006 
1007   SmallPtrSet<const Value *, 32> EphValues;
1008   CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
1009 
1010   unsigned LoopSize =
1011       ApproximateLoopSize(L, NumInlineCandidates, NotDuplicatable, Convergent,
1012                           TTI, EphValues, UP.BEInsns);
1013   LLVM_DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
1014   if (NotDuplicatable) {
1015     LLVM_DEBUG(dbgs() << "  Not unrolling loop which contains non-duplicatable"
1016                       << " instructions.\n");
1017     return LoopUnrollResult::Unmodified;
1018   }
1019   if (NumInlineCandidates != 0) {
1020     LLVM_DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
1021     return LoopUnrollResult::Unmodified;
1022   }
1023 
1024   // Find trip count and trip multiple if count is not available
1025   unsigned TripCount = 0;
1026   unsigned MaxTripCount = 0;
1027   unsigned TripMultiple = 1;
1028   // If there are multiple exiting blocks but one of them is the latch, use the
1029   // latch for the trip count estimation. Otherwise insist on a single exiting
1030   // block for the trip count estimation.
1031   BasicBlock *ExitingBlock = L->getLoopLatch();
1032   if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
1033     ExitingBlock = L->getExitingBlock();
1034   if (ExitingBlock) {
1035     TripCount = SE.getSmallConstantTripCount(L, ExitingBlock);
1036     TripMultiple = SE.getSmallConstantTripMultiple(L, ExitingBlock);
1037   }
1038 
1039   // If the loop contains a convergent operation, the prelude we'd add
1040   // to do the first few instructions before we hit the unrolled loop
1041   // is unsafe -- it adds a control-flow dependency to the convergent
1042   // operation.  Therefore restrict remainder loop (try unrollig without).
1043   //
1044   // TODO: This is quite conservative.  In practice, convergent_op()
1045   // is likely to be called unconditionally in the loop.  In this
1046   // case, the program would be ill-formed (on most architectures)
1047   // unless n were the same on all threads in a thread group.
1048   // Assuming n is the same on all threads, any kind of unrolling is
1049   // safe.  But currently llvm's notion of convergence isn't powerful
1050   // enough to express this.
1051   if (Convergent)
1052     UP.AllowRemainder = false;
1053 
1054   // Try to find the trip count upper bound if we cannot find the exact trip
1055   // count.
1056   bool MaxOrZero = false;
1057   if (!TripCount) {
1058     MaxTripCount = SE.getSmallConstantMaxTripCount(L);
1059     MaxOrZero = SE.isBackedgeTakenCountMaxOrZero(L);
1060     // We can unroll by the upper bound amount if it's generally allowed or if
1061     // we know that the loop is executed either the upper bound or zero times.
1062     // (MaxOrZero unrolling keeps only the first loop test, so the number of
1063     // loop tests remains the same compared to the non-unrolled version, whereas
1064     // the generic upper bound unrolling keeps all but the last loop test so the
1065     // number of loop tests goes up which may end up being worse on targets with
1066     // constrained branch predictor resources so is controlled by an option.)
1067     // In addition we only unroll small upper bounds.
1068     if (!(UP.UpperBound || MaxOrZero) || MaxTripCount > UnrollMaxUpperBound) {
1069       MaxTripCount = 0;
1070     }
1071   }
1072 
1073   // computeUnrollCount() decides whether it is beneficial to use upper bound to
1074   // fully unroll the loop.
1075   bool UseUpperBound = false;
1076   bool IsCountSetExplicitly = computeUnrollCount(
1077       L, TTI, DT, LI, SE, EphValues, &ORE, TripCount, MaxTripCount,
1078       TripMultiple, LoopSize, UP, UseUpperBound);
1079   if (!UP.Count)
1080     return LoopUnrollResult::Unmodified;
1081   // Unroll factor (Count) must be less or equal to TripCount.
1082   if (TripCount && UP.Count > TripCount)
1083     UP.Count = TripCount;
1084 
1085   // Save loop properties before it is transformed.
1086   MDNode *OrigLoopID = L->getLoopID();
1087 
1088   // Unroll the loop.
1089   Loop *RemainderLoop = nullptr;
1090   LoopUnrollResult UnrollResult = UnrollLoop(
1091       L, UP.Count, TripCount, UP.Force, UP.Runtime, UP.AllowExpensiveTripCount,
1092       UseUpperBound, MaxOrZero, TripMultiple, UP.PeelCount, UP.UnrollRemainder,
1093       ForgetAllSCEV, LI, &SE, &DT, &AC, &ORE, PreserveLCSSA, &RemainderLoop);
1094   if (UnrollResult == LoopUnrollResult::Unmodified)
1095     return LoopUnrollResult::Unmodified;
1096 
1097   if (RemainderLoop) {
1098     Optional<MDNode *> RemainderLoopID =
1099         makeFollowupLoopID(OrigLoopID, {LLVMLoopUnrollFollowupAll,
1100                                         LLVMLoopUnrollFollowupRemainder});
1101     if (RemainderLoopID.hasValue())
1102       RemainderLoop->setLoopID(RemainderLoopID.getValue());
1103   }
1104 
1105   if (UnrollResult != LoopUnrollResult::FullyUnrolled) {
1106     Optional<MDNode *> NewLoopID =
1107         makeFollowupLoopID(OrigLoopID, {LLVMLoopUnrollFollowupAll,
1108                                         LLVMLoopUnrollFollowupUnrolled});
1109     if (NewLoopID.hasValue()) {
1110       L->setLoopID(NewLoopID.getValue());
1111 
1112       // Do not setLoopAlreadyUnrolled if loop attributes have been specified
1113       // explicitly.
1114       return UnrollResult;
1115     }
1116   }
1117 
1118   // If loop has an unroll count pragma or unrolled by explicitly set count
1119   // mark loop as unrolled to prevent unrolling beyond that requested.
1120   // If the loop was peeled, we already "used up" the profile information
1121   // we had, so we don't want to unroll or peel again.
1122   if (UnrollResult != LoopUnrollResult::FullyUnrolled &&
1123       (IsCountSetExplicitly || UP.PeelCount))
1124     L->setLoopAlreadyUnrolled();
1125 
1126   return UnrollResult;
1127 }
1128 
1129 namespace {
1130 
1131 class LoopUnroll : public LoopPass {
1132 public:
1133   static char ID; // Pass ID, replacement for typeid
1134 
1135   int OptLevel;
1136 
1137   /// If false, use a cost model to determine whether unrolling of a loop is
1138   /// profitable. If true, only loops that explicitly request unrolling via
1139   /// metadata are considered. All other loops are skipped.
1140   bool OnlyWhenForced;
1141 
1142   /// If false, when SCEV is invalidated, only forget everything in the
1143   /// top-most loop (call forgetTopMostLoop), of the loop being processed.
1144   /// Otherwise, forgetAllLoops and rebuild when needed next.
1145   bool ForgetAllSCEV;
1146 
1147   Optional<unsigned> ProvidedCount;
1148   Optional<unsigned> ProvidedThreshold;
1149   Optional<bool> ProvidedAllowPartial;
1150   Optional<bool> ProvidedRuntime;
1151   Optional<bool> ProvidedUpperBound;
1152   Optional<bool> ProvidedAllowPeeling;
1153 
1154   LoopUnroll(int OptLevel = 2, bool OnlyWhenForced = false,
1155              bool ForgetAllSCEV = false, Optional<unsigned> Threshold = None,
1156              Optional<unsigned> Count = None,
1157              Optional<bool> AllowPartial = None, Optional<bool> Runtime = None,
1158              Optional<bool> UpperBound = None,
1159              Optional<bool> AllowPeeling = None)
1160       : LoopPass(ID), OptLevel(OptLevel), OnlyWhenForced(OnlyWhenForced),
1161         ForgetAllSCEV(ForgetAllSCEV), ProvidedCount(std::move(Count)),
1162         ProvidedThreshold(Threshold), ProvidedAllowPartial(AllowPartial),
1163         ProvidedRuntime(Runtime), ProvidedUpperBound(UpperBound),
1164         ProvidedAllowPeeling(AllowPeeling) {
1165     initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
1166   }
1167 
1168   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
1169     if (skipLoop(L))
1170       return false;
1171 
1172     Function &F = *L->getHeader()->getParent();
1173 
1174     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1175     LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1176     ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1177     const TargetTransformInfo &TTI =
1178         getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1179     auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1180     // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
1181     // pass.  Function analyses need to be preserved across loop transformations
1182     // but ORE cannot be preserved (see comment before the pass definition).
1183     OptimizationRemarkEmitter ORE(&F);
1184     bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
1185 
1186     LoopUnrollResult Result = tryToUnrollLoop(
1187         L, DT, LI, SE, TTI, AC, ORE, nullptr, nullptr,
1188         PreserveLCSSA, OptLevel, OnlyWhenForced,
1189         ForgetAllSCEV, ProvidedCount, ProvidedThreshold, ProvidedAllowPartial,
1190         ProvidedRuntime, ProvidedUpperBound, ProvidedAllowPeeling);
1191 
1192     if (Result == LoopUnrollResult::FullyUnrolled)
1193       LPM.markLoopAsDeleted(*L);
1194 
1195     return Result != LoopUnrollResult::Unmodified;
1196   }
1197 
1198   /// This transformation requires natural loop information & requires that
1199   /// loop preheaders be inserted into the CFG...
1200   void getAnalysisUsage(AnalysisUsage &AU) const override {
1201     AU.addRequired<AssumptionCacheTracker>();
1202     AU.addRequired<TargetTransformInfoWrapperPass>();
1203     // FIXME: Loop passes are required to preserve domtree, and for now we just
1204     // recreate dom info if anything gets unrolled.
1205     getLoopAnalysisUsage(AU);
1206   }
1207 };
1208 
1209 } // end anonymous namespace
1210 
1211 char LoopUnroll::ID = 0;
1212 
1213 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
1214 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1215 INITIALIZE_PASS_DEPENDENCY(LoopPass)
1216 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1217 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
1218 
1219 Pass *llvm::createLoopUnrollPass(int OptLevel, bool OnlyWhenForced,
1220                                  bool ForgetAllSCEV, int Threshold, int Count,
1221                                  int AllowPartial, int Runtime, int UpperBound,
1222                                  int AllowPeeling) {
1223   // TODO: It would make more sense for this function to take the optionals
1224   // directly, but that's dangerous since it would silently break out of tree
1225   // callers.
1226   return new LoopUnroll(
1227       OptLevel, OnlyWhenForced, ForgetAllSCEV,
1228       Threshold == -1 ? None : Optional<unsigned>(Threshold),
1229       Count == -1 ? None : Optional<unsigned>(Count),
1230       AllowPartial == -1 ? None : Optional<bool>(AllowPartial),
1231       Runtime == -1 ? None : Optional<bool>(Runtime),
1232       UpperBound == -1 ? None : Optional<bool>(UpperBound),
1233       AllowPeeling == -1 ? None : Optional<bool>(AllowPeeling));
1234 }
1235 
1236 Pass *llvm::createSimpleLoopUnrollPass(int OptLevel, bool OnlyWhenForced,
1237                                        bool ForgetAllSCEV) {
1238   return createLoopUnrollPass(OptLevel, OnlyWhenForced, ForgetAllSCEV, -1, -1,
1239                               0, 0, 0, 0);
1240 }
1241 
1242 PreservedAnalyses LoopFullUnrollPass::run(Loop &L, LoopAnalysisManager &AM,
1243                                           LoopStandardAnalysisResults &AR,
1244                                           LPMUpdater &Updater) {
1245   const auto &FAM =
1246       AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
1247   Function *F = L.getHeader()->getParent();
1248 
1249   auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
1250   // FIXME: This should probably be optional rather than required.
1251   if (!ORE)
1252     report_fatal_error(
1253         "LoopFullUnrollPass: OptimizationRemarkEmitterAnalysis not "
1254         "cached at a higher level");
1255 
1256   // Keep track of the previous loop structure so we can identify new loops
1257   // created by unrolling.
1258   Loop *ParentL = L.getParentLoop();
1259   SmallPtrSet<Loop *, 4> OldLoops;
1260   if (ParentL)
1261     OldLoops.insert(ParentL->begin(), ParentL->end());
1262   else
1263     OldLoops.insert(AR.LI.begin(), AR.LI.end());
1264 
1265   std::string LoopName = L.getName();
1266 
1267   bool Changed =
1268       tryToUnrollLoop(&L, AR.DT, &AR.LI, AR.SE, AR.TTI, AR.AC, *ORE,
1269                       /*BFI*/ nullptr, /*PSI*/ nullptr,
1270                       /*PreserveLCSSA*/ true, OptLevel, OnlyWhenForced,
1271                       /*ForgetAllSCEV*/ false, /*Count*/ None,
1272                       /*Threshold*/ None, /*AllowPartial*/ false,
1273                       /*Runtime*/ false, /*UpperBound*/ false,
1274                       /*AllowPeeling*/ false) != LoopUnrollResult::Unmodified;
1275   if (!Changed)
1276     return PreservedAnalyses::all();
1277 
1278   // The parent must not be damaged by unrolling!
1279 #ifndef NDEBUG
1280   if (ParentL)
1281     ParentL->verifyLoop();
1282 #endif
1283 
1284   // Unrolling can do several things to introduce new loops into a loop nest:
1285   // - Full unrolling clones child loops within the current loop but then
1286   //   removes the current loop making all of the children appear to be new
1287   //   sibling loops.
1288   //
1289   // When a new loop appears as a sibling loop after fully unrolling,
1290   // its nesting structure has fundamentally changed and we want to revisit
1291   // it to reflect that.
1292   //
1293   // When unrolling has removed the current loop, we need to tell the
1294   // infrastructure that it is gone.
1295   //
1296   // Finally, we support a debugging/testing mode where we revisit child loops
1297   // as well. These are not expected to require further optimizations as either
1298   // they or the loop they were cloned from have been directly visited already.
1299   // But the debugging mode allows us to check this assumption.
1300   bool IsCurrentLoopValid = false;
1301   SmallVector<Loop *, 4> SibLoops;
1302   if (ParentL)
1303     SibLoops.append(ParentL->begin(), ParentL->end());
1304   else
1305     SibLoops.append(AR.LI.begin(), AR.LI.end());
1306   erase_if(SibLoops, [&](Loop *SibLoop) {
1307     if (SibLoop == &L) {
1308       IsCurrentLoopValid = true;
1309       return true;
1310     }
1311 
1312     // Otherwise erase the loop from the list if it was in the old loops.
1313     return OldLoops.count(SibLoop) != 0;
1314   });
1315   Updater.addSiblingLoops(SibLoops);
1316 
1317   if (!IsCurrentLoopValid) {
1318     Updater.markLoopAsDeleted(L, LoopName);
1319   } else {
1320     // We can only walk child loops if the current loop remained valid.
1321     if (UnrollRevisitChildLoops) {
1322       // Walk *all* of the child loops.
1323       SmallVector<Loop *, 4> ChildLoops(L.begin(), L.end());
1324       Updater.addChildLoops(ChildLoops);
1325     }
1326   }
1327 
1328   return getLoopPassPreservedAnalyses();
1329 }
1330 
1331 template <typename RangeT>
1332 static SmallVector<Loop *, 8> appendLoopsToWorklist(RangeT &&Loops) {
1333   SmallVector<Loop *, 8> Worklist;
1334   // We use an internal worklist to build up the preorder traversal without
1335   // recursion.
1336   SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist;
1337 
1338   for (Loop *RootL : Loops) {
1339     assert(PreOrderLoops.empty() && "Must start with an empty preorder walk.");
1340     assert(PreOrderWorklist.empty() &&
1341            "Must start with an empty preorder walk worklist.");
1342     PreOrderWorklist.push_back(RootL);
1343     do {
1344       Loop *L = PreOrderWorklist.pop_back_val();
1345       PreOrderWorklist.append(L->begin(), L->end());
1346       PreOrderLoops.push_back(L);
1347     } while (!PreOrderWorklist.empty());
1348 
1349     Worklist.append(PreOrderLoops.begin(), PreOrderLoops.end());
1350     PreOrderLoops.clear();
1351   }
1352   return Worklist;
1353 }
1354 
1355 PreservedAnalyses LoopUnrollPass::run(Function &F,
1356                                       FunctionAnalysisManager &AM) {
1357   auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
1358   auto &LI = AM.getResult<LoopAnalysis>(F);
1359   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
1360   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1361   auto &AC = AM.getResult<AssumptionAnalysis>(F);
1362   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1363 
1364   LoopAnalysisManager *LAM = nullptr;
1365   if (auto *LAMProxy = AM.getCachedResult<LoopAnalysisManagerFunctionProxy>(F))
1366     LAM = &LAMProxy->getManager();
1367 
1368   const ModuleAnalysisManager &MAM =
1369       AM.getResult<ModuleAnalysisManagerFunctionProxy>(F).getManager();
1370   ProfileSummaryInfo *PSI =
1371       MAM.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
1372   auto *BFI = (PSI && PSI->hasProfileSummary()) ?
1373       &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;
1374 
1375   bool Changed = false;
1376 
1377   // The unroller requires loops to be in simplified form, and also needs LCSSA.
1378   // Since simplification may add new inner loops, it has to run before the
1379   // legality and profitability checks. This means running the loop unroller
1380   // will simplify all loops, regardless of whether anything end up being
1381   // unrolled.
1382   for (auto &L : LI) {
1383     Changed |= simplifyLoop(L, &DT, &LI, &SE, &AC, false /* PreserveLCSSA */);
1384     Changed |= formLCSSARecursively(*L, DT, &LI, &SE);
1385   }
1386 
1387   SmallVector<Loop *, 8> Worklist = appendLoopsToWorklist(LI);
1388 
1389   while (!Worklist.empty()) {
1390     // Because the LoopInfo stores the loops in RPO, we walk the worklist
1391     // from back to front so that we work forward across the CFG, which
1392     // for unrolling is only needed to get optimization remarks emitted in
1393     // a forward order.
1394     Loop &L = *Worklist.pop_back_val();
1395 #ifndef NDEBUG
1396     Loop *ParentL = L.getParentLoop();
1397 #endif
1398 
1399     // Check if the profile summary indicates that the profiled application
1400     // has a huge working set size, in which case we disable peeling to avoid
1401     // bloating it further.
1402     Optional<bool> LocalAllowPeeling = UnrollOpts.AllowPeeling;
1403     if (PSI && PSI->hasHugeWorkingSetSize())
1404       LocalAllowPeeling = false;
1405     std::string LoopName = L.getName();
1406     // The API here is quite complex to call and we allow to select some
1407     // flavors of unrolling during construction time (by setting UnrollOpts).
1408     LoopUnrollResult Result = tryToUnrollLoop(
1409         &L, DT, &LI, SE, TTI, AC, ORE, BFI, PSI,
1410         /*PreserveLCSSA*/ true, UnrollOpts.OptLevel, UnrollOpts.OnlyWhenForced,
1411         /*ForgetAllSCEV*/ false, /*Count*/ None,
1412         /*Threshold*/ None, UnrollOpts.AllowPartial, UnrollOpts.AllowRuntime,
1413         UnrollOpts.AllowUpperBound, LocalAllowPeeling);
1414     Changed |= Result != LoopUnrollResult::Unmodified;
1415 
1416     // The parent must not be damaged by unrolling!
1417 #ifndef NDEBUG
1418     if (Result != LoopUnrollResult::Unmodified && ParentL)
1419       ParentL->verifyLoop();
1420 #endif
1421 
1422     // Clear any cached analysis results for L if we removed it completely.
1423     if (LAM && Result == LoopUnrollResult::FullyUnrolled)
1424       LAM->clear(L, LoopName);
1425   }
1426 
1427   if (!Changed)
1428     return PreservedAnalyses::all();
1429 
1430   return getLoopPassPreservedAnalyses();
1431 }
1432