LoopUnrollPass.cpp revision 36b56886974eae4f9c5ebc96befd3e7bfe5de338
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/Dominators.h"
23#include "llvm/IR/IntrinsicInst.h"
24#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/raw_ostream.h"
27#include "llvm/Transforms/Utils/UnrollLoop.h"
28#include <climits>
29
30using namespace llvm;
31
32static cl::opt<unsigned>
33UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
34  cl::desc("The cut-off point for automatic loop unrolling"));
35
36static cl::opt<unsigned>
37UnrollCount("unroll-count", cl::init(0), cl::Hidden,
38  cl::desc("Use this unroll count for all loops, for testing purposes"));
39
40static cl::opt<bool>
41UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
42  cl::desc("Allows loops to be partially unrolled until "
43           "-unroll-threshold loop size is reached."));
44
45static cl::opt<bool>
46UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
47  cl::desc("Unroll loops with run-time trip counts"));
48
49namespace {
50  class LoopUnroll : public LoopPass {
51  public:
52    static char ID; // Pass ID, replacement for typeid
53    LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
54      CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
55      CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
56      CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
57      CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
58
59      UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
60      UserAllowPartial = (P != -1) ||
61                         (UnrollAllowPartial.getNumOccurrences() > 0);
62      UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
63      UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
64
65      initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
66    }
67
68    /// A magic value for use with the Threshold parameter to indicate
69    /// that the loop unroll should be performed regardless of how much
70    /// code expansion would result.
71    static const unsigned NoThreshold = UINT_MAX;
72
73    // Threshold to use when optsize is specified (and there is no
74    // explicit -unroll-threshold).
75    static const unsigned OptSizeUnrollThreshold = 50;
76
77    // Default unroll count for loops with run-time trip count if
78    // -unroll-count is not set
79    static const unsigned UnrollRuntimeCount = 8;
80
81    unsigned CurrentCount;
82    unsigned CurrentThreshold;
83    bool     CurrentAllowPartial;
84    bool     CurrentRuntime;
85    bool     UserCount;            // CurrentCount is user-specified.
86    bool     UserThreshold;        // CurrentThreshold is user-specified.
87    bool     UserAllowPartial;     // CurrentAllowPartial is user-specified.
88    bool     UserRuntime;          // CurrentRuntime is user-specified.
89
90    bool runOnLoop(Loop *L, LPPassManager &LPM) override;
91
92    /// This transformation requires natural loop information & requires that
93    /// loop preheaders be inserted into the CFG...
94    ///
95    void getAnalysisUsage(AnalysisUsage &AU) const override {
96      AU.addRequired<LoopInfo>();
97      AU.addPreserved<LoopInfo>();
98      AU.addRequiredID(LoopSimplifyID);
99      AU.addPreservedID(LoopSimplifyID);
100      AU.addRequiredID(LCSSAID);
101      AU.addPreservedID(LCSSAID);
102      AU.addRequired<ScalarEvolution>();
103      AU.addPreserved<ScalarEvolution>();
104      AU.addRequired<TargetTransformInfo>();
105      // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
106      // If loop unroll does not preserve dom info then LCSSA pass on next
107      // loop will receive invalid dom info.
108      // For now, recreate dom info, if loop is unrolled.
109      AU.addPreserved<DominatorTreeWrapperPass>();
110    }
111  };
112}
113
114char LoopUnroll::ID = 0;
115INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
116INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
117INITIALIZE_PASS_DEPENDENCY(LoopInfo)
118INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
119INITIALIZE_PASS_DEPENDENCY(LCSSA)
120INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
121INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
122
123Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
124                                 int Runtime) {
125  return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
126}
127
128Pass *llvm::createSimpleLoopUnrollPass() {
129  return llvm::createLoopUnrollPass(-1, -1, 0, 0);
130}
131
132/// ApproximateLoopSize - Approximate the size of the loop.
133static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
134                                    bool &NotDuplicatable,
135                                    const TargetTransformInfo &TTI) {
136  CodeMetrics Metrics;
137  for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
138       I != E; ++I)
139    Metrics.analyzeBasicBlock(*I, TTI);
140  NumCalls = Metrics.NumInlineCandidates;
141  NotDuplicatable = Metrics.notDuplicatable;
142
143  unsigned LoopSize = Metrics.NumInsts;
144
145  // Don't allow an estimate of size zero.  This would allows unrolling of loops
146  // with huge iteration counts, which is a compile time problem even if it's
147  // not a problem for code quality.
148  if (LoopSize == 0) LoopSize = 1;
149
150  return LoopSize;
151}
152
153bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
154  if (skipOptnoneFunction(L))
155    return false;
156
157  LoopInfo *LI = &getAnalysis<LoopInfo>();
158  ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
159  const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>();
160
161  BasicBlock *Header = L->getHeader();
162  DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
163        << "] Loop %" << Header->getName() << "\n");
164  (void)Header;
165
166  TargetTransformInfo::UnrollingPreferences UP;
167  UP.Threshold = CurrentThreshold;
168  UP.OptSizeThreshold = OptSizeUnrollThreshold;
169  UP.PartialThreshold = CurrentThreshold;
170  UP.PartialOptSizeThreshold = OptSizeUnrollThreshold;
171  UP.Count = CurrentCount;
172  UP.MaxCount = UINT_MAX;
173  UP.Partial = CurrentAllowPartial;
174  UP.Runtime = CurrentRuntime;
175  TTI.getUnrollingPreferences(L, UP);
176
177  // Determine the current unrolling threshold.  While this is normally set
178  // from UnrollThreshold, it is overridden to a smaller value if the current
179  // function is marked as optimize-for-size, and the unroll threshold was
180  // not user specified.
181  unsigned Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
182  unsigned PartialThreshold =
183    UserThreshold ? CurrentThreshold : UP.PartialThreshold;
184  if (!UserThreshold &&
185      Header->getParent()->getAttributes().
186        hasAttribute(AttributeSet::FunctionIndex,
187                     Attribute::OptimizeForSize)) {
188    Threshold = UP.OptSizeThreshold;
189    PartialThreshold = UP.PartialOptSizeThreshold;
190  }
191
192  // Find trip count and trip multiple if count is not available
193  unsigned TripCount = 0;
194  unsigned TripMultiple = 1;
195  // Find "latch trip count". UnrollLoop assumes that control cannot exit
196  // via the loop latch on any iteration prior to TripCount. The loop may exit
197  // early via an earlier branch.
198  BasicBlock *LatchBlock = L->getLoopLatch();
199  if (LatchBlock) {
200    TripCount = SE->getSmallConstantTripCount(L, LatchBlock);
201    TripMultiple = SE->getSmallConstantTripMultiple(L, LatchBlock);
202  }
203
204  bool Runtime = UserRuntime ? CurrentRuntime : UP.Runtime;
205
206  // Use a default unroll-count if the user doesn't specify a value
207  // and the trip count is a run-time value.  The default is different
208  // for run-time or compile-time trip count loops.
209  unsigned Count = UserCount ? CurrentCount : UP.Count;
210  if (Runtime && Count == 0 && TripCount == 0)
211    Count = UnrollRuntimeCount;
212
213  if (Count == 0) {
214    // Conservative heuristic: if we know the trip count, see if we can
215    // completely unroll (subject to the threshold, checked below); otherwise
216    // try to find greatest modulo of the trip count which is still under
217    // threshold value.
218    if (TripCount == 0)
219      return false;
220    Count = TripCount;
221  }
222
223  // Enforce the threshold.
224  if (Threshold != NoThreshold && PartialThreshold != NoThreshold) {
225    unsigned NumInlineCandidates;
226    bool notDuplicatable;
227    unsigned LoopSize = ApproximateLoopSize(L, NumInlineCandidates,
228                                            notDuplicatable, TTI);
229    DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
230    if (notDuplicatable) {
231      DEBUG(dbgs() << "  Not unrolling loop which contains non-duplicatable"
232            << " instructions.\n");
233      return false;
234    }
235    if (NumInlineCandidates != 0) {
236      DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
237      return false;
238    }
239    uint64_t Size = (uint64_t)LoopSize*Count;
240    if (TripCount != 1 && Size > Threshold) {
241      DEBUG(dbgs() << "  Too large to fully unroll with count: " << Count
242            << " because size: " << Size << ">" << Threshold << "\n");
243      bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
244      if (!AllowPartial && !(Runtime && TripCount == 0)) {
245        DEBUG(dbgs() << "  will not try to unroll partially because "
246              << "-unroll-allow-partial not given\n");
247        return false;
248      }
249      if (TripCount) {
250        // Reduce unroll count to be modulo of TripCount for partial unrolling
251        Count = PartialThreshold / LoopSize;
252        while (Count != 0 && TripCount%Count != 0)
253          Count--;
254      }
255      else if (Runtime) {
256        // Reduce unroll count to be a lower power-of-two value
257        while (Count != 0 && Size > PartialThreshold) {
258          Count >>= 1;
259          Size = LoopSize*Count;
260        }
261      }
262      if (Count > UP.MaxCount)
263        Count = UP.MaxCount;
264      if (Count < 2) {
265        DEBUG(dbgs() << "  could not unroll partially\n");
266        return false;
267      }
268      DEBUG(dbgs() << "  partially unrolling with count: " << Count << "\n");
269    }
270  }
271
272  // Unroll the loop.
273  if (!UnrollLoop(L, Count, TripCount, Runtime, TripMultiple, LI, this, &LPM))
274    return false;
275
276  return true;
277}
278