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/CodeMetrics.h"
17 #include "llvm/Analysis/LoopPass.h"
18 #include "llvm/Analysis/ScalarEvolution.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/Dominators.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 #define DEBUG_TYPE "loop-unroll"
33 static cl::opt<unsigned>
34 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
35 cl::desc("The cut-off point for automatic loop unrolling"));
37 static cl::opt<unsigned>
38 UnrollCount("unroll-count", cl::init(0), cl::Hidden,
39 cl::desc("Use this unroll count for all loops, for testing purposes"));
42 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
43 cl::desc("Allows loops to be partially unrolled until "
44 "-unroll-threshold loop size is reached."));
47 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
48 cl::desc("Unroll loops with run-time trip counts"));
51 class LoopUnroll : public LoopPass {
53 static char ID; // Pass ID, replacement for typeid
54 LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
55 CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
56 CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
57 CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
58 CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
60 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
61 UserAllowPartial = (P != -1) ||
62 (UnrollAllowPartial.getNumOccurrences() > 0);
63 UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
64 UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
66 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
69 /// A magic value for use with the Threshold parameter to indicate
70 /// that the loop unroll should be performed regardless of how much
71 /// code expansion would result.
72 static const unsigned NoThreshold = UINT_MAX;
74 // Threshold to use when optsize is specified (and there is no
75 // explicit -unroll-threshold).
76 static const unsigned OptSizeUnrollThreshold = 50;
78 // Default unroll count for loops with run-time trip count if
79 // -unroll-count is not set
80 static const unsigned UnrollRuntimeCount = 8;
82 unsigned CurrentCount;
83 unsigned CurrentThreshold;
84 bool CurrentAllowPartial;
86 bool UserCount; // CurrentCount is user-specified.
87 bool UserThreshold; // CurrentThreshold is user-specified.
88 bool UserAllowPartial; // CurrentAllowPartial is user-specified.
89 bool UserRuntime; // CurrentRuntime is user-specified.
91 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
93 /// This transformation requires natural loop information & requires that
94 /// loop preheaders be inserted into the CFG...
96 void getAnalysisUsage(AnalysisUsage &AU) const override {
97 AU.addRequired<LoopInfo>();
98 AU.addPreserved<LoopInfo>();
99 AU.addRequiredID(LoopSimplifyID);
100 AU.addPreservedID(LoopSimplifyID);
101 AU.addRequiredID(LCSSAID);
102 AU.addPreservedID(LCSSAID);
103 AU.addRequired<ScalarEvolution>();
104 AU.addPreserved<ScalarEvolution>();
105 AU.addRequired<TargetTransformInfo>();
106 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
107 // If loop unroll does not preserve dom info then LCSSA pass on next
108 // loop will receive invalid dom info.
109 // For now, recreate dom info, if loop is unrolled.
110 AU.addPreserved<DominatorTreeWrapperPass>();
115 char LoopUnroll::ID = 0;
116 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
117 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
118 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
119 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
120 INITIALIZE_PASS_DEPENDENCY(LCSSA)
121 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
122 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
124 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
126 return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
129 Pass *llvm::createSimpleLoopUnrollPass() {
130 return llvm::createLoopUnrollPass(-1, -1, 0, 0);
133 /// ApproximateLoopSize - Approximate the size of the loop.
134 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
135 bool &NotDuplicatable,
136 const TargetTransformInfo &TTI) {
138 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
140 Metrics.analyzeBasicBlock(*I, TTI);
141 NumCalls = Metrics.NumInlineCandidates;
142 NotDuplicatable = Metrics.notDuplicatable;
144 unsigned LoopSize = Metrics.NumInsts;
146 // Don't allow an estimate of size zero. This would allows unrolling of loops
147 // with huge iteration counts, which is a compile time problem even if it's
148 // not a problem for code quality.
149 if (LoopSize == 0) LoopSize = 1;
154 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
155 if (skipOptnoneFunction(L))
158 LoopInfo *LI = &getAnalysis<LoopInfo>();
159 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
160 const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>();
162 BasicBlock *Header = L->getHeader();
163 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
164 << "] Loop %" << Header->getName() << "\n");
167 TargetTransformInfo::UnrollingPreferences UP;
168 UP.Threshold = CurrentThreshold;
169 UP.OptSizeThreshold = OptSizeUnrollThreshold;
170 UP.PartialThreshold = CurrentThreshold;
171 UP.PartialOptSizeThreshold = OptSizeUnrollThreshold;
172 UP.Count = CurrentCount;
173 UP.MaxCount = UINT_MAX;
174 UP.Partial = CurrentAllowPartial;
175 UP.Runtime = CurrentRuntime;
176 TTI.getUnrollingPreferences(L, UP);
178 // Determine the current unrolling threshold. While this is normally set
179 // from UnrollThreshold, it is overridden to a smaller value if the current
180 // function is marked as optimize-for-size, and the unroll threshold was
181 // not user specified.
182 unsigned Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
183 unsigned PartialThreshold =
184 UserThreshold ? CurrentThreshold : UP.PartialThreshold;
185 if (!UserThreshold &&
186 Header->getParent()->getAttributes().
187 hasAttribute(AttributeSet::FunctionIndex,
188 Attribute::OptimizeForSize)) {
189 Threshold = UP.OptSizeThreshold;
190 PartialThreshold = UP.PartialOptSizeThreshold;
193 // Find trip count and trip multiple if count is not available
194 unsigned TripCount = 0;
195 unsigned TripMultiple = 1;
196 // Find "latch trip count". UnrollLoop assumes that control cannot exit
197 // via the loop latch on any iteration prior to TripCount. The loop may exit
198 // early via an earlier branch.
199 BasicBlock *LatchBlock = L->getLoopLatch();
201 TripCount = SE->getSmallConstantTripCount(L, LatchBlock);
202 TripMultiple = SE->getSmallConstantTripMultiple(L, LatchBlock);
205 bool Runtime = UserRuntime ? CurrentRuntime : UP.Runtime;
207 // Use a default unroll-count if the user doesn't specify a value
208 // and the trip count is a run-time value. The default is different
209 // for run-time or compile-time trip count loops.
210 unsigned Count = UserCount ? CurrentCount : UP.Count;
211 if (Runtime && Count == 0 && TripCount == 0)
212 Count = UnrollRuntimeCount;
215 // Conservative heuristic: if we know the trip count, see if we can
216 // completely unroll (subject to the threshold, checked below); otherwise
217 // try to find greatest modulo of the trip count which is still under
224 // Enforce the threshold.
225 if (Threshold != NoThreshold && PartialThreshold != NoThreshold) {
226 unsigned NumInlineCandidates;
227 bool notDuplicatable;
228 unsigned LoopSize = ApproximateLoopSize(L, NumInlineCandidates,
229 notDuplicatable, TTI);
230 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
231 if (notDuplicatable) {
232 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
233 << " instructions.\n");
236 if (NumInlineCandidates != 0) {
237 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
240 uint64_t Size = (uint64_t)LoopSize*Count;
241 if (TripCount != 1 &&
242 (Size > Threshold || (Count != TripCount && Size > PartialThreshold))) {
243 if (Size > Threshold)
244 DEBUG(dbgs() << " Too large to fully unroll with count: " << Count
245 << " because size: " << Size << ">" << Threshold << "\n");
247 bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
248 if (!AllowPartial && !(Runtime && TripCount == 0)) {
249 DEBUG(dbgs() << " will not try to unroll partially because "
250 << "-unroll-allow-partial not given\n");
254 // Reduce unroll count to be modulo of TripCount for partial unrolling
255 Count = PartialThreshold / LoopSize;
256 while (Count != 0 && TripCount%Count != 0)
260 // Reduce unroll count to be a lower power-of-two value
261 while (Count != 0 && Size > PartialThreshold) {
263 Size = LoopSize*Count;
266 if (Count > UP.MaxCount)
269 DEBUG(dbgs() << " could not unroll partially\n");
272 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
277 if (!UnrollLoop(L, Count, TripCount, Runtime, TripMultiple, LI, this, &LPM))