036200bf09f5609c74ed9486e47f6b96ec8d3361
[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 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/Analysis/AssumptionCache.h"
17 #include "llvm/Analysis/CodeMetrics.h"
18 #include "llvm/Analysis/FunctionTargetTransformInfo.h"
19 #include "llvm/Analysis/LoopPass.h"
20 #include "llvm/Analysis/ScalarEvolution.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DiagnosticInfo.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Metadata.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Transforms/Utils/UnrollLoop.h"
31 #include <climits>
32
33 using namespace llvm;
34
35 #define DEBUG_TYPE "loop-unroll"
36
37 static cl::opt<unsigned>
38 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
39   cl::desc("The cut-off point for automatic loop unrolling"));
40
41 static cl::opt<unsigned>
42 UnrollCount("unroll-count", cl::init(0), cl::Hidden,
43   cl::desc("Use this unroll count for all loops including those with "
44            "unroll_count pragma values, for testing purposes"));
45
46 static cl::opt<bool>
47 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
48   cl::desc("Allows loops to be partially unrolled until "
49            "-unroll-threshold loop size is reached."));
50
51 static cl::opt<bool>
52 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
53   cl::desc("Unroll loops with run-time trip counts"));
54
55 static cl::opt<unsigned>
56 PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
57   cl::desc("Unrolled size limit for loops with an unroll(full) or "
58            "unroll_count pragma."));
59
60 namespace {
61   class LoopUnroll : public LoopPass {
62   public:
63     static char ID; // Pass ID, replacement for typeid
64     LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
65       CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
66       CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
67       CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
68       CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
69
70       UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
71       UserAllowPartial = (P != -1) ||
72                          (UnrollAllowPartial.getNumOccurrences() > 0);
73       UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
74       UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
75
76       initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
77     }
78
79     /// A magic value for use with the Threshold parameter to indicate
80     /// that the loop unroll should be performed regardless of how much
81     /// code expansion would result.
82     static const unsigned NoThreshold = UINT_MAX;
83
84     // Threshold to use when optsize is specified (and there is no
85     // explicit -unroll-threshold).
86     static const unsigned OptSizeUnrollThreshold = 50;
87
88     // Default unroll count for loops with run-time trip count if
89     // -unroll-count is not set
90     static const unsigned UnrollRuntimeCount = 8;
91
92     unsigned CurrentCount;
93     unsigned CurrentThreshold;
94     bool     CurrentAllowPartial;
95     bool     CurrentRuntime;
96     bool     UserCount;            // CurrentCount is user-specified.
97     bool     UserThreshold;        // CurrentThreshold is user-specified.
98     bool     UserAllowPartial;     // CurrentAllowPartial is user-specified.
99     bool     UserRuntime;          // CurrentRuntime is user-specified.
100
101     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
102
103     /// This transformation requires natural loop information & requires that
104     /// loop preheaders be inserted into the CFG...
105     ///
106     void getAnalysisUsage(AnalysisUsage &AU) const override {
107       AU.addRequired<AssumptionCacheTracker>();
108       AU.addRequired<LoopInfoWrapperPass>();
109       AU.addPreserved<LoopInfoWrapperPass>();
110       AU.addRequiredID(LoopSimplifyID);
111       AU.addPreservedID(LoopSimplifyID);
112       AU.addRequiredID(LCSSAID);
113       AU.addPreservedID(LCSSAID);
114       AU.addRequired<ScalarEvolution>();
115       AU.addPreserved<ScalarEvolution>();
116       AU.addRequired<TargetTransformInfo>();
117       AU.addRequired<FunctionTargetTransformInfo>();
118       // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
119       // If loop unroll does not preserve dom info then LCSSA pass on next
120       // loop will receive invalid dom info.
121       // For now, recreate dom info, if loop is unrolled.
122       AU.addPreserved<DominatorTreeWrapperPass>();
123     }
124
125     // Fill in the UnrollingPreferences parameter with values from the
126     // TargetTransformationInfo.
127     void getUnrollingPreferences(Loop *L, const FunctionTargetTransformInfo &FTTI,
128                                  TargetTransformInfo::UnrollingPreferences &UP) {
129       UP.Threshold = CurrentThreshold;
130       UP.OptSizeThreshold = OptSizeUnrollThreshold;
131       UP.PartialThreshold = CurrentThreshold;
132       UP.PartialOptSizeThreshold = OptSizeUnrollThreshold;
133       UP.Count = CurrentCount;
134       UP.MaxCount = UINT_MAX;
135       UP.Partial = CurrentAllowPartial;
136       UP.Runtime = CurrentRuntime;
137       FTTI.getUnrollingPreferences(L, UP);
138     }
139
140     // Select and return an unroll count based on parameters from
141     // user, unroll preferences, unroll pragmas, or a heuristic.
142     // SetExplicitly is set to true if the unroll count is is set by
143     // the user or a pragma rather than selected heuristically.
144     unsigned
145     selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
146                       unsigned PragmaCount,
147                       const TargetTransformInfo::UnrollingPreferences &UP,
148                       bool &SetExplicitly);
149
150     // Select threshold values used to limit unrolling based on a
151     // total unrolled size.  Parameters Threshold and PartialThreshold
152     // are set to the maximum unrolled size for fully and partially
153     // unrolled loops respectively.
154     void selectThresholds(const Loop *L, bool HasPragma,
155                           const TargetTransformInfo::UnrollingPreferences &UP,
156                           unsigned &Threshold, unsigned &PartialThreshold) {
157       // Determine the current unrolling threshold.  While this is
158       // normally set from UnrollThreshold, it is overridden to a
159       // smaller value if the current function is marked as
160       // optimize-for-size, and the unroll threshold was not user
161       // specified.
162       Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
163       PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold;
164       if (!UserThreshold &&
165           L->getHeader()->getParent()->getAttributes().
166               hasAttribute(AttributeSet::FunctionIndex,
167                            Attribute::OptimizeForSize)) {
168         Threshold = UP.OptSizeThreshold;
169         PartialThreshold = UP.PartialOptSizeThreshold;
170       }
171       if (HasPragma) {
172         // If the loop has an unrolling pragma, we want to be more
173         // aggressive with unrolling limits.  Set thresholds to at
174         // least the PragmaTheshold value which is larger than the
175         // default limits.
176         if (Threshold != NoThreshold)
177           Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold);
178         if (PartialThreshold != NoThreshold)
179           PartialThreshold =
180               std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold);
181       }
182     }
183   };
184 }
185
186 char LoopUnroll::ID = 0;
187 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
188 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
189 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
190 INITIALIZE_PASS_DEPENDENCY(FunctionTargetTransformInfo)
191 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
192 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
193 INITIALIZE_PASS_DEPENDENCY(LCSSA)
194 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
195 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
196
197 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
198                                  int Runtime) {
199   return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
200 }
201
202 Pass *llvm::createSimpleLoopUnrollPass() {
203   return llvm::createLoopUnrollPass(-1, -1, 0, 0);
204 }
205
206 /// ApproximateLoopSize - Approximate the size of the loop.
207 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
208                                     bool &NotDuplicatable,
209                                     const TargetTransformInfo &TTI,
210                                     AssumptionCache *AC) {
211   SmallPtrSet<const Value *, 32> EphValues;
212   CodeMetrics::collectEphemeralValues(L, AC, EphValues);
213
214   CodeMetrics Metrics;
215   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
216        I != E; ++I)
217     Metrics.analyzeBasicBlock(*I, TTI, EphValues);
218   NumCalls = Metrics.NumInlineCandidates;
219   NotDuplicatable = Metrics.notDuplicatable;
220
221   unsigned LoopSize = Metrics.NumInsts;
222
223   // Don't allow an estimate of size zero.  This would allows unrolling of loops
224   // with huge iteration counts, which is a compile time problem even if it's
225   // not a problem for code quality. Also, the code using this size may assume
226   // that each loop has at least three instructions (likely a conditional
227   // branch, a comparison feeding that branch, and some kind of loop increment
228   // feeding that comparison instruction).
229   LoopSize = std::max(LoopSize, 3u);
230
231   return LoopSize;
232 }
233
234 // Returns the loop hint metadata node with the given name (for example,
235 // "llvm.loop.unroll.count").  If no such metadata node exists, then nullptr is
236 // returned.
237 static const MDNode *GetUnrollMetadata(const Loop *L, StringRef Name) {
238   MDNode *LoopID = L->getLoopID();
239   if (!LoopID)
240     return nullptr;
241
242   // First operand should refer to the loop id itself.
243   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
244   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
245
246   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
247     const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
248     if (!MD)
249       continue;
250
251     const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
252     if (!S)
253       continue;
254
255     if (Name.equals(S->getString()))
256       return MD;
257   }
258   return nullptr;
259 }
260
261 // Returns true if the loop has an unroll(full) pragma.
262 static bool HasUnrollFullPragma(const Loop *L) {
263   return GetUnrollMetadata(L, "llvm.loop.unroll.full");
264 }
265
266 // Returns true if the loop has an unroll(disable) pragma.
267 static bool HasUnrollDisablePragma(const Loop *L) {
268   return GetUnrollMetadata(L, "llvm.loop.unroll.disable");
269 }
270
271 // If loop has an unroll_count pragma return the (necessarily
272 // positive) value from the pragma.  Otherwise return 0.
273 static unsigned UnrollCountPragmaValue(const Loop *L) {
274   const MDNode *MD = GetUnrollMetadata(L, "llvm.loop.unroll.count");
275   if (MD) {
276     assert(MD->getNumOperands() == 2 &&
277            "Unroll count hint metadata should have two operands.");
278     unsigned Count =
279         mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
280     assert(Count >= 1 && "Unroll count must be positive.");
281     return Count;
282   }
283   return 0;
284 }
285
286 // Remove existing unroll metadata and add unroll disable metadata to
287 // indicate the loop has already been unrolled.  This prevents a loop
288 // from being unrolled more than is directed by a pragma if the loop
289 // unrolling pass is run more than once (which it generally is).
290 static void SetLoopAlreadyUnrolled(Loop *L) {
291   MDNode *LoopID = L->getLoopID();
292   if (!LoopID) return;
293
294   // First remove any existing loop unrolling metadata.
295   SmallVector<Metadata *, 4> MDs;
296   // Reserve first location for self reference to the LoopID metadata node.
297   MDs.push_back(nullptr);
298   for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
299     bool IsUnrollMetadata = false;
300     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
301     if (MD) {
302       const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
303       IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
304     }
305     if (!IsUnrollMetadata)
306       MDs.push_back(LoopID->getOperand(i));
307   }
308
309   // Add unroll(disable) metadata to disable future unrolling.
310   LLVMContext &Context = L->getHeader()->getContext();
311   SmallVector<Metadata *, 1> DisableOperands;
312   DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
313   MDNode *DisableNode = MDNode::get(Context, DisableOperands);
314   MDs.push_back(DisableNode);
315
316   MDNode *NewLoopID = MDNode::get(Context, MDs);
317   // Set operand 0 to refer to the loop id itself.
318   NewLoopID->replaceOperandWith(0, NewLoopID);
319   L->setLoopID(NewLoopID);
320 }
321
322 unsigned LoopUnroll::selectUnrollCount(
323     const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
324     unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
325     bool &SetExplicitly) {
326   SetExplicitly = true;
327
328   // User-specified count (either as a command-line option or
329   // constructor parameter) has highest precedence.
330   unsigned Count = UserCount ? CurrentCount : 0;
331
332   // If there is no user-specified count, unroll pragmas have the next
333   // highest precendence.
334   if (Count == 0) {
335     if (PragmaCount) {
336       Count = PragmaCount;
337     } else if (PragmaFullUnroll) {
338       Count = TripCount;
339     }
340   }
341
342   if (Count == 0)
343     Count = UP.Count;
344
345   if (Count == 0) {
346     SetExplicitly = false;
347     if (TripCount == 0)
348       // Runtime trip count.
349       Count = UnrollRuntimeCount;
350     else
351       // Conservative heuristic: if we know the trip count, see if we can
352       // completely unroll (subject to the threshold, checked below); otherwise
353       // try to find greatest modulo of the trip count which is still under
354       // threshold value.
355       Count = TripCount;
356   }
357   if (TripCount && Count > TripCount)
358     return TripCount;
359   return Count;
360 }
361
362 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
363   if (skipOptnoneFunction(L))
364     return false;
365
366   LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
367   ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
368   const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>();
369   const FunctionTargetTransformInfo &FTTI =
370       getAnalysis<FunctionTargetTransformInfo>();
371   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
372       *L->getHeader()->getParent());
373
374   BasicBlock *Header = L->getHeader();
375   DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
376         << "] Loop %" << Header->getName() << "\n");
377
378   if (HasUnrollDisablePragma(L)) {
379     return false;
380   }
381   bool PragmaFullUnroll = HasUnrollFullPragma(L);
382   unsigned PragmaCount = UnrollCountPragmaValue(L);
383   bool HasPragma = PragmaFullUnroll || PragmaCount > 0;
384
385   TargetTransformInfo::UnrollingPreferences UP;
386   getUnrollingPreferences(L, FTTI, UP);
387
388   // Find trip count and trip multiple if count is not available
389   unsigned TripCount = 0;
390   unsigned TripMultiple = 1;
391   // If there are multiple exiting blocks but one of them is the latch, use the
392   // latch for the trip count estimation. Otherwise insist on a single exiting
393   // block for the trip count estimation.
394   BasicBlock *ExitingBlock = L->getLoopLatch();
395   if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
396     ExitingBlock = L->getExitingBlock();
397   if (ExitingBlock) {
398     TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
399     TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
400   }
401
402   // Select an initial unroll count.  This may be reduced later based
403   // on size thresholds.
404   bool CountSetExplicitly;
405   unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
406                                      PragmaCount, UP, CountSetExplicitly);
407
408   unsigned NumInlineCandidates;
409   bool notDuplicatable;
410   unsigned LoopSize =
411       ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC);
412   DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
413
414   // When computing the unrolled size, note that the conditional branch on the
415   // backedge and the comparison feeding it are not replicated like the rest of
416   // the loop body (which is why 2 is subtracted).
417   uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2;
418   if (notDuplicatable) {
419     DEBUG(dbgs() << "  Not unrolling loop which contains non-duplicatable"
420                  << " instructions.\n");
421     return false;
422   }
423   if (NumInlineCandidates != 0) {
424     DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
425     return false;
426   }
427
428   unsigned Threshold, PartialThreshold;
429   selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold);
430
431   // Given Count, TripCount and thresholds determine the type of
432   // unrolling which is to be performed.
433   enum { Full = 0, Partial = 1, Runtime = 2 };
434   int Unrolling;
435   if (TripCount && Count == TripCount) {
436     if (Threshold != NoThreshold && UnrolledSize > Threshold) {
437       DEBUG(dbgs() << "  Too large to fully unroll with count: " << Count
438                    << " because size: " << UnrolledSize << ">" << Threshold
439                    << "\n");
440       Unrolling = Partial;
441     } else {
442       Unrolling = Full;
443     }
444   } else if (TripCount && Count < TripCount) {
445     Unrolling = Partial;
446   } else {
447     Unrolling = Runtime;
448   }
449
450   // Reduce count based on the type of unrolling and the threshold values.
451   unsigned OriginalCount = Count;
452   bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime;
453   if (Unrolling == Partial) {
454     bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
455     if (!AllowPartial && !CountSetExplicitly) {
456       DEBUG(dbgs() << "  will not try to unroll partially because "
457                    << "-unroll-allow-partial not given\n");
458       return false;
459     }
460     if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
461       // Reduce unroll count to be modulo of TripCount for partial unrolling.
462       Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2);
463       while (Count != 0 && TripCount % Count != 0)
464         Count--;
465     }
466   } else if (Unrolling == Runtime) {
467     if (!AllowRuntime && !CountSetExplicitly) {
468       DEBUG(dbgs() << "  will not try to unroll loop with runtime trip count "
469                    << "-unroll-runtime not given\n");
470       return false;
471     }
472     // Reduce unroll count to be the largest power-of-two factor of
473     // the original count which satisfies the threshold limit.
474     while (Count != 0 && UnrolledSize > PartialThreshold) {
475       Count >>= 1;
476       UnrolledSize = (LoopSize-2) * Count + 2;
477     }
478     if (Count > UP.MaxCount)
479       Count = UP.MaxCount;
480     DEBUG(dbgs() << "  partially unrolling with count: " << Count << "\n");
481   }
482
483   if (HasPragma) {
484     if (PragmaCount != 0)
485       // If loop has an unroll count pragma mark loop as unrolled to prevent
486       // unrolling beyond that requested by the pragma.
487       SetLoopAlreadyUnrolled(L);
488
489     // Emit optimization remarks if we are unable to unroll the loop
490     // as directed by a pragma.
491     DebugLoc LoopLoc = L->getStartLoc();
492     Function *F = Header->getParent();
493     LLVMContext &Ctx = F->getContext();
494     if (PragmaFullUnroll && PragmaCount == 0) {
495       if (TripCount && Count != TripCount) {
496         emitOptimizationRemarkMissed(
497             Ctx, DEBUG_TYPE, *F, LoopLoc,
498             "Unable to fully unroll loop as directed by unroll(full) pragma "
499             "because unrolled size is too large.");
500       } else if (!TripCount) {
501         emitOptimizationRemarkMissed(
502             Ctx, DEBUG_TYPE, *F, LoopLoc,
503             "Unable to fully unroll loop as directed by unroll(full) pragma "
504             "because loop has a runtime trip count.");
505       }
506     } else if (PragmaCount > 0 && Count != OriginalCount) {
507       emitOptimizationRemarkMissed(
508           Ctx, DEBUG_TYPE, *F, LoopLoc,
509           "Unable to unroll loop the number of times directed by "
510           "unroll_count pragma because unrolled size is too large.");
511     }
512   }
513
514   if (Unrolling != Full && Count < 2) {
515     // Partial unrolling by 1 is a nop.  For full unrolling, a factor
516     // of 1 makes sense because loop control can be eliminated.
517     return false;
518   }
519
520   // Unroll the loop.
521   if (!UnrollLoop(L, Count, TripCount, AllowRuntime, TripMultiple, LI, this,
522                   &LPM, &AC))
523     return false;
524
525   return true;
526 }