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 #define DEBUG_TYPE "loop-unroll"
16 #include "llvm/Transforms/Scalar.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/IntrinsicInst.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Transforms/Utils/UnrollLoop.h"
31 static cl::opt<unsigned>
32 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
33 cl::desc("The cut-off point for automatic loop unrolling"));
35 static cl::opt<unsigned>
36 UnrollCount("unroll-count", cl::init(0), cl::Hidden,
37 cl::desc("Use this unroll count for all loops, for testing purposes"));
40 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
41 cl::desc("Allows loops to be partially unrolled until "
42 "-unroll-threshold loop size is reached."));
45 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
46 cl::desc("Unroll loops with run-time trip counts"));
49 class LoopUnroll : public LoopPass {
51 static char ID; // Pass ID, replacement for typeid
52 LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
53 CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
54 CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
55 CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
56 CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
58 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
59 UserAllowPartial = (P != -1) ||
60 (UnrollAllowPartial.getNumOccurrences() > 0);
61 UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
62 UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
64 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
67 /// A magic value for use with the Threshold parameter to indicate
68 /// that the loop unroll should be performed regardless of how much
69 /// code expansion would result.
70 static const unsigned NoThreshold = UINT_MAX;
72 // Threshold to use when optsize is specified (and there is no
73 // explicit -unroll-threshold).
74 static const unsigned OptSizeUnrollThreshold = 50;
76 // Default unroll count for loops with run-time trip count if
77 // -unroll-count is not set
78 static const unsigned UnrollRuntimeCount = 8;
80 unsigned CurrentCount;
81 unsigned CurrentThreshold;
82 bool CurrentAllowPartial;
84 bool UserCount; // CurrentCount is user-specified.
85 bool UserThreshold; // CurrentThreshold is user-specified.
86 bool UserAllowPartial; // CurrentAllowPartial is user-specified.
87 bool UserRuntime; // CurrentRuntime is user-specified.
89 bool runOnLoop(Loop *L, LPPassManager &LPM);
91 /// This transformation requires natural loop information & requires that
92 /// loop preheaders be inserted into the CFG...
94 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
95 AU.addRequired<LoopInfo>();
96 AU.addPreserved<LoopInfo>();
97 AU.addRequiredID(LoopSimplifyID);
98 AU.addPreservedID(LoopSimplifyID);
99 AU.addRequiredID(LCSSAID);
100 AU.addPreservedID(LCSSAID);
101 AU.addRequired<ScalarEvolution>();
102 AU.addPreserved<ScalarEvolution>();
103 AU.addRequired<TargetTransformInfo>();
104 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
105 // If loop unroll does not preserve dom info then LCSSA pass on next
106 // loop will receive invalid dom info.
107 // For now, recreate dom info, if loop is unrolled.
108 AU.addPreserved<DominatorTree>();
113 char LoopUnroll::ID = 0;
114 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
115 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
116 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
117 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
118 INITIALIZE_PASS_DEPENDENCY(LCSSA)
119 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
120 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
122 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
124 return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
127 /// ApproximateLoopSize - Approximate the size of the loop.
128 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
129 bool &NotDuplicatable,
130 const TargetTransformInfo &TTI) {
132 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
134 Metrics.analyzeBasicBlock(*I, TTI);
135 NumCalls = Metrics.NumInlineCandidates;
136 NotDuplicatable = Metrics.notDuplicatable;
138 unsigned LoopSize = Metrics.NumInsts;
140 // Don't allow an estimate of size zero. This would allows unrolling of loops
141 // with huge iteration counts, which is a compile time problem even if it's
142 // not a problem for code quality.
143 if (LoopSize == 0) LoopSize = 1;
148 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
149 LoopInfo *LI = &getAnalysis<LoopInfo>();
150 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
151 const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>();
153 BasicBlock *Header = L->getHeader();
154 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
155 << "] Loop %" << Header->getName() << "\n");
158 TargetTransformInfo::UnrollingPreferences UP;
159 UP.Threshold = CurrentThreshold;
160 UP.OptSizeThreshold = OptSizeUnrollThreshold;
161 UP.Count = CurrentCount;
162 UP.Partial = CurrentAllowPartial;
163 UP.Runtime = CurrentRuntime;
164 TTI.getUnrollingPreferences(L, UP);
166 // Determine the current unrolling threshold. While this is normally set
167 // from UnrollThreshold, it is overridden to a smaller value if the current
168 // function is marked as optimize-for-size, and the unroll threshold was
169 // not user specified.
170 unsigned Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
171 if (!UserThreshold &&
172 Header->getParent()->getAttributes().
173 hasAttribute(AttributeSet::FunctionIndex,
174 Attribute::OptimizeForSize))
175 Threshold = UP.OptSizeThreshold;
177 // Find trip count and trip multiple if count is not available
178 unsigned TripCount = 0;
179 unsigned TripMultiple = 1;
180 // Find "latch trip count". UnrollLoop assumes that control cannot exit
181 // via the loop latch on any iteration prior to TripCount. The loop may exit
182 // early via an earlier branch.
183 BasicBlock *LatchBlock = L->getLoopLatch();
185 TripCount = SE->getSmallConstantTripCount(L, LatchBlock);
186 TripMultiple = SE->getSmallConstantTripMultiple(L, LatchBlock);
189 bool Runtime = UserRuntime ? CurrentRuntime : UP.Runtime;
191 // Use a default unroll-count if the user doesn't specify a value
192 // and the trip count is a run-time value. The default is different
193 // for run-time or compile-time trip count loops.
194 unsigned Count = UserCount ? CurrentCount : UP.Count;
195 if (Runtime && Count == 0 && TripCount == 0)
196 Count = UnrollRuntimeCount;
199 // Conservative heuristic: if we know the trip count, see if we can
200 // completely unroll (subject to the threshold, checked below); otherwise
201 // try to find greatest modulo of the trip count which is still under
208 // Enforce the threshold.
209 if (Threshold != NoThreshold) {
210 unsigned NumInlineCandidates;
211 bool notDuplicatable;
212 unsigned LoopSize = ApproximateLoopSize(L, NumInlineCandidates,
213 notDuplicatable, TTI);
214 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
215 if (notDuplicatable) {
216 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
217 << " instructions.\n");
220 if (NumInlineCandidates != 0) {
221 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
224 uint64_t Size = (uint64_t)LoopSize*Count;
225 if (TripCount != 1 && Size > Threshold) {
226 DEBUG(dbgs() << " Too large to fully unroll with count: " << Count
227 << " because size: " << Size << ">" << Threshold << "\n");
228 bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
229 if (!AllowPartial && !(Runtime && TripCount == 0)) {
230 DEBUG(dbgs() << " will not try to unroll partially because "
231 << "-unroll-allow-partial not given\n");
235 // Reduce unroll count to be modulo of TripCount for partial unrolling
236 Count = Threshold / LoopSize;
237 while (Count != 0 && TripCount%Count != 0)
241 // Reduce unroll count to be a lower power-of-two value
242 while (Count != 0 && Size > Threshold) {
244 Size = LoopSize*Count;
248 DEBUG(dbgs() << " could not unroll partially\n");
251 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
256 if (!UnrollLoop(L, Count, TripCount, Runtime, TripMultiple, LI, &LPM))