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/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"
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"));
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"));
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."));
42 // Temporary flag to be made default shortly.
44 UnrollWithSCEV("unroll-scev", cl::init(false), cl::Hidden,
45 cl::desc("Use ScalarEvolution to analyze loop trip counts for unrolling"));
48 class LoopUnroll : public LoopPass {
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;
56 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
58 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
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;
66 // Threshold to use when optsize is specified (and there is no
67 // explicit -unroll-threshold).
68 static const unsigned OptSizeUnrollThreshold = 50;
70 unsigned CurrentCount;
71 unsigned CurrentThreshold;
72 bool CurrentAllowPartial;
73 bool UserThreshold; // CurrentThreshold is user-specified.
75 bool runOnLoop(Loop *L, LPPassManager &LPM);
77 /// This transformation requires natural loop information & requires that
78 /// loop preheaders be inserted into the CFG...
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>();
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)
105 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial) {
106 return new LoopUnroll(Threshold, Count, AllowPartial);
109 /// ApproximateLoopSize - Approximate the size of the loop.
110 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls) {
112 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
114 Metrics.analyzeBasicBlock(*I);
115 NumCalls = Metrics.NumInlineCandidates;
117 unsigned LoopSize = Metrics.NumInsts;
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;
127 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
128 LoopInfo *LI = &getAnalysis<LoopInfo>();
129 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
131 BasicBlock *Header = L->getHeader();
132 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
133 << "] Loop %" << Header->getName() << "\n");
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;
145 // Find trip count and trip multiple if count is not available
146 unsigned TripCount = 0;
147 unsigned TripMultiple = 1;
148 if (UnrollWithSCEV) {
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();
154 TripCount = SE->getSmallConstantTripCount(L, LatchBlock);
155 TripMultiple = SE->getSmallConstantTripMultiple(L, LatchBlock);
159 TripCount = L->getSmallConstantTripCount();
161 TripMultiple = L->getSmallConstantTripMultiple();
163 // Automatically select an unroll count.
164 unsigned Count = CurrentCount;
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
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");
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");
193 // Reduce unroll count to be modulo of TripCount for partial unrolling
194 Count = Threshold / LoopSize;
195 while (Count != 0 && TripCount%Count != 0) {
199 DEBUG(dbgs() << " could not unroll partially\n");
202 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
207 if (!UnrollLoop(L, Count, TripCount, TripMultiple, LI, &LPM))