1 //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/Analysis/AssumptionCache.h"
18 #include "llvm/Analysis/CodeMetrics.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/LoopPass.h"
21 #include "llvm/Analysis/ScalarEvolution.h"
22 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DiagnosticInfo.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/InstVisitor.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Transforms/Utils/UnrollLoop.h"
38 #define DEBUG_TYPE "loop-unroll"
40 static cl::opt<unsigned>
41 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
42 cl::desc("The cut-off point for automatic loop unrolling"));
44 static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
45 "unroll-max-iteration-count-to-analyze", cl::init(0), cl::Hidden,
46 cl::desc("Don't allow loop unrolling to simulate more than this number of"
47 "iterations when checking full unroll profitability"));
49 static cl::opt<unsigned> UnrollMinPercentOfOptimized(
50 "unroll-percent-of-optimized-for-complete-unroll", cl::init(20), cl::Hidden,
51 cl::desc("If complete unrolling could trigger further optimizations, and, "
52 "by that, remove the given percent of instructions, perform the "
53 "complete unroll even if it's beyond the threshold"));
55 static cl::opt<unsigned> UnrollAbsoluteThreshold(
56 "unroll-absolute-threshold", cl::init(2000), cl::Hidden,
57 cl::desc("Don't unroll if the unrolled size is bigger than this threshold,"
58 " even if we can remove big portion of instructions later."));
60 static cl::opt<unsigned>
61 UnrollCount("unroll-count", cl::init(0), cl::Hidden,
62 cl::desc("Use this unroll count for all loops including those with "
63 "unroll_count pragma values, for testing purposes"));
66 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
67 cl::desc("Allows loops to be partially unrolled until "
68 "-unroll-threshold loop size is reached."));
71 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
72 cl::desc("Unroll loops with run-time trip counts"));
74 static cl::opt<unsigned>
75 PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
76 cl::desc("Unrolled size limit for loops with an unroll(full) or "
77 "unroll_count pragma."));
80 class LoopUnroll : public LoopPass {
82 static char ID; // Pass ID, replacement for typeid
83 LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
84 CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
85 CurrentAbsoluteThreshold = UnrollAbsoluteThreshold;
86 CurrentMinPercentOfOptimized = UnrollMinPercentOfOptimized;
87 CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
88 CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
89 CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
91 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
92 UserAbsoluteThreshold = (UnrollAbsoluteThreshold.getNumOccurrences() > 0);
93 UserPercentOfOptimized =
94 (UnrollMinPercentOfOptimized.getNumOccurrences() > 0);
95 UserAllowPartial = (P != -1) ||
96 (UnrollAllowPartial.getNumOccurrences() > 0);
97 UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
98 UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
100 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
103 /// A magic value for use with the Threshold parameter to indicate
104 /// that the loop unroll should be performed regardless of how much
105 /// code expansion would result.
106 static const unsigned NoThreshold = UINT_MAX;
108 // Threshold to use when optsize is specified (and there is no
109 // explicit -unroll-threshold).
110 static const unsigned OptSizeUnrollThreshold = 50;
112 // Default unroll count for loops with run-time trip count if
113 // -unroll-count is not set
114 static const unsigned UnrollRuntimeCount = 8;
116 unsigned CurrentCount;
117 unsigned CurrentThreshold;
118 unsigned CurrentAbsoluteThreshold;
119 unsigned CurrentMinPercentOfOptimized;
120 bool CurrentAllowPartial;
122 bool UserCount; // CurrentCount is user-specified.
123 bool UserThreshold; // CurrentThreshold is user-specified.
124 bool UserAbsoluteThreshold; // CurrentAbsoluteThreshold is
126 bool UserPercentOfOptimized; // CurrentMinPercentOfOptimized is
128 bool UserAllowPartial; // CurrentAllowPartial is user-specified.
129 bool UserRuntime; // CurrentRuntime is user-specified.
131 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
133 /// This transformation requires natural loop information & requires that
134 /// loop preheaders be inserted into the CFG...
136 void getAnalysisUsage(AnalysisUsage &AU) const override {
137 AU.addRequired<AssumptionCacheTracker>();
138 AU.addRequired<LoopInfoWrapperPass>();
139 AU.addPreserved<LoopInfoWrapperPass>();
140 AU.addRequiredID(LoopSimplifyID);
141 AU.addPreservedID(LoopSimplifyID);
142 AU.addRequiredID(LCSSAID);
143 AU.addPreservedID(LCSSAID);
144 AU.addRequired<ScalarEvolution>();
145 AU.addPreserved<ScalarEvolution>();
146 AU.addRequired<TargetTransformInfoWrapperPass>();
147 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
148 // If loop unroll does not preserve dom info then LCSSA pass on next
149 // loop will receive invalid dom info.
150 // For now, recreate dom info, if loop is unrolled.
151 AU.addPreserved<DominatorTreeWrapperPass>();
154 // Fill in the UnrollingPreferences parameter with values from the
155 // TargetTransformationInfo.
156 void getUnrollingPreferences(Loop *L, const TargetTransformInfo &TTI,
157 TargetTransformInfo::UnrollingPreferences &UP) {
158 UP.Threshold = CurrentThreshold;
159 UP.AbsoluteThreshold = CurrentAbsoluteThreshold;
160 UP.MinPercentOfOptimized = CurrentMinPercentOfOptimized;
161 UP.OptSizeThreshold = OptSizeUnrollThreshold;
162 UP.PartialThreshold = CurrentThreshold;
163 UP.PartialOptSizeThreshold = OptSizeUnrollThreshold;
164 UP.Count = CurrentCount;
165 UP.MaxCount = UINT_MAX;
166 UP.Partial = CurrentAllowPartial;
167 UP.Runtime = CurrentRuntime;
168 UP.AllowExpensiveTripCount = false;
169 TTI.getUnrollingPreferences(L, UP);
172 // Select and return an unroll count based on parameters from
173 // user, unroll preferences, unroll pragmas, or a heuristic.
174 // SetExplicitly is set to true if the unroll count is is set by
175 // the user or a pragma rather than selected heuristically.
177 selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
178 unsigned PragmaCount,
179 const TargetTransformInfo::UnrollingPreferences &UP,
180 bool &SetExplicitly);
182 // Select threshold values used to limit unrolling based on a
183 // total unrolled size. Parameters Threshold and PartialThreshold
184 // are set to the maximum unrolled size for fully and partially
185 // unrolled loops respectively.
186 void selectThresholds(const Loop *L, bool HasPragma,
187 const TargetTransformInfo::UnrollingPreferences &UP,
188 unsigned &Threshold, unsigned &PartialThreshold,
189 unsigned &AbsoluteThreshold,
190 unsigned &PercentOfOptimizedForCompleteUnroll) {
191 // Determine the current unrolling threshold. While this is
192 // normally set from UnrollThreshold, it is overridden to a
193 // smaller value if the current function is marked as
194 // optimize-for-size, and the unroll threshold was not user
196 Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
197 PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold;
198 AbsoluteThreshold = UserAbsoluteThreshold ? CurrentAbsoluteThreshold
199 : UP.AbsoluteThreshold;
200 PercentOfOptimizedForCompleteUnroll = UserPercentOfOptimized
201 ? CurrentMinPercentOfOptimized
202 : UP.MinPercentOfOptimized;
204 if (!UserThreshold &&
205 L->getHeader()->getParent()->hasFnAttribute(
206 Attribute::OptimizeForSize)) {
207 Threshold = UP.OptSizeThreshold;
208 PartialThreshold = UP.PartialOptSizeThreshold;
211 // If the loop has an unrolling pragma, we want to be more
212 // aggressive with unrolling limits. Set thresholds to at
213 // least the PragmaTheshold value which is larger than the
215 if (Threshold != NoThreshold)
216 Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold);
217 if (PartialThreshold != NoThreshold)
219 std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold);
222 bool canUnrollCompletely(Loop *L, unsigned Threshold,
223 unsigned AbsoluteThreshold, uint64_t UnrolledSize,
224 unsigned NumberOfOptimizedInstructions,
225 unsigned PercentOfOptimizedForCompleteUnroll);
229 char LoopUnroll::ID = 0;
230 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
231 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
232 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
233 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
234 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
235 INITIALIZE_PASS_DEPENDENCY(LCSSA)
236 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
237 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
239 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
241 return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
244 Pass *llvm::createSimpleLoopUnrollPass() {
245 return llvm::createLoopUnrollPass(-1, -1, 0, 0);
249 /// \brief SCEV expressions visitor used for finding expressions that would
250 /// become constants if the loop L is unrolled.
251 struct FindConstantPointers {
252 /// \brief Shows whether the expression is ConstAddress+Constant or not.
253 bool IndexIsConstant;
255 /// \brief Used for filtering out SCEV expressions with two or more AddRec
258 /// Used to filter out complicated SCEV expressions, having several AddRec
259 /// sub-expressions. We don't handle them, because unrolling one loop
260 /// would help to replace only one of these inductions with a constant, and
261 /// consequently, the expression would remain non-constant.
264 /// \brief If the SCEV expression becomes ConstAddress+Constant, this value
265 /// holds ConstAddress. Otherwise, it's nullptr.
268 /// \brief The loop, which we try to completely unroll.
273 FindConstantPointers(const Loop *L, ScalarEvolution &SE)
274 : IndexIsConstant(true), HaveSeenAR(false), BaseAddress(nullptr),
277 /// Examine the given expression S and figure out, if it can be a part of an
278 /// expression, that could become a constant after the loop is unrolled.
279 /// The routine sets IndexIsConstant and HaveSeenAR according to the analysis
281 /// \returns true if we need to examine subexpressions, and false otherwise.
282 bool follow(const SCEV *S) {
283 if (const SCEVUnknown *SC = dyn_cast<SCEVUnknown>(S)) {
284 // We've reached the leaf node of SCEV, it's most probably just a
286 // If it's the only one SCEV-subexpression, then it might be a base
287 // address of an index expression.
288 // If we've already recorded base address, then just give up on this SCEV
289 // - it's too complicated.
291 IndexIsConstant = false;
294 BaseAddress = SC->getValue();
297 if (isa<SCEVConstant>(S))
299 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
300 // If the current SCEV expression is AddRec, and its loop isn't the loop
301 // we are about to unroll, then we won't get a constant address after
302 // unrolling, and thus, won't be able to eliminate the load.
303 if (AR->getLoop() != L) {
304 IndexIsConstant = false;
307 // We don't handle multiple AddRecs here, so give up in this case.
309 IndexIsConstant = false;
315 // Continue traversal.
318 bool isDone() const { return !IndexIsConstant; }
320 } // End anonymous namespace.
323 /// \brief Struct to represent a GEP whose start and step are known fixed
324 /// offsets from a base address due to SCEV's analysis.
325 struct SCEVGEPDescriptor {
330 } // End anonymous namespace.
332 /// \brief Build a cache of all the GEP instructions which SCEV can describe.
334 /// Visit all GEPs in the loop and find those which after complete loop
335 /// unrolling would become a constant, or BaseAddress+Constant. For those where
336 /// we can identify small constant starts and steps from a base address, return
337 /// a map from the GEP to the base, start, and step relevant for that GEP. This
338 /// is essentially a simplified and fast to query form of the SCEV analysis
339 /// which we can afford to look into repeatedly for different iterations of the
341 static SmallDenseMap<Value *, SCEVGEPDescriptor>
342 buildSCEVGEPCache(const Loop &L, ScalarEvolution &SE) {
343 SmallDenseMap<Value *, SCEVGEPDescriptor> Cache;
345 for (auto BB : L.getBlocks()) {
346 for (Instruction &I : *BB) {
347 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
348 Value *V = cast<Value>(GEP);
349 if (!SE.isSCEVable(V->getType()))
351 const SCEV *S = SE.getSCEV(V);
353 // FIXME: It'd be nice if the worklist and set used by the
354 // SCEVTraversal could be re-used between loop iterations, but the
355 // interface doesn't support that. There is no way to clear the visited
356 // sets between uses.
357 FindConstantPointers Visitor(&L, SE);
358 SCEVTraversal<FindConstantPointers> T(Visitor);
360 // Try to find (BaseAddress+Step+Offset) tuple.
361 // If succeeded, save it to the cache - it might help in folding
364 if (!Visitor.IndexIsConstant || !Visitor.BaseAddress)
367 const SCEV *BaseAddrSE = SE.getSCEV(Visitor.BaseAddress);
368 if (BaseAddrSE->getType() != S->getType())
370 const SCEV *OffSE = SE.getMinusSCEV(S, BaseAddrSE);
371 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OffSE);
376 const SCEVConstant *StepSE =
377 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE));
378 const SCEVConstant *StartSE = dyn_cast<SCEVConstant>(AR->getStart());
379 if (!StepSE || !StartSE)
382 // Check and skip caching if doing so would require lots of bits to
384 APInt Start = StartSE->getValue()->getValue();
385 APInt Step = StepSE->getValue()->getValue();
386 if (Start.getActiveBits() > 32 || Step.getActiveBits() > 32)
389 // We found a cacheable SCEV model for the GEP.
390 Cache[V] = {Visitor.BaseAddress,
391 (unsigned)Start.getLimitedValue(),
392 (unsigned)Step.getLimitedValue()};
401 // This class is used to get an estimate of the optimization effects that we
402 // could get from complete loop unrolling. It comes from the fact that some
403 // loads might be replaced with concrete constant values and that could trigger
404 // a chain of instruction simplifications.
406 // E.g. we might have:
407 // int a[] = {0, 1, 0};
409 // for (i = 0; i < 3; i ++)
411 // If we completely unroll the loop, we would get:
412 // v = b[0]*a[0] + b[1]*a[1] + b[2]*a[2]
413 // Which then will be simplified to:
414 // v = b[0]* 0 + b[1]* 1 + b[2]* 0
417 class UnrolledInstAnalyzer : private InstVisitor<UnrolledInstAnalyzer, bool> {
418 typedef InstVisitor<UnrolledInstAnalyzer, bool> Base;
419 friend class InstVisitor<UnrolledInstAnalyzer, bool>;
422 UnrolledInstAnalyzer(unsigned Iteration,
423 DenseMap<Value *, Constant *> &SimplifiedValues,
424 SmallDenseMap<Value *, SCEVGEPDescriptor> &SCEVGEPCache)
425 : Iteration(Iteration), SimplifiedValues(SimplifiedValues),
426 SCEVGEPCache(SCEVGEPCache) {}
428 // Allow access to the initial visit method.
432 /// \brief Number of currently simulated iteration.
434 /// If an expression is ConstAddress+Constant, then the Constant is
435 /// Start + Iteration*Step, where Start and Step could be obtained from
439 // While we walk the loop instructions, we we build up and maintain a mapping
440 // of simplified values specific to this iteration. The idea is to propagate
441 // any special information we have about loads that can be replaced with
442 // constants after complete unrolling, and account for likely simplifications
444 DenseMap<Value *, Constant *> &SimplifiedValues;
446 // To avoid requesting SCEV info on every iteration, request it once, and
447 // for each value that would become ConstAddress+Constant after loop
448 // unrolling, save the corresponding data.
449 SmallDenseMap<Value *, SCEVGEPDescriptor> &SCEVGEPCache;
451 /// Base case for the instruction visitor.
452 bool visitInstruction(Instruction &I) { return false; };
454 /// TODO: Add visitors for other instruction types, e.g. ZExt, SExt.
456 /// Try to simplify binary operator I.
458 /// TODO: Probaly it's worth to hoist the code for estimating the
459 /// simplifications effects to a separate class, since we have a very similar
460 /// code in InlineCost already.
461 bool visitBinaryOperator(BinaryOperator &I) {
462 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
463 if (!isa<Constant>(LHS))
464 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
466 if (!isa<Constant>(RHS))
467 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
469 Value *SimpleV = nullptr;
470 const DataLayout &DL = I.getModule()->getDataLayout();
471 if (auto FI = dyn_cast<FPMathOperator>(&I))
473 SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL);
475 SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
477 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
478 SimplifiedValues[&I] = C;
483 /// Try to fold load I.
484 bool visitLoad(LoadInst &I) {
485 Value *AddrOp = I.getPointerOperand();
486 if (!isa<Constant>(AddrOp))
487 if (Constant *SimplifiedAddrOp = SimplifiedValues.lookup(AddrOp))
488 AddrOp = SimplifiedAddrOp;
490 auto It = SCEVGEPCache.find(AddrOp);
491 if (It == SCEVGEPCache.end())
493 SCEVGEPDescriptor GEPDesc = It->second;
495 auto GV = dyn_cast<GlobalVariable>(GEPDesc.BaseAddr);
496 // We're only interested in loads that can be completely folded to a
498 if (!GV || !GV->hasInitializer())
501 ConstantDataSequential *CDS =
502 dyn_cast<ConstantDataSequential>(GV->getInitializer());
506 // This calculation should never overflow because we bound Iteration quite
507 // low and both the start and step are 32-bit integers. We use signed
508 // integers so that UBSan will catch if a bug sneaks into the code.
509 int ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U;
510 int64_t Index = ((int64_t)GEPDesc.Start +
511 (int64_t)GEPDesc.Step * (int64_t)Iteration) /
513 if (Index >= CDS->getNumElements()) {
514 // FIXME: For now we conservatively ignore out of bound accesses, but
515 // we're allowed to perform the optimization in this case.
519 Constant *CV = CDS->getElementAsConstant(Index);
520 assert(CV && "Constant expected.");
521 SimplifiedValues[&I] = CV;
530 struct EstimatedUnrollCost {
531 /// \brief Count the number of optimized instructions.
532 unsigned NumberOfOptimizedInstructions;
534 /// \brief Count the total number of instructions.
535 unsigned UnrolledLoopSize;
539 /// \brief Figure out if the loop is worth full unrolling.
541 /// Complete loop unrolling can make some loads constant, and we need to know
542 /// if that would expose any further optimization opportunities. This routine
543 /// estimates this optimization. It assigns computed number of instructions,
544 /// that potentially might be optimized away, to
545 /// NumberOfOptimizedInstructions, and total number of instructions to
546 /// UnrolledLoopSize (not counting blocks that won't be reached, if we were
547 /// able to compute the condition).
548 /// \returns false if we can't analyze the loop, or if we discovered that
549 /// unrolling won't give anything. Otherwise, returns true.
550 Optional<EstimatedUnrollCost>
551 analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, ScalarEvolution &SE,
552 const TargetTransformInfo &TTI,
553 unsigned MaxUnrolledLoopSize) {
554 // We want to be able to scale offsets by the trip count and add more offsets
555 // to them without checking for overflows, and we already don't want to
556 // analyze *massive* trip counts, so we force the max to be reasonably small.
557 assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) &&
558 "The unroll iterations max is too large!");
560 // Don't simulate loops with a big or unknown tripcount
561 if (!UnrollMaxIterationsCountToAnalyze || !TripCount ||
562 TripCount > UnrollMaxIterationsCountToAnalyze)
565 // To avoid compute SCEV-expressions on every iteration, compute them once
566 // and store interesting to us in SCEVGEPCache.
567 SmallDenseMap<Value *, SCEVGEPDescriptor> SCEVGEPCache =
568 buildSCEVGEPCache(*L, SE);
570 SmallSetVector<BasicBlock *, 16> BBWorklist;
571 DenseMap<Value *, Constant *> SimplifiedValues;
573 unsigned NumberOfOptimizedInstructions = 0;
574 unsigned UnrolledLoopSize = 0;
576 // Simulate execution of each iteration of the loop counting instructions,
577 // which would be simplified.
578 // Since the same load will take different values on different iterations,
579 // we literally have to go through all loop's iterations.
580 for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
581 SimplifiedValues.clear();
582 UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SCEVGEPCache);
585 BBWorklist.insert(L->getHeader());
586 // Note that we *must not* cache the size, this loop grows the worklist.
587 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
588 BasicBlock *BB = BBWorklist[Idx];
590 // Visit all instructions in the given basic block and try to simplify
591 // it. We don't change the actual IR, just count optimization
593 for (Instruction &I : *BB) {
594 UnrolledLoopSize += TTI.getUserCost(&I);
596 // Visit the instruction to analyze its loop cost after unrolling,
597 // and if the visitor returns true, then we can optimize this
599 if (Analyzer.visit(I))
600 NumberOfOptimizedInstructions += TTI.getUserCost(&I);
602 // If unrolled body turns out to be too big, bail out.
603 if (UnrolledLoopSize - NumberOfOptimizedInstructions >
608 // Add BB's successors to the worklist.
609 for (BasicBlock *Succ : successors(BB))
610 if (L->contains(Succ))
611 BBWorklist.insert(Succ);
614 // If we found no optimization opportunities on the first iteration, we
615 // won't find them on later ones too.
616 if (!NumberOfOptimizedInstructions)
619 return {{NumberOfOptimizedInstructions, UnrolledLoopSize}};
622 /// ApproximateLoopSize - Approximate the size of the loop.
623 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
624 bool &NotDuplicatable,
625 const TargetTransformInfo &TTI,
626 AssumptionCache *AC) {
627 SmallPtrSet<const Value *, 32> EphValues;
628 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
631 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
633 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
634 NumCalls = Metrics.NumInlineCandidates;
635 NotDuplicatable = Metrics.notDuplicatable;
637 unsigned LoopSize = Metrics.NumInsts;
639 // Don't allow an estimate of size zero. This would allows unrolling of loops
640 // with huge iteration counts, which is a compile time problem even if it's
641 // not a problem for code quality. Also, the code using this size may assume
642 // that each loop has at least three instructions (likely a conditional
643 // branch, a comparison feeding that branch, and some kind of loop increment
644 // feeding that comparison instruction).
645 LoopSize = std::max(LoopSize, 3u);
650 // Returns the loop hint metadata node with the given name (for example,
651 // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
653 static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
654 if (MDNode *LoopID = L->getLoopID())
655 return GetUnrollMetadata(LoopID, Name);
659 // Returns true if the loop has an unroll(full) pragma.
660 static bool HasUnrollFullPragma(const Loop *L) {
661 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
664 // Returns true if the loop has an unroll(disable) pragma.
665 static bool HasUnrollDisablePragma(const Loop *L) {
666 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
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");
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");
679 assert(MD->getNumOperands() == 2 &&
680 "Unroll count hint metadata should have two operands.");
682 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
683 assert(Count >= 1 && "Unroll count must be positive.");
689 // Remove existing unroll metadata and add unroll disable metadata to
690 // indicate the loop has already been unrolled. This prevents a loop
691 // from being unrolled more than is directed by a pragma if the loop
692 // unrolling pass is run more than once (which it generally is).
693 static void SetLoopAlreadyUnrolled(Loop *L) {
694 MDNode *LoopID = L->getLoopID();
697 // First remove any existing loop unrolling metadata.
698 SmallVector<Metadata *, 4> MDs;
699 // Reserve first location for self reference to the LoopID metadata node.
700 MDs.push_back(nullptr);
701 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
702 bool IsUnrollMetadata = false;
703 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
705 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
706 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
708 if (!IsUnrollMetadata)
709 MDs.push_back(LoopID->getOperand(i));
712 // Add unroll(disable) metadata to disable future unrolling.
713 LLVMContext &Context = L->getHeader()->getContext();
714 SmallVector<Metadata *, 1> DisableOperands;
715 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
716 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
717 MDs.push_back(DisableNode);
719 MDNode *NewLoopID = MDNode::get(Context, MDs);
720 // Set operand 0 to refer to the loop id itself.
721 NewLoopID->replaceOperandWith(0, NewLoopID);
722 L->setLoopID(NewLoopID);
725 bool LoopUnroll::canUnrollCompletely(
726 Loop *L, unsigned Threshold, unsigned AbsoluteThreshold,
727 uint64_t UnrolledSize, unsigned NumberOfOptimizedInstructions,
728 unsigned PercentOfOptimizedForCompleteUnroll) {
730 if (Threshold == NoThreshold) {
731 DEBUG(dbgs() << " Can fully unroll, because no threshold is set.\n");
735 if (UnrolledSize <= Threshold) {
736 DEBUG(dbgs() << " Can fully unroll, because unrolled size: "
737 << UnrolledSize << "<" << Threshold << "\n");
741 assert(UnrolledSize && "UnrolledSize can't be 0 at this point.");
742 unsigned PercentOfOptimizedInstructions =
743 (uint64_t)NumberOfOptimizedInstructions * 100ull / UnrolledSize;
745 if (UnrolledSize <= AbsoluteThreshold &&
746 PercentOfOptimizedInstructions >= PercentOfOptimizedForCompleteUnroll) {
747 DEBUG(dbgs() << " Can fully unroll, because unrolling will help removing "
748 << PercentOfOptimizedInstructions
749 << "% instructions (threshold: "
750 << PercentOfOptimizedForCompleteUnroll << "%)\n");
751 DEBUG(dbgs() << " Unrolled size (" << UnrolledSize
752 << ") is less than the threshold (" << AbsoluteThreshold
757 DEBUG(dbgs() << " Too large to fully unroll:\n");
758 DEBUG(dbgs() << " Unrolled size: " << UnrolledSize << "\n");
759 DEBUG(dbgs() << " Estimated number of optimized instructions: "
760 << NumberOfOptimizedInstructions << "\n");
761 DEBUG(dbgs() << " Absolute threshold: " << AbsoluteThreshold << "\n");
762 DEBUG(dbgs() << " Minimum percent of removed instructions: "
763 << PercentOfOptimizedForCompleteUnroll << "\n");
764 DEBUG(dbgs() << " Threshold for small loops: " << Threshold << "\n");
768 unsigned LoopUnroll::selectUnrollCount(
769 const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
770 unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
771 bool &SetExplicitly) {
772 SetExplicitly = true;
774 // User-specified count (either as a command-line option or
775 // constructor parameter) has highest precedence.
776 unsigned Count = UserCount ? CurrentCount : 0;
778 // If there is no user-specified count, unroll pragmas have the next
779 // highest precendence.
783 } else if (PragmaFullUnroll) {
792 SetExplicitly = false;
794 // Runtime trip count.
795 Count = UnrollRuntimeCount;
797 // Conservative heuristic: if we know the trip count, see if we can
798 // completely unroll (subject to the threshold, checked below); otherwise
799 // try to find greatest modulo of the trip count which is still under
803 if (TripCount && Count > TripCount)
808 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
809 if (skipOptnoneFunction(L))
812 Function &F = *L->getHeader()->getParent();
814 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
815 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
816 const TargetTransformInfo &TTI =
817 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
818 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
820 BasicBlock *Header = L->getHeader();
821 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
822 << "] Loop %" << Header->getName() << "\n");
824 if (HasUnrollDisablePragma(L)) {
827 bool PragmaFullUnroll = HasUnrollFullPragma(L);
828 unsigned PragmaCount = UnrollCountPragmaValue(L);
829 bool HasPragma = PragmaFullUnroll || PragmaCount > 0;
831 TargetTransformInfo::UnrollingPreferences UP;
832 getUnrollingPreferences(L, TTI, UP);
834 // Find trip count and trip multiple if count is not available
835 unsigned TripCount = 0;
836 unsigned TripMultiple = 1;
837 // If there are multiple exiting blocks but one of them is the latch, use the
838 // latch for the trip count estimation. Otherwise insist on a single exiting
839 // block for the trip count estimation.
840 BasicBlock *ExitingBlock = L->getLoopLatch();
841 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
842 ExitingBlock = L->getExitingBlock();
844 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
845 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
848 // Select an initial unroll count. This may be reduced later based
849 // on size thresholds.
850 bool CountSetExplicitly;
851 unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
852 PragmaCount, UP, CountSetExplicitly);
854 unsigned NumInlineCandidates;
855 bool notDuplicatable;
857 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC);
858 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
860 // When computing the unrolled size, note that the conditional branch on the
861 // backedge and the comparison feeding it are not replicated like the rest of
862 // the loop body (which is why 2 is subtracted).
863 uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2;
864 if (notDuplicatable) {
865 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
866 << " instructions.\n");
869 if (NumInlineCandidates != 0) {
870 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
874 unsigned Threshold, PartialThreshold;
875 unsigned AbsoluteThreshold, PercentOfOptimizedForCompleteUnroll;
876 selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold,
877 AbsoluteThreshold, PercentOfOptimizedForCompleteUnroll);
879 // Given Count, TripCount and thresholds determine the type of
880 // unrolling which is to be performed.
881 enum { Full = 0, Partial = 1, Runtime = 2 };
883 if (TripCount && Count == TripCount) {
885 // If the loop is really small, we don't need to run an expensive analysis.
886 if (canUnrollCompletely(
887 L, Threshold, AbsoluteThreshold,
888 UnrolledSize, 0, 100)) {
891 // The loop isn't that small, but we still can fully unroll it if that
892 // helps to remove a significant number of instructions.
893 // To check that, run additional analysis on the loop.
894 if (Optional<EstimatedUnrollCost> Cost =
895 analyzeLoopUnrollCost(L, TripCount, *SE, TTI, AbsoluteThreshold))
896 if (canUnrollCompletely(L, Threshold, AbsoluteThreshold,
897 Cost->UnrolledLoopSize,
898 Cost->NumberOfOptimizedInstructions,
899 PercentOfOptimizedForCompleteUnroll)) {
903 } else if (TripCount && Count < TripCount) {
909 // Reduce count based on the type of unrolling and the threshold values.
910 unsigned OriginalCount = Count;
911 bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime;
912 if (HasRuntimeUnrollDisablePragma(L)) {
913 AllowRuntime = false;
915 if (Unrolling == Partial) {
916 bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
917 if (!AllowPartial && !CountSetExplicitly) {
918 DEBUG(dbgs() << " will not try to unroll partially because "
919 << "-unroll-allow-partial not given\n");
922 if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
923 // Reduce unroll count to be modulo of TripCount for partial unrolling.
924 Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2);
925 while (Count != 0 && TripCount % Count != 0)
928 } else if (Unrolling == Runtime) {
929 if (!AllowRuntime && !CountSetExplicitly) {
930 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count "
931 << "-unroll-runtime not given\n");
934 // Reduce unroll count to be the largest power-of-two factor of
935 // the original count which satisfies the threshold limit.
936 while (Count != 0 && UnrolledSize > PartialThreshold) {
938 UnrolledSize = (LoopSize-2) * Count + 2;
940 if (Count > UP.MaxCount)
942 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
946 if (PragmaCount != 0)
947 // If loop has an unroll count pragma mark loop as unrolled to prevent
948 // unrolling beyond that requested by the pragma.
949 SetLoopAlreadyUnrolled(L);
951 // Emit optimization remarks if we are unable to unroll the loop
952 // as directed by a pragma.
953 DebugLoc LoopLoc = L->getStartLoc();
954 Function *F = Header->getParent();
955 LLVMContext &Ctx = F->getContext();
956 if (PragmaFullUnroll && PragmaCount == 0) {
957 if (TripCount && Count != TripCount) {
958 emitOptimizationRemarkMissed(
959 Ctx, DEBUG_TYPE, *F, LoopLoc,
960 "Unable to fully unroll loop as directed by unroll(full) pragma "
961 "because unrolled size is too large.");
962 } else if (!TripCount) {
963 emitOptimizationRemarkMissed(
964 Ctx, DEBUG_TYPE, *F, LoopLoc,
965 "Unable to fully unroll loop as directed by unroll(full) pragma "
966 "because loop has a runtime trip count.");
968 } else if (PragmaCount > 0 && Count != OriginalCount) {
969 emitOptimizationRemarkMissed(
970 Ctx, DEBUG_TYPE, *F, LoopLoc,
971 "Unable to unroll loop the number of times directed by "
972 "unroll_count pragma because unrolled size is too large.");
976 if (Unrolling != Full && Count < 2) {
977 // Partial unrolling by 1 is a nop. For full unrolling, a factor
978 // of 1 makes sense because loop control can be eliminated.
983 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, UP.AllowExpensiveTripCount,
984 TripMultiple, LI, this, &LPM, &AC))