Enable SCEV-based unrolling by default.
[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/IntrinsicInst.h"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/Analysis/LoopPass.h"
19 #include "llvm/Analysis/CodeMetrics.h"
20 #include "llvm/Analysis/ScalarEvolution.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Transforms/Utils/UnrollLoop.h"
25 #include <climits>
26
27 using namespace llvm;
28
29 static cl::opt<unsigned>
30 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
31   cl::desc("The cut-off point for automatic loop unrolling"));
32
33 static cl::opt<unsigned>
34 UnrollCount("unroll-count", cl::init(0), cl::Hidden,
35   cl::desc("Use this unroll count for all loops, for testing purposes"));
36
37 static cl::opt<bool>
38 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
39   cl::desc("Allows loops to be partially unrolled until "
40            "-unroll-threshold loop size is reached."));
41
42 // Temporary flag to be removed in 3.0
43 static cl::opt<bool>
44 NoSCEVUnroll("disable-unroll-scev", cl::init(false), cl::Hidden,
45   cl::desc("Use ScalarEvolution to analyze loop trip counts for unrolling"));
46
47 namespace {
48   class LoopUnroll : public LoopPass {
49   public:
50     static char ID; // Pass ID, replacement for typeid
51     LoopUnroll(int T = -1, int C = -1,  int P = -1) : LoopPass(ID) {
52       CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
53       CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
54       CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
55
56       UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
57
58       initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
59     }
60
61     /// A magic value for use with the Threshold parameter to indicate
62     /// that the loop unroll should be performed regardless of how much
63     /// code expansion would result.
64     static const unsigned NoThreshold = UINT_MAX;
65
66     // Threshold to use when optsize is specified (and there is no
67     // explicit -unroll-threshold).
68     static const unsigned OptSizeUnrollThreshold = 50;
69
70     unsigned CurrentCount;
71     unsigned CurrentThreshold;
72     bool     CurrentAllowPartial;
73     bool     UserThreshold;        // CurrentThreshold is user-specified.
74
75     bool runOnLoop(Loop *L, LPPassManager &LPM);
76
77     /// This transformation requires natural loop information & requires that
78     /// loop preheaders be inserted into the CFG...
79     ///
80     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
81       AU.addRequired<LoopInfo>();
82       AU.addPreserved<LoopInfo>();
83       AU.addRequiredID(LoopSimplifyID);
84       AU.addPreservedID(LoopSimplifyID);
85       AU.addRequiredID(LCSSAID);
86       AU.addPreservedID(LCSSAID);
87       AU.addRequired<ScalarEvolution>();
88       AU.addPreserved<ScalarEvolution>();
89       // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
90       // If loop unroll does not preserve dom info then LCSSA pass on next
91       // loop will receive invalid dom info.
92       // For now, recreate dom info, if loop is unrolled.
93       AU.addPreserved<DominatorTree>();
94     }
95   };
96 }
97
98 char LoopUnroll::ID = 0;
99 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
100 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
101 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
102 INITIALIZE_PASS_DEPENDENCY(LCSSA)
103 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
104
105 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial) {
106   return new LoopUnroll(Threshold, Count, AllowPartial);
107 }
108
109 /// ApproximateLoopSize - Approximate the size of the loop.
110 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls) {
111   CodeMetrics Metrics;
112   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
113        I != E; ++I)
114     Metrics.analyzeBasicBlock(*I);
115   NumCalls = Metrics.NumInlineCandidates;
116
117   unsigned LoopSize = Metrics.NumInsts;
118
119   // Don't allow an estimate of size zero.  This would allows unrolling of loops
120   // with huge iteration counts, which is a compile time problem even if it's
121   // not a problem for code quality.
122   if (LoopSize == 0) LoopSize = 1;
123
124   return LoopSize;
125 }
126
127 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
128   LoopInfo *LI = &getAnalysis<LoopInfo>();
129   ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
130
131   BasicBlock *Header = L->getHeader();
132   DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
133         << "] Loop %" << Header->getName() << "\n");
134   (void)Header;
135
136   // Determine the current unrolling threshold.  While this is normally set
137   // from UnrollThreshold, it is overridden to a smaller value if the current
138   // function is marked as optimize-for-size, and the unroll threshold was
139   // not user specified.
140   unsigned Threshold = CurrentThreshold;
141   if (!UserThreshold &&
142       Header->getParent()->hasFnAttr(Attribute::OptimizeForSize))
143     Threshold = OptSizeUnrollThreshold;
144
145   // Find trip count and trip multiple if count is not available
146   unsigned TripCount = 0;
147   unsigned TripMultiple = 1;
148   if (!NoSCEVUnroll) {
149     // Find "latch trip count". UnrollLoop assumes that control cannot exit
150     // via the loop latch on any iteration prior to TripCount. The loop may exit
151     // early via an earlier branch.
152     BasicBlock *LatchBlock = L->getLoopLatch();
153     if (LatchBlock) {
154       TripCount = SE->getSmallConstantTripCount(L, LatchBlock);
155       TripMultiple = SE->getSmallConstantTripMultiple(L, LatchBlock);
156     }
157   }
158   else {
159     TripCount = L->getSmallConstantTripCount();
160     if (TripCount == 0)
161       TripMultiple = L->getSmallConstantTripMultiple();
162   }
163   // Automatically select an unroll count.
164   unsigned Count = CurrentCount;
165   if (Count == 0) {
166     // Conservative heuristic: if we know the trip count, see if we can
167     // completely unroll (subject to the threshold, checked below); otherwise
168     // try to find greatest modulo of the trip count which is still under
169     // threshold value.
170     if (TripCount == 0)
171       return false;
172     Count = TripCount;
173   }
174
175   // Enforce the threshold.
176   if (Threshold != NoThreshold) {
177     unsigned NumInlineCandidates;
178     unsigned LoopSize = ApproximateLoopSize(L, NumInlineCandidates);
179     DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
180     if (NumInlineCandidates != 0) {
181       DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
182       return false;
183     }
184     uint64_t Size = (uint64_t)LoopSize*Count;
185     if (TripCount != 1 && Size > Threshold) {
186       DEBUG(dbgs() << "  Too large to fully unroll with count: " << Count
187             << " because size: " << Size << ">" << Threshold << "\n");
188       if (!CurrentAllowPartial) {
189         DEBUG(dbgs() << "  will not try to unroll partially because "
190               << "-unroll-allow-partial not given\n");
191         return false;
192       }
193       // Reduce unroll count to be modulo of TripCount for partial unrolling
194       Count = Threshold / LoopSize;
195       while (Count != 0 && TripCount%Count != 0) {
196         Count--;
197       }
198       if (Count < 2) {
199         DEBUG(dbgs() << "  could not unroll partially\n");
200         return false;
201       }
202       DEBUG(dbgs() << "  partially unrolling with count: " << Count << "\n");
203     }
204   }
205
206   // Unroll the loop.
207   if (!UnrollLoop(L, Count, TripCount, TripMultiple, LI, &LPM))
208     return false;
209
210   return true;
211 }