Get rid of static constructors for pass registration. Instead, every pass exposes...
[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/InlineCost.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 namespace {
43   class LoopUnroll : public LoopPass {
44   public:
45     static char ID; // Pass ID, replacement for typeid
46     LoopUnroll() : LoopPass(ID) {
47       initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
48     }
49
50     /// A magic value for use with the Threshold parameter to indicate
51     /// that the loop unroll should be performed regardless of how much
52     /// code expansion would result.
53     static const unsigned NoThreshold = UINT_MAX;
54     
55     // Threshold to use when optsize is specified (and there is no
56     // explicit -unroll-threshold).
57     static const unsigned OptSizeUnrollThreshold = 50;
58     
59     unsigned CurrentThreshold;
60
61     bool runOnLoop(Loop *L, LPPassManager &LPM);
62
63     /// This transformation requires natural loop information & requires that
64     /// loop preheaders be inserted into the CFG...
65     ///
66     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67       AU.addRequired<LoopInfo>();
68       AU.addPreserved<LoopInfo>();
69       AU.addRequiredID(LoopSimplifyID);
70       AU.addPreservedID(LoopSimplifyID);
71       AU.addRequiredID(LCSSAID);
72       AU.addPreservedID(LCSSAID);
73       AU.addPreserved<ScalarEvolution>();
74       // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
75       // If loop unroll does not preserve dom info then LCSSA pass on next
76       // loop will receive invalid dom info.
77       // For now, recreate dom info, if loop is unrolled.
78       AU.addPreserved<DominatorTree>();
79     }
80   };
81 }
82
83 char LoopUnroll::ID = 0;
84 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
85 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
86 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
87 INITIALIZE_PASS_DEPENDENCY(LCSSA)
88 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
89 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
90 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
91
92 Pass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
93
94 /// ApproximateLoopSize - Approximate the size of the loop.
95 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls) {
96   CodeMetrics Metrics;
97   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
98        I != E; ++I)
99     Metrics.analyzeBasicBlock(*I);
100   NumCalls = Metrics.NumInlineCandidates;
101   
102   unsigned LoopSize = Metrics.NumInsts;
103   
104   // If we can identify the induction variable, we know that it will become
105   // constant when we unroll the loop, so factor that into our loop size 
106   // estimate.
107   // FIXME: We have to divide by InlineConstants::InstrCost because the
108   // measure returned by CountCodeReductionForConstant is not an instruction
109   // count, but rather a weight as defined by InlineConstants.  It would 
110   // probably be a good idea to standardize on a single weighting scheme by
111   // pushing more of the logic for weighting into CodeMetrics.
112   if (PHINode *IndVar = L->getCanonicalInductionVariable()) {
113     unsigned SizeDecrease = Metrics.CountCodeReductionForConstant(IndVar);
114     // NOTE: Because SizeDecrease is a fuzzy estimate, we don't want to allow
115     // it to totally negate the cost of unrolling a loop.
116     SizeDecrease = SizeDecrease > LoopSize / 2 ? LoopSize / 2 : SizeDecrease;
117   }
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   
129   LoopInfo *LI = &getAnalysis<LoopInfo>();
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   CurrentThreshold = UnrollThreshold;
141   if (Header->getParent()->hasFnAttr(Attribute::OptimizeForSize) &&
142       UnrollThreshold.getNumOccurrences() == 0)
143     CurrentThreshold = OptSizeUnrollThreshold;
144
145   // Find trip count
146   unsigned TripCount = L->getSmallConstantTripCount();
147   unsigned Count = UnrollCount;
148
149   // Automatically select an unroll count.
150   if (Count == 0) {
151     // Conservative heuristic: if we know the trip count, see if we can
152     // completely unroll (subject to the threshold, checked below); otherwise
153     // try to find greatest modulo of the trip count which is still under
154     // threshold value.
155     if (TripCount == 0)
156       return false;
157     Count = TripCount;
158   }
159
160   // Enforce the threshold.
161   if (CurrentThreshold != NoThreshold) {
162     unsigned NumInlineCandidates;
163     unsigned LoopSize = ApproximateLoopSize(L, NumInlineCandidates);
164     DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
165     if (NumInlineCandidates != 0) {
166       DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
167       return false;
168     }
169     uint64_t Size = (uint64_t)LoopSize*Count;
170     if (TripCount != 1 && Size > CurrentThreshold) {
171       DEBUG(dbgs() << "  Too large to fully unroll with count: " << Count
172             << " because size: " << Size << ">" << CurrentThreshold << "\n");
173       if (!UnrollAllowPartial) {
174         DEBUG(dbgs() << "  will not try to unroll partially because "
175               << "-unroll-allow-partial not given\n");
176         return false;
177       }
178       // Reduce unroll count to be modulo of TripCount for partial unrolling
179       Count = CurrentThreshold / LoopSize;
180       while (Count != 0 && TripCount%Count != 0) {
181         Count--;
182       }
183       if (Count < 2) {
184         DEBUG(dbgs() << "  could not unroll partially\n");
185         return false;
186       }
187       DEBUG(dbgs() << "  partially unrolling with count: " << Count << "\n");
188     }
189   }
190
191   // Unroll the loop.
192   Function *F = L->getHeader()->getParent();
193   if (!UnrollLoop(L, Count, LI, &LPM))
194     return false;
195
196   // FIXME: Reconstruct dom info, because it is not preserved properly.
197   if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>())
198     DT->runOnFunction(*F);
199   return true;
200 }