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/Analysis/AssumptionCache.h"
17 #include "llvm/Analysis/CodeMetrics.h"
18 #include "llvm/Analysis/LoopPass.h"
19 #include "llvm/Analysis/ScalarEvolution.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/DiagnosticInfo.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/Metadata.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Transforms/Utils/UnrollLoop.h"
34 #define DEBUG_TYPE "loop-unroll"
36 static cl::opt<unsigned>
37 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
38 cl::desc("The cut-off point for automatic loop unrolling"));
40 static cl::opt<unsigned>
41 UnrollCount("unroll-count", cl::init(0), cl::Hidden,
42 cl::desc("Use this unroll count for all loops including those with "
43 "unroll_count pragma values, for testing purposes"));
46 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
47 cl::desc("Allows loops to be partially unrolled until "
48 "-unroll-threshold loop size is reached."));
51 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
52 cl::desc("Unroll loops with run-time trip counts"));
54 static cl::opt<unsigned>
55 PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
56 cl::desc("Unrolled size limit for loops with an unroll(full) or "
57 "unroll_count pragma."));
60 class LoopUnroll : public LoopPass {
62 static char ID; // Pass ID, replacement for typeid
63 LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
64 CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
65 CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
66 CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
67 CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
69 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
70 UserAllowPartial = (P != -1) ||
71 (UnrollAllowPartial.getNumOccurrences() > 0);
72 UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
73 UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
75 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
78 /// A magic value for use with the Threshold parameter to indicate
79 /// that the loop unroll should be performed regardless of how much
80 /// code expansion would result.
81 static const unsigned NoThreshold = UINT_MAX;
83 // Threshold to use when optsize is specified (and there is no
84 // explicit -unroll-threshold).
85 static const unsigned OptSizeUnrollThreshold = 50;
87 // Default unroll count for loops with run-time trip count if
88 // -unroll-count is not set
89 static const unsigned UnrollRuntimeCount = 8;
91 unsigned CurrentCount;
92 unsigned CurrentThreshold;
93 bool CurrentAllowPartial;
95 bool UserCount; // CurrentCount is user-specified.
96 bool UserThreshold; // CurrentThreshold is user-specified.
97 bool UserAllowPartial; // CurrentAllowPartial is user-specified.
98 bool UserRuntime; // CurrentRuntime is user-specified.
100 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
102 /// This transformation requires natural loop information & requires that
103 /// loop preheaders be inserted into the CFG...
105 void getAnalysisUsage(AnalysisUsage &AU) const override {
106 AU.addRequired<AssumptionCacheTracker>();
107 AU.addRequired<LoopInfoWrapperPass>();
108 AU.addPreserved<LoopInfoWrapperPass>();
109 AU.addRequiredID(LoopSimplifyID);
110 AU.addPreservedID(LoopSimplifyID);
111 AU.addRequiredID(LCSSAID);
112 AU.addPreservedID(LCSSAID);
113 AU.addRequired<ScalarEvolution>();
114 AU.addPreserved<ScalarEvolution>();
115 AU.addRequired<TargetTransformInfoWrapperPass>();
116 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
117 // If loop unroll does not preserve dom info then LCSSA pass on next
118 // loop will receive invalid dom info.
119 // For now, recreate dom info, if loop is unrolled.
120 AU.addPreserved<DominatorTreeWrapperPass>();
123 // Fill in the UnrollingPreferences parameter with values from the
124 // TargetTransformationInfo.
125 void getUnrollingPreferences(Loop *L, const TargetTransformInfo &TTI,
126 TargetTransformInfo::UnrollingPreferences &UP) {
127 UP.Threshold = CurrentThreshold;
128 UP.OptSizeThreshold = OptSizeUnrollThreshold;
129 UP.PartialThreshold = CurrentThreshold;
130 UP.PartialOptSizeThreshold = OptSizeUnrollThreshold;
131 UP.Count = CurrentCount;
132 UP.MaxCount = UINT_MAX;
133 UP.Partial = CurrentAllowPartial;
134 UP.Runtime = CurrentRuntime;
135 TTI.getUnrollingPreferences(L, UP);
138 // Select and return an unroll count based on parameters from
139 // user, unroll preferences, unroll pragmas, or a heuristic.
140 // SetExplicitly is set to true if the unroll count is is set by
141 // the user or a pragma rather than selected heuristically.
143 selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
144 unsigned PragmaCount,
145 const TargetTransformInfo::UnrollingPreferences &UP,
146 bool &SetExplicitly);
148 // Select threshold values used to limit unrolling based on a
149 // total unrolled size. Parameters Threshold and PartialThreshold
150 // are set to the maximum unrolled size for fully and partially
151 // unrolled loops respectively.
152 void selectThresholds(const Loop *L, bool HasPragma,
153 const TargetTransformInfo::UnrollingPreferences &UP,
154 unsigned &Threshold, unsigned &PartialThreshold) {
155 // Determine the current unrolling threshold. While this is
156 // normally set from UnrollThreshold, it is overridden to a
157 // smaller value if the current function is marked as
158 // optimize-for-size, and the unroll threshold was not user
160 Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
161 PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold;
162 if (!UserThreshold &&
163 L->getHeader()->getParent()->getAttributes().
164 hasAttribute(AttributeSet::FunctionIndex,
165 Attribute::OptimizeForSize)) {
166 Threshold = UP.OptSizeThreshold;
167 PartialThreshold = UP.PartialOptSizeThreshold;
170 // If the loop has an unrolling pragma, we want to be more
171 // aggressive with unrolling limits. Set thresholds to at
172 // least the PragmaTheshold value which is larger than the
174 if (Threshold != NoThreshold)
175 Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold);
176 if (PartialThreshold != NoThreshold)
178 std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold);
184 char LoopUnroll::ID = 0;
185 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
186 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
187 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
188 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
189 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
190 INITIALIZE_PASS_DEPENDENCY(LCSSA)
191 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
192 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
194 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
196 return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
199 Pass *llvm::createSimpleLoopUnrollPass() {
200 return llvm::createLoopUnrollPass(-1, -1, 0, 0);
203 /// ApproximateLoopSize - Approximate the size of the loop.
204 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
205 bool &NotDuplicatable,
206 const TargetTransformInfo &TTI,
207 AssumptionCache *AC) {
208 SmallPtrSet<const Value *, 32> EphValues;
209 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
212 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
214 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
215 NumCalls = Metrics.NumInlineCandidates;
216 NotDuplicatable = Metrics.notDuplicatable;
218 unsigned LoopSize = Metrics.NumInsts;
220 // Don't allow an estimate of size zero. This would allows unrolling of loops
221 // with huge iteration counts, which is a compile time problem even if it's
222 // not a problem for code quality. Also, the code using this size may assume
223 // that each loop has at least three instructions (likely a conditional
224 // branch, a comparison feeding that branch, and some kind of loop increment
225 // feeding that comparison instruction).
226 LoopSize = std::max(LoopSize, 3u);
231 // Returns the loop hint metadata node with the given name (for example,
232 // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
234 static const MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
235 MDNode *LoopID = L->getLoopID();
238 return GetUnrollMetadata(LoopID, Name);
241 // Returns true if the loop has an unroll(full) pragma.
242 static bool HasUnrollFullPragma(const Loop *L) {
243 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
246 // Returns true if the loop has an unroll(disable) pragma.
247 static bool HasUnrollDisablePragma(const Loop *L) {
248 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
251 // If loop has an unroll_count pragma return the (necessarily
252 // positive) value from the pragma. Otherwise return 0.
253 static unsigned UnrollCountPragmaValue(const Loop *L) {
254 const MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
256 assert(MD->getNumOperands() == 2 &&
257 "Unroll count hint metadata should have two operands.");
259 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
260 assert(Count >= 1 && "Unroll count must be positive.");
266 // Remove existing unroll metadata and add unroll disable metadata to
267 // indicate the loop has already been unrolled. This prevents a loop
268 // from being unrolled more than is directed by a pragma if the loop
269 // unrolling pass is run more than once (which it generally is).
270 static void SetLoopAlreadyUnrolled(Loop *L) {
271 MDNode *LoopID = L->getLoopID();
274 // First remove any existing loop unrolling metadata.
275 SmallVector<Metadata *, 4> MDs;
276 // Reserve first location for self reference to the LoopID metadata node.
277 MDs.push_back(nullptr);
278 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
279 bool IsUnrollMetadata = false;
280 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
282 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
283 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
285 if (!IsUnrollMetadata)
286 MDs.push_back(LoopID->getOperand(i));
289 // Add unroll(disable) metadata to disable future unrolling.
290 LLVMContext &Context = L->getHeader()->getContext();
291 SmallVector<Metadata *, 1> DisableOperands;
292 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
293 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
294 MDs.push_back(DisableNode);
296 MDNode *NewLoopID = MDNode::get(Context, MDs);
297 // Set operand 0 to refer to the loop id itself.
298 NewLoopID->replaceOperandWith(0, NewLoopID);
299 L->setLoopID(NewLoopID);
302 unsigned LoopUnroll::selectUnrollCount(
303 const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
304 unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
305 bool &SetExplicitly) {
306 SetExplicitly = true;
308 // User-specified count (either as a command-line option or
309 // constructor parameter) has highest precedence.
310 unsigned Count = UserCount ? CurrentCount : 0;
312 // If there is no user-specified count, unroll pragmas have the next
313 // highest precendence.
317 } else if (PragmaFullUnroll) {
326 SetExplicitly = false;
328 // Runtime trip count.
329 Count = UnrollRuntimeCount;
331 // Conservative heuristic: if we know the trip count, see if we can
332 // completely unroll (subject to the threshold, checked below); otherwise
333 // try to find greatest modulo of the trip count which is still under
337 if (TripCount && Count > TripCount)
342 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
343 if (skipOptnoneFunction(L))
346 Function &F = *L->getHeader()->getParent();
348 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
349 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
350 const TargetTransformInfo &TTI =
351 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
352 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
354 BasicBlock *Header = L->getHeader();
355 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
356 << "] Loop %" << Header->getName() << "\n");
358 if (HasUnrollDisablePragma(L)) {
361 bool PragmaFullUnroll = HasUnrollFullPragma(L);
362 unsigned PragmaCount = UnrollCountPragmaValue(L);
363 bool HasPragma = PragmaFullUnroll || PragmaCount > 0;
365 TargetTransformInfo::UnrollingPreferences UP;
366 getUnrollingPreferences(L, TTI, UP);
368 // Find trip count and trip multiple if count is not available
369 unsigned TripCount = 0;
370 unsigned TripMultiple = 1;
371 // If there are multiple exiting blocks but one of them is the latch, use the
372 // latch for the trip count estimation. Otherwise insist on a single exiting
373 // block for the trip count estimation.
374 BasicBlock *ExitingBlock = L->getLoopLatch();
375 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
376 ExitingBlock = L->getExitingBlock();
378 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
379 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
382 // Select an initial unroll count. This may be reduced later based
383 // on size thresholds.
384 bool CountSetExplicitly;
385 unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
386 PragmaCount, UP, CountSetExplicitly);
388 unsigned NumInlineCandidates;
389 bool notDuplicatable;
391 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC);
392 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
394 // When computing the unrolled size, note that the conditional branch on the
395 // backedge and the comparison feeding it are not replicated like the rest of
396 // the loop body (which is why 2 is subtracted).
397 uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2;
398 if (notDuplicatable) {
399 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
400 << " instructions.\n");
403 if (NumInlineCandidates != 0) {
404 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
408 unsigned Threshold, PartialThreshold;
409 selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold);
411 // Given Count, TripCount and thresholds determine the type of
412 // unrolling which is to be performed.
413 enum { Full = 0, Partial = 1, Runtime = 2 };
415 if (TripCount && Count == TripCount) {
416 if (Threshold != NoThreshold && UnrolledSize > Threshold) {
417 DEBUG(dbgs() << " Too large to fully unroll with count: " << Count
418 << " because size: " << UnrolledSize << ">" << Threshold
424 } else if (TripCount && Count < TripCount) {
430 // Reduce count based on the type of unrolling and the threshold values.
431 unsigned OriginalCount = Count;
432 bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime;
433 if (Unrolling == Partial) {
434 bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
435 if (!AllowPartial && !CountSetExplicitly) {
436 DEBUG(dbgs() << " will not try to unroll partially because "
437 << "-unroll-allow-partial not given\n");
440 if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
441 // Reduce unroll count to be modulo of TripCount for partial unrolling.
442 Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2);
443 while (Count != 0 && TripCount % Count != 0)
446 } else if (Unrolling == Runtime) {
447 if (!AllowRuntime && !CountSetExplicitly) {
448 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count "
449 << "-unroll-runtime not given\n");
452 // Reduce unroll count to be the largest power-of-two factor of
453 // the original count which satisfies the threshold limit.
454 while (Count != 0 && UnrolledSize > PartialThreshold) {
456 UnrolledSize = (LoopSize-2) * Count + 2;
458 if (Count > UP.MaxCount)
460 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
464 if (PragmaCount != 0)
465 // If loop has an unroll count pragma mark loop as unrolled to prevent
466 // unrolling beyond that requested by the pragma.
467 SetLoopAlreadyUnrolled(L);
469 // Emit optimization remarks if we are unable to unroll the loop
470 // as directed by a pragma.
471 DebugLoc LoopLoc = L->getStartLoc();
472 Function *F = Header->getParent();
473 LLVMContext &Ctx = F->getContext();
474 if (PragmaFullUnroll && PragmaCount == 0) {
475 if (TripCount && Count != TripCount) {
476 emitOptimizationRemarkMissed(
477 Ctx, DEBUG_TYPE, *F, LoopLoc,
478 "Unable to fully unroll loop as directed by unroll(full) pragma "
479 "because unrolled size is too large.");
480 } else if (!TripCount) {
481 emitOptimizationRemarkMissed(
482 Ctx, DEBUG_TYPE, *F, LoopLoc,
483 "Unable to fully unroll loop as directed by unroll(full) pragma "
484 "because loop has a runtime trip count.");
486 } else if (PragmaCount > 0 && Count != OriginalCount) {
487 emitOptimizationRemarkMissed(
488 Ctx, DEBUG_TYPE, *F, LoopLoc,
489 "Unable to unroll loop the number of times directed by "
490 "unroll_count pragma because unrolled size is too large.");
494 if (Unrolling != Full && Count < 2) {
495 // Partial unrolling by 1 is a nop. For full unrolling, a factor
496 // of 1 makes sense because loop control can be eliminated.
501 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, TripMultiple, LI, this,