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."));
43 class LoopUnroll
: public LoopPass
{
45 static char ID
; // Pass ID, replacement for typeid
46 LoopUnroll(int T
= -1, int C
= -1, int P
= -1) : LoopPass(ID
) {
47 CurrentThreshold
= (T
== -1) ? UnrollThreshold
: unsigned(T
);
48 CurrentCount
= (C
== -1) ? UnrollCount
: unsigned(C
);
49 CurrentAllowPartial
= (P
== -1) ? UnrollAllowPartial
: (bool)P
;
51 UserThreshold
= (T
!= -1) || (UnrollThreshold
.getNumOccurrences() > 0);
53 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
56 /// A magic value for use with the Threshold parameter to indicate
57 /// that the loop unroll should be performed regardless of how much
58 /// code expansion would result.
59 static const unsigned NoThreshold
= UINT_MAX
;
61 // Threshold to use when optsize is specified (and there is no
62 // explicit -unroll-threshold).
63 static const unsigned OptSizeUnrollThreshold
= 50;
65 unsigned CurrentCount
;
66 unsigned CurrentThreshold
;
67 bool CurrentAllowPartial
;
68 bool UserThreshold
; // CurrentThreshold is user-specified.
70 bool runOnLoop(Loop
*L
, LPPassManager
&LPM
);
72 /// This transformation requires natural loop information & requires that
73 /// loop preheaders be inserted into the CFG...
75 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
76 AU
.addRequired
<LoopInfo
>();
77 AU
.addPreserved
<LoopInfo
>();
78 AU
.addRequiredID(LoopSimplifyID
);
79 AU
.addPreservedID(LoopSimplifyID
);
80 AU
.addRequiredID(LCSSAID
);
81 AU
.addPreservedID(LCSSAID
);
82 AU
.addPreserved
<ScalarEvolution
>();
83 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
84 // If loop unroll does not preserve dom info then LCSSA pass on next
85 // loop will receive invalid dom info.
86 // For now, recreate dom info, if loop is unrolled.
87 AU
.addPreserved
<DominatorTree
>();
92 char LoopUnroll::ID
= 0;
93 INITIALIZE_PASS_BEGIN(LoopUnroll
, "loop-unroll", "Unroll loops", false, false)
94 INITIALIZE_PASS_DEPENDENCY(LoopInfo
)
95 INITIALIZE_PASS_DEPENDENCY(LoopSimplify
)
96 INITIALIZE_PASS_DEPENDENCY(LCSSA
)
97 INITIALIZE_PASS_END(LoopUnroll
, "loop-unroll", "Unroll loops", false, false)
99 Pass
*llvm::createLoopUnrollPass(int Threshold
, int Count
, int AllowPartial
) {
100 return new LoopUnroll(Threshold
, Count
, AllowPartial
);
103 /// ApproximateLoopSize - Approximate the size of the loop.
104 static unsigned ApproximateLoopSize(const Loop
*L
, unsigned &NumCalls
) {
106 for (Loop::block_iterator I
= L
->block_begin(), E
= L
->block_end();
108 Metrics
.analyzeBasicBlock(*I
);
109 NumCalls
= Metrics
.NumInlineCandidates
;
111 unsigned LoopSize
= Metrics
.NumInsts
;
113 // Don't allow an estimate of size zero. This would allows unrolling of loops
114 // with huge iteration counts, which is a compile time problem even if it's
115 // not a problem for code quality.
116 if (LoopSize
== 0) LoopSize
= 1;
121 bool LoopUnroll::runOnLoop(Loop
*L
, LPPassManager
&LPM
) {
122 LoopInfo
*LI
= &getAnalysis
<LoopInfo
>();
124 BasicBlock
*Header
= L
->getHeader();
125 DEBUG(dbgs() << "Loop Unroll: F[" << Header
->getParent()->getName()
126 << "] Loop %" << Header
->getName() << "\n");
129 // Determine the current unrolling threshold. While this is normally set
130 // from UnrollThreshold, it is overridden to a smaller value if the current
131 // function is marked as optimize-for-size, and the unroll threshold was
132 // not user specified.
133 unsigned Threshold
= CurrentThreshold
;
134 if (!UserThreshold
&&
135 Header
->getParent()->hasFnAttr(Attribute::OptimizeForSize
))
136 Threshold
= OptSizeUnrollThreshold
;
139 unsigned TripCount
= L
->getSmallConstantTripCount();
140 unsigned Count
= CurrentCount
;
142 // Automatically select an unroll count.
144 // Conservative heuristic: if we know the trip count, see if we can
145 // completely unroll (subject to the threshold, checked below); otherwise
146 // try to find greatest modulo of the trip count which is still under
153 // Enforce the threshold.
154 if (Threshold
!= NoThreshold
) {
155 unsigned NumInlineCandidates
;
156 unsigned LoopSize
= ApproximateLoopSize(L
, NumInlineCandidates
);
157 DEBUG(dbgs() << " Loop Size = " << LoopSize
<< "\n");
158 if (NumInlineCandidates
!= 0) {
159 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
162 uint64_t Size
= (uint64_t)LoopSize
*Count
;
163 if (TripCount
!= 1 && Size
> Threshold
) {
164 DEBUG(dbgs() << " Too large to fully unroll with count: " << Count
165 << " because size: " << Size
<< ">" << Threshold
<< "\n");
166 if (!CurrentAllowPartial
) {
167 DEBUG(dbgs() << " will not try to unroll partially because "
168 << "-unroll-allow-partial not given\n");
171 // Reduce unroll count to be modulo of TripCount for partial unrolling
172 Count
= Threshold
/ LoopSize
;
173 while (Count
!= 0 && TripCount
%Count
!= 0) {
177 DEBUG(dbgs() << " could not unroll partially\n");
180 DEBUG(dbgs() << " partially unrolling with count: " << Count
<< "\n");
185 Function
*F
= L
->getHeader()->getParent();
186 if (!UnrollLoop(L
, Count
, LI
, &LPM
))
189 // FIXME: Reconstruct dom info, because it is not preserved properly.
190 if (DominatorTree
*DT
= getAnalysisIfAvailable
<DominatorTree
>())
191 DT
->runOnFunction(*F
);