08ac38dec5dd8adc2f032aad68ced9c79ffef454
[oota-llvm.git] / lib / Transforms / Scalar / LoopUnrollPass.cpp
1 //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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 //===----------------------------------------------------------------------===//
14
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"
27 #include <climits>
28
29 using namespace llvm;
30
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"));
34
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"));
38
39 static cl::opt<bool>
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."));
43
44 static cl::opt<bool>
45 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
46   cl::desc("Unroll loops with run-time trip counts"));
47
48 namespace {
49   class LoopUnroll : public LoopPass {
50   public:
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;
57
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);
63
64       initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
65     }
66
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;
71
72     // Threshold to use when optsize is specified (and there is no
73     // explicit -unroll-threshold).
74     static const unsigned OptSizeUnrollThreshold = 50;
75
76     // Default unroll count for loops with run-time trip count if
77     // -unroll-count is not set
78     static const unsigned UnrollRuntimeCount = 8;
79
80     unsigned CurrentCount;
81     unsigned CurrentThreshold;
82     bool     CurrentAllowPartial;
83     bool     CurrentRuntime;
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.
88
89     bool runOnLoop(Loop *L, LPPassManager &LPM);
90
91     /// This transformation requires natural loop information & requires that
92     /// loop preheaders be inserted into the CFG...
93     ///
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>();
109     }
110   };
111 }
112
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)
121
122 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
123                                  int Runtime) {
124   return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
125 }
126
127 /// ApproximateLoopSize - Approximate the size of the loop.
128 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
129                                     bool &NotDuplicatable,
130                                     const TargetTransformInfo &TTI) {
131   CodeMetrics Metrics;
132   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
133        I != E; ++I)
134     Metrics.analyzeBasicBlock(*I, TTI);
135   NumCalls = Metrics.NumInlineCandidates;
136   NotDuplicatable = Metrics.notDuplicatable;
137
138   unsigned LoopSize = Metrics.NumInsts;
139
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;
144
145   return LoopSize;
146 }
147
148 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
149   LoopInfo *LI = &getAnalysis<LoopInfo>();
150   ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
151   const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>();
152
153   BasicBlock *Header = L->getHeader();
154   DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
155         << "] Loop %" << Header->getName() << "\n");
156   (void)Header;
157
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);
165
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;
176
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();
184   if (LatchBlock) {
185     TripCount = SE->getSmallConstantTripCount(L, LatchBlock);
186     TripMultiple = SE->getSmallConstantTripMultiple(L, LatchBlock);
187   }
188
189   bool Runtime = UserRuntime ? CurrentRuntime : UP.Runtime;
190
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;
197
198   if (Count == 0) {
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
202     // threshold value.
203     if (TripCount == 0)
204       return false;
205     Count = TripCount;
206   }
207
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");
218       return false;
219     }
220     if (NumInlineCandidates != 0) {
221       DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
222       return false;
223     }
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");
232         return false;
233       }
234       if (TripCount) {
235         // Reduce unroll count to be modulo of TripCount for partial unrolling
236         Count = Threshold / LoopSize;
237         while (Count != 0 && TripCount%Count != 0)
238           Count--;
239       }
240       else if (Runtime) {
241         // Reduce unroll count to be a lower power-of-two value
242         while (Count != 0 && Size > Threshold) {
243           Count >>= 1;
244           Size = LoopSize*Count;
245         }
246       }
247       if (Count < 2) {
248         DEBUG(dbgs() << "  could not unroll partially\n");
249         return false;
250       }
251       DEBUG(dbgs() << "  partially unrolling with count: " << Count << "\n");
252     }
253   }
254
255   // Unroll the loop.
256   if (!UnrollLoop(L, Count, TripCount, Runtime, TripMultiple, LI, &LPM))
257     return false;
258
259   return true;
260 }