blob: d9236a2c773b66b216418d93b282053506eed793 [file] [log] [blame]
Chris Lattner946b2552004-04-18 05:20:17 +00001//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattner946b2552004-04-18 05:20:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattner946b2552004-04-18 05:20:17 +00008//===----------------------------------------------------------------------===//
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.
Chris Lattner946b2552004-04-18 05:20:17 +000013//===----------------------------------------------------------------------===//
14
Chris Lattner946b2552004-04-18 05:20:17 +000015#include "llvm/Transforms/Scalar.h"
Chandler Carruth3b057b32015-02-13 03:57:40 +000016#include "llvm/ADT/SetVector.h"
James Molloyefbba722015-09-10 10:22:12 +000017#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000018#include "llvm/Analysis/AssumptionCache.h"
Chris Lattner679572e2011-01-02 07:35:53 +000019#include "llvm/Analysis/CodeMetrics.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000020#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/Analysis/LoopPass.h"
Dan Gohman0141c132010-07-26 18:11:16 +000022#include "llvm/Analysis/ScalarEvolution.h"
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000023#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000024#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/DataLayout.h"
Eli Benderskyff903242014-06-16 23:53:02 +000026#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000027#include "llvm/IR/Dominators.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000028#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/IntrinsicInst.h"
Eli Benderskyff903242014-06-16 23:53:02 +000030#include "llvm/IR/Metadata.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000031#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000033#include "llvm/Support/raw_ostream.h"
Dan Gohman3dc2d922008-05-14 00:24:14 +000034#include "llvm/Transforms/Utils/UnrollLoop.h"
Duncan Sands67933e62008-05-16 09:30:00 +000035#include <climits>
Chris Lattner946b2552004-04-18 05:20:17 +000036
Dan Gohman3dc2d922008-05-14 00:24:14 +000037using namespace llvm;
Chris Lattner946b2552004-04-18 05:20:17 +000038
Chandler Carruth964daaa2014-04-22 02:55:47 +000039#define DEBUG_TYPE "loop-unroll"
40
Dan Gohmand78c4002008-05-13 00:00:25 +000041static cl::opt<unsigned>
Chandler Carruth9dabd142015-06-05 17:01:43 +000042 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
43 cl::desc("The baseline cost threshold for loop unrolling"));
44
45static cl::opt<unsigned> UnrollPercentDynamicCostSavedThreshold(
46 "unroll-percent-dynamic-cost-saved-threshold", cl::init(20), cl::Hidden,
47 cl::desc("The percentage of estimated dynamic cost which must be saved by "
48 "unrolling to allow unrolling up to the max threshold."));
49
50static cl::opt<unsigned> UnrollDynamicCostSavingsDiscount(
51 "unroll-dynamic-cost-savings-discount", cl::init(2000), cl::Hidden,
52 cl::desc("This is the amount discounted from the total unroll cost when "
53 "the unrolled form has a high dynamic cost savings (triggered by "
54 "the '-unroll-perecent-dynamic-cost-saved-threshold' flag)."));
Dan Gohmand78c4002008-05-13 00:00:25 +000055
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000056static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
Chandler Carruth1fbc3162015-02-13 05:31:46 +000057 "unroll-max-iteration-count-to-analyze", cl::init(0), cl::Hidden,
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000058 cl::desc("Don't allow loop unrolling to simulate more than this number of"
59 "iterations when checking full unroll profitability"));
60
Dan Gohmand78c4002008-05-13 00:00:25 +000061static cl::opt<unsigned>
62UnrollCount("unroll-count", cl::init(0), cl::Hidden,
Eli Benderskyff903242014-06-16 23:53:02 +000063 cl::desc("Use this unroll count for all loops including those with "
64 "unroll_count pragma values, for testing purposes"));
Dan Gohmand78c4002008-05-13 00:00:25 +000065
Matthijs Kooijman98b5c162008-07-29 13:21:23 +000066static cl::opt<bool>
67UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
68 cl::desc("Allows loops to be partially unrolled until "
69 "-unroll-threshold loop size is reached."));
70
Andrew Trickd04d15292011-12-09 06:19:40 +000071static cl::opt<bool>
72UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
73 cl::desc("Unroll loops with run-time trip counts"));
74
Eli Benderskyff903242014-06-16 23:53:02 +000075static cl::opt<unsigned>
76PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
Mark Heffernane6b4ba12014-07-23 17:31:37 +000077 cl::desc("Unrolled size limit for loops with an unroll(full) or "
Eli Benderskyff903242014-06-16 23:53:02 +000078 "unroll_count pragma."));
79
Chris Lattner79a42ac2006-12-19 21:40:18 +000080namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +000081 class LoopUnroll : public LoopPass {
Chris Lattner946b2552004-04-18 05:20:17 +000082 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +000083 static char ID; // Pass ID, replacement for typeid
Hal Finkel081eaef2013-11-05 00:08:03 +000084 LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
Chris Lattner35a65b22011-04-14 02:27:25 +000085 CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
Chandler Carruth9dabd142015-06-05 17:01:43 +000086 CurrentPercentDynamicCostSavedThreshold =
87 UnrollPercentDynamicCostSavedThreshold;
88 CurrentDynamicCostSavingsDiscount = UnrollDynamicCostSavingsDiscount;
Chris Lattner35a65b22011-04-14 02:27:25 +000089 CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
Junjie Gu7c3b4592011-04-13 16:15:29 +000090 CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
Hal Finkel081eaef2013-11-05 00:08:03 +000091 CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
Junjie Gu7c3b4592011-04-13 16:15:29 +000092
93 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
Chandler Carruth9dabd142015-06-05 17:01:43 +000094 UserPercentDynamicCostSavedThreshold =
95 (UnrollPercentDynamicCostSavedThreshold.getNumOccurrences() > 0);
96 UserDynamicCostSavingsDiscount =
97 (UnrollDynamicCostSavingsDiscount.getNumOccurrences() > 0);
Hal Finkel8f2e7002013-09-11 19:25:43 +000098 UserAllowPartial = (P != -1) ||
99 (UnrollAllowPartial.getNumOccurrences() > 0);
Hal Finkel081eaef2013-11-05 00:08:03 +0000100 UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
Hal Finkel8f2e7002013-09-11 19:25:43 +0000101 UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
Andrew Trick279e7a62011-07-23 00:29:16 +0000102
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000103 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
104 }
Devang Patel09f162c2007-05-01 21:15:47 +0000105
Dan Gohman2980d9d2007-05-11 20:53:41 +0000106 /// A magic value for use with the Threshold parameter to indicate
107 /// that the loop unroll should be performed regardless of how much
108 /// code expansion would result.
109 static const unsigned NoThreshold = UINT_MAX;
Andrew Trick279e7a62011-07-23 00:29:16 +0000110
Owen Andersona4d9c782010-09-07 23:15:30 +0000111 // Threshold to use when optsize is specified (and there is no
112 // explicit -unroll-threshold).
113 static const unsigned OptSizeUnrollThreshold = 50;
Andrew Trick279e7a62011-07-23 00:29:16 +0000114
Andrew Trickd04d15292011-12-09 06:19:40 +0000115 // Default unroll count for loops with run-time trip count if
116 // -unroll-count is not set
117 static const unsigned UnrollRuntimeCount = 8;
118
Junjie Gu7c3b4592011-04-13 16:15:29 +0000119 unsigned CurrentCount;
Owen Andersona4d9c782010-09-07 23:15:30 +0000120 unsigned CurrentThreshold;
Chandler Carruth9dabd142015-06-05 17:01:43 +0000121 unsigned CurrentPercentDynamicCostSavedThreshold;
122 unsigned CurrentDynamicCostSavingsDiscount;
123 bool CurrentAllowPartial;
124 bool CurrentRuntime;
125
126 // Flags for whether the 'current' settings are user-specified.
127 bool UserCount;
128 bool UserThreshold;
129 bool UserPercentDynamicCostSavedThreshold;
130 bool UserDynamicCostSavingsDiscount;
131 bool UserAllowPartial;
132 bool UserRuntime;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000133
Craig Topper3e4c6972014-03-05 09:10:37 +0000134 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Chris Lattner946b2552004-04-18 05:20:17 +0000135
136 /// This transformation requires natural loop information & requires that
137 /// loop preheaders be inserted into the CFG...
138 ///
Craig Topper3e4c6972014-03-05 09:10:37 +0000139 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth66b31302015-01-04 12:03:27 +0000140 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000141 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000142 AU.addRequired<LoopInfoWrapperPass>();
143 AU.addPreserved<LoopInfoWrapperPass>();
Dan Gohman0141c132010-07-26 18:11:16 +0000144 AU.addRequiredID(LoopSimplifyID);
145 AU.addPreservedID(LoopSimplifyID);
146 AU.addRequiredID(LCSSAID);
147 AU.addPreservedID(LCSSAID);
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000148 AU.addRequired<ScalarEvolutionWrapperPass>();
149 AU.addPreserved<ScalarEvolutionWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000150 AU.addRequired<TargetTransformInfoWrapperPass>();
Devang Patelf94b9822008-07-03 07:04:22 +0000151 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
152 // If loop unroll does not preserve dom info then LCSSA pass on next
153 // loop will receive invalid dom info.
154 // For now, recreate dom info, if loop is unrolled.
Chandler Carruth73523022014-01-13 13:07:17 +0000155 AU.addPreserved<DominatorTreeWrapperPass>();
James Molloyefbba722015-09-10 10:22:12 +0000156 AU.addPreserved<GlobalsAAWrapperPass>();
Chris Lattner946b2552004-04-18 05:20:17 +0000157 }
Eli Benderskyff903242014-06-16 23:53:02 +0000158
159 // Fill in the UnrollingPreferences parameter with values from the
160 // TargetTransformationInfo.
Chandler Carruth21fc1952015-02-01 14:37:03 +0000161 void getUnrollingPreferences(Loop *L, const TargetTransformInfo &TTI,
Eli Benderskyff903242014-06-16 23:53:02 +0000162 TargetTransformInfo::UnrollingPreferences &UP) {
163 UP.Threshold = CurrentThreshold;
Chandler Carruth9dabd142015-06-05 17:01:43 +0000164 UP.PercentDynamicCostSavedThreshold =
165 CurrentPercentDynamicCostSavedThreshold;
166 UP.DynamicCostSavingsDiscount = CurrentDynamicCostSavingsDiscount;
Eli Benderskyff903242014-06-16 23:53:02 +0000167 UP.OptSizeThreshold = OptSizeUnrollThreshold;
168 UP.PartialThreshold = CurrentThreshold;
169 UP.PartialOptSizeThreshold = OptSizeUnrollThreshold;
170 UP.Count = CurrentCount;
171 UP.MaxCount = UINT_MAX;
172 UP.Partial = CurrentAllowPartial;
173 UP.Runtime = CurrentRuntime;
Sanjoy Dase178f462015-04-14 03:20:38 +0000174 UP.AllowExpensiveTripCount = false;
Chandler Carruth21fc1952015-02-01 14:37:03 +0000175 TTI.getUnrollingPreferences(L, UP);
Eli Benderskyff903242014-06-16 23:53:02 +0000176 }
177
178 // Select and return an unroll count based on parameters from
179 // user, unroll preferences, unroll pragmas, or a heuristic.
180 // SetExplicitly is set to true if the unroll count is is set by
181 // the user or a pragma rather than selected heuristically.
182 unsigned
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000183 selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
Eli Benderskyff903242014-06-16 23:53:02 +0000184 unsigned PragmaCount,
185 const TargetTransformInfo::UnrollingPreferences &UP,
186 bool &SetExplicitly);
187
Eli Benderskyff903242014-06-16 23:53:02 +0000188 // Select threshold values used to limit unrolling based on a
189 // total unrolled size. Parameters Threshold and PartialThreshold
190 // are set to the maximum unrolled size for fully and partially
191 // unrolled loops respectively.
Mark Heffernan89391542015-08-10 17:28:08 +0000192 void selectThresholds(const Loop *L, bool UsePragmaThreshold,
Eli Benderskyff903242014-06-16 23:53:02 +0000193 const TargetTransformInfo::UnrollingPreferences &UP,
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000194 unsigned &Threshold, unsigned &PartialThreshold,
Chandler Carruth9dabd142015-06-05 17:01:43 +0000195 unsigned &PercentDynamicCostSavedThreshold,
196 unsigned &DynamicCostSavingsDiscount) {
Eli Benderskyff903242014-06-16 23:53:02 +0000197 // Determine the current unrolling threshold. While this is
198 // normally set from UnrollThreshold, it is overridden to a
199 // smaller value if the current function is marked as
200 // optimize-for-size, and the unroll threshold was not user
201 // specified.
202 Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
203 PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold;
Chandler Carruth9dabd142015-06-05 17:01:43 +0000204 PercentDynamicCostSavedThreshold =
205 UserPercentDynamicCostSavedThreshold
206 ? CurrentPercentDynamicCostSavedThreshold
207 : UP.PercentDynamicCostSavedThreshold;
208 DynamicCostSavingsDiscount = UserDynamicCostSavingsDiscount
209 ? CurrentDynamicCostSavingsDiscount
210 : UP.DynamicCostSavingsDiscount;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000211
Eli Benderskyff903242014-06-16 23:53:02 +0000212 if (!UserThreshold &&
Sanjay Patel924879a2015-08-04 15:49:57 +0000213 // FIXME: Use Function::optForSize().
Duncan P. N. Exon Smith2c79ad92015-02-14 01:11:29 +0000214 L->getHeader()->getParent()->hasFnAttribute(
215 Attribute::OptimizeForSize)) {
Eli Benderskyff903242014-06-16 23:53:02 +0000216 Threshold = UP.OptSizeThreshold;
217 PartialThreshold = UP.PartialOptSizeThreshold;
218 }
Mark Heffernan89391542015-08-10 17:28:08 +0000219 if (UsePragmaThreshold) {
Eli Benderskyff903242014-06-16 23:53:02 +0000220 // If the loop has an unrolling pragma, we want to be more
221 // aggressive with unrolling limits. Set thresholds to at
222 // least the PragmaTheshold value which is larger than the
223 // default limits.
224 if (Threshold != NoThreshold)
225 Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold);
226 if (PartialThreshold != NoThreshold)
227 PartialThreshold =
228 std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold);
229 }
230 }
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000231 bool canUnrollCompletely(Loop *L, unsigned Threshold,
Chandler Carruth9dabd142015-06-05 17:01:43 +0000232 unsigned PercentDynamicCostSavedThreshold,
233 unsigned DynamicCostSavingsDiscount,
Sanjoy Dasad714b12015-06-06 05:24:10 +0000234 uint64_t UnrolledCost, uint64_t RolledDynamicCost);
Chris Lattner946b2552004-04-18 05:20:17 +0000235 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000236}
Chris Lattner946b2552004-04-18 05:20:17 +0000237
Dan Gohmand78c4002008-05-13 00:00:25 +0000238char LoopUnroll::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000239INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
Chandler Carruth705b1852015-01-31 03:43:40 +0000240INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chandler Carruth66b31302015-01-04 12:03:27 +0000241INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000242INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000243INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000244INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
245INITIALIZE_PASS_DEPENDENCY(LCSSA)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000246INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000247INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000248
Hal Finkel081eaef2013-11-05 00:08:03 +0000249Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
250 int Runtime) {
251 return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
Junjie Gu7c3b4592011-04-13 16:15:29 +0000252}
Chris Lattner946b2552004-04-18 05:20:17 +0000253
Hal Finkel86b30642014-03-31 23:23:51 +0000254Pass *llvm::createSimpleLoopUnrollPass() {
255 return llvm::createLoopUnrollPass(-1, -1, 0, 0);
256}
257
Benjamin Kramer51f6096c2015-03-23 12:30:58 +0000258namespace {
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000259// This class is used to get an estimate of the optimization effects that we
260// could get from complete loop unrolling. It comes from the fact that some
261// loads might be replaced with concrete constant values and that could trigger
262// a chain of instruction simplifications.
263//
264// E.g. we might have:
265// int a[] = {0, 1, 0};
266// v = 0;
267// for (i = 0; i < 3; i ++)
268// v += b[i]*a[i];
269// If we completely unroll the loop, we would get:
270// v = b[0]*a[0] + b[1]*a[1] + b[2]*a[2]
271// Which then will be simplified to:
272// v = b[0]* 0 + b[1]* 1 + b[2]* 0
273// And finally:
274// v = b[1]
Chandler Carruth02156082015-05-22 17:41:35 +0000275class UnrolledInstAnalyzer : private InstVisitor<UnrolledInstAnalyzer, bool> {
276 typedef InstVisitor<UnrolledInstAnalyzer, bool> Base;
277 friend class InstVisitor<UnrolledInstAnalyzer, bool>;
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000278 struct SimplifiedAddress {
279 Value *Base = nullptr;
280 ConstantInt *Offset = nullptr;
281 };
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000282
Chandler Carruth02156082015-05-22 17:41:35 +0000283public:
284 UnrolledInstAnalyzer(unsigned Iteration,
285 DenseMap<Value *, Constant *> &SimplifiedValues,
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000286 const Loop *L, ScalarEvolution &SE)
287 : Iteration(Iteration), SimplifiedValues(SimplifiedValues), L(L), SE(SE) {
288 IterationNumber = SE.getConstant(APInt(64, Iteration));
289 }
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000290
Chandler Carruth02156082015-05-22 17:41:35 +0000291 // Allow access to the initial visit method.
292 using Base::visit;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000293
Chandler Carruth02156082015-05-22 17:41:35 +0000294private:
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000295 /// \brief A cache of pointer bases and constant-folded offsets corresponding
296 /// to GEP (or derived from GEP) instructions.
297 ///
298 /// In order to find the base pointer one needs to perform non-trivial
299 /// traversal of the corresponding SCEV expression, so it's good to have the
300 /// results saved.
301 DenseMap<Value *, SimplifiedAddress> SimplifiedAddresses;
302
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000303 /// \brief Number of currently simulated iteration.
304 ///
305 /// If an expression is ConstAddress+Constant, then the Constant is
306 /// Start + Iteration*Step, where Start and Step could be obtained from
Chandler Carruthe1a04622015-05-22 03:02:22 +0000307 /// SCEVGEPCache.
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000308 unsigned Iteration;
309
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000310 /// \brief SCEV expression corresponding to number of currently simulated
311 /// iteration.
312 const SCEV *IterationNumber;
313
314 /// \brief A Value->Constant map for keeping values that we managed to
315 /// constant-fold on the given iteration.
316 ///
317 /// While we walk the loop instructions, we build up and maintain a mapping
318 /// of simplified values specific to this iteration. The idea is to propagate
319 /// any special information we have about loads that can be replaced with
320 /// constants after complete unrolling, and account for likely simplifications
321 /// post-unrolling.
Chandler Carruth02156082015-05-22 17:41:35 +0000322 DenseMap<Value *, Constant *> &SimplifiedValues;
323
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000324 const Loop *L;
325 ScalarEvolution &SE;
326
327 /// \brief Try to simplify instruction \param I using its SCEV expression.
328 ///
329 /// The idea is that some AddRec expressions become constants, which then
330 /// could trigger folding of other instructions. However, that only happens
331 /// for expressions whose start value is also constant, which isn't always the
332 /// case. In another common and important case the start value is just some
333 /// address (i.e. SCEVUnknown) - in this case we compute the offset and save
334 /// it along with the base address instead.
335 bool simplifyInstWithSCEV(Instruction *I) {
336 if (!SE.isSCEVable(I->getType()))
337 return false;
338
339 const SCEV *S = SE.getSCEV(I);
340 if (auto *SC = dyn_cast<SCEVConstant>(S)) {
341 SimplifiedValues[I] = SC->getValue();
342 return true;
343 }
344
345 auto *AR = dyn_cast<SCEVAddRecExpr>(S);
346 if (!AR)
347 return false;
348
349 const SCEV *ValueAtIteration = AR->evaluateAtIteration(IterationNumber, SE);
350 // Check if the AddRec expression becomes a constant.
351 if (auto *SC = dyn_cast<SCEVConstant>(ValueAtIteration)) {
352 SimplifiedValues[I] = SC->getValue();
353 return true;
354 }
355
356 // Check if the offset from the base address becomes a constant.
357 auto *Base = dyn_cast<SCEVUnknown>(SE.getPointerBase(S));
358 if (!Base)
359 return false;
360 auto *Offset =
361 dyn_cast<SCEVConstant>(SE.getMinusSCEV(ValueAtIteration, Base));
362 if (!Offset)
363 return false;
364 SimplifiedAddress Address;
365 Address.Base = Base->getValue();
366 Address.Offset = Offset->getValue();
367 SimplifiedAddresses[I] = Address;
368 return true;
369 }
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000370
371 /// Base case for the instruction visitor.
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000372 bool visitInstruction(Instruction &I) {
373 return simplifyInstWithSCEV(&I);
374 }
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000375
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000376 /// Try to simplify binary operator I.
377 ///
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000378 /// TODO: Probably it's worth to hoist the code for estimating the
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000379 /// simplifications effects to a separate class, since we have a very similar
380 /// code in InlineCost already.
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000381 bool visitBinaryOperator(BinaryOperator &I) {
382 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
383 if (!isa<Constant>(LHS))
384 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
385 LHS = SimpleLHS;
386 if (!isa<Constant>(RHS))
387 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
388 RHS = SimpleRHS;
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000389
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +0000390 Value *SimpleV = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000391 const DataLayout &DL = I.getModule()->getDataLayout();
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +0000392 if (auto FI = dyn_cast<FPMathOperator>(&I))
393 SimpleV =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000394 SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +0000395 else
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000396 SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000397
Chandler Carruthf174a152015-05-22 02:47:29 +0000398 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000399 SimplifiedValues[&I] = C;
Chandler Carruthf174a152015-05-22 02:47:29 +0000400
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000401 if (SimpleV)
402 return true;
403 return Base::visitBinaryOperator(I);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000404 }
405
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000406 /// Try to fold load I.
407 bool visitLoad(LoadInst &I) {
408 Value *AddrOp = I.getPointerOperand();
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000409
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000410 auto AddressIt = SimplifiedAddresses.find(AddrOp);
411 if (AddressIt == SimplifiedAddresses.end())
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000412 return false;
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000413 ConstantInt *SimplifiedAddrOp = AddressIt->second.Offset;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000414
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000415 auto *GV = dyn_cast<GlobalVariable>(AddressIt->second.Base);
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000416 // We're only interested in loads that can be completely folded to a
417 // constant.
Michael Zolotukhin8bb31dd2015-09-22 21:41:29 +0000418 if (!GV || !GV->hasDefinitiveInitializer() || !GV->isConstant())
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000419 return false;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000420
421 ConstantDataSequential *CDS =
422 dyn_cast<ConstantDataSequential>(GV->getInitializer());
423 if (!CDS)
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000424 return false;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000425
Chandler Carrutha6ae8772015-05-12 23:32:56 +0000426 int ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U;
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000427 assert(SimplifiedAddrOp->getValue().getActiveBits() < 64 &&
428 "Unexpectedly large index value.");
429 int64_t Index = SimplifiedAddrOp->getSExtValue() / ElemSize;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000430 if (Index >= CDS->getNumElements()) {
431 // FIXME: For now we conservatively ignore out of bound accesses, but
432 // we're allowed to perform the optimization in this case.
433 return false;
434 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000435
436 Constant *CV = CDS->getElementAsConstant(Index);
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000437 assert(CV && "Constant expected.");
438 SimplifiedValues[&I] = CV;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000439
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000440 return true;
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000441 }
Michael Zolotukhin31b3eaa2015-07-15 00:19:51 +0000442
443 bool visitCastInst(CastInst &I) {
444 // Propagate constants through casts.
445 Constant *COp = dyn_cast<Constant>(I.getOperand(0));
446 if (!COp)
447 COp = SimplifiedValues.lookup(I.getOperand(0));
448 if (COp)
449 if (Constant *C =
450 ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
451 SimplifiedValues[&I] = C;
452 return true;
453 }
454
455 return Base::visitCastInst(I);
456 }
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000457
458 bool visitCmpInst(CmpInst &I) {
459 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
460
461 // First try to handle simplified comparisons.
462 if (!isa<Constant>(LHS))
463 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
464 LHS = SimpleLHS;
465 if (!isa<Constant>(RHS))
466 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
467 RHS = SimpleRHS;
468
469 if (!isa<Constant>(LHS) && !isa<Constant>(RHS)) {
470 auto SimplifiedLHS = SimplifiedAddresses.find(LHS);
471 if (SimplifiedLHS != SimplifiedAddresses.end()) {
472 auto SimplifiedRHS = SimplifiedAddresses.find(RHS);
473 if (SimplifiedRHS != SimplifiedAddresses.end()) {
474 SimplifiedAddress &LHSAddr = SimplifiedLHS->second;
475 SimplifiedAddress &RHSAddr = SimplifiedRHS->second;
476 if (LHSAddr.Base == RHSAddr.Base) {
477 LHS = LHSAddr.Offset;
478 RHS = RHSAddr.Offset;
479 }
480 }
481 }
482 }
483
484 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
485 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
486 if (Constant *C = ConstantExpr::getCompare(I.getPredicate(), CLHS, CRHS)) {
487 SimplifiedValues[&I] = C;
488 return true;
489 }
490 }
491 }
492
493 return Base::visitCmpInst(I);
494 }
Chandler Carruth02156082015-05-22 17:41:35 +0000495};
496} // namespace
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000497
Chandler Carruth6c03dff2015-02-13 04:39:05 +0000498
Chandler Carruth02156082015-05-22 17:41:35 +0000499namespace {
500struct EstimatedUnrollCost {
Chandler Carruth9dabd142015-06-05 17:01:43 +0000501 /// \brief The estimated cost after unrolling.
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000502 int UnrolledCost;
Chandler Carruth302a1332015-02-13 02:10:56 +0000503
Chandler Carruth9dabd142015-06-05 17:01:43 +0000504 /// \brief The estimated dynamic cost of executing the instructions in the
505 /// rolled form.
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000506 int RolledDynamicCost;
Chandler Carruth02156082015-05-22 17:41:35 +0000507};
508}
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000509
Chandler Carruth02156082015-05-22 17:41:35 +0000510/// \brief Figure out if the loop is worth full unrolling.
511///
512/// Complete loop unrolling can make some loads constant, and we need to know
513/// if that would expose any further optimization opportunities. This routine
Michael Zolotukhinc4e4f332015-06-11 22:17:39 +0000514/// estimates this optimization. It computes cost of unrolled loop
515/// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By
516/// dynamic cost we mean that we won't count costs of blocks that are known not
517/// to be executed (i.e. if we have a branch in the loop and we know that at the
518/// given iteration its condition would be resolved to true, we won't add up the
519/// cost of the 'false'-block).
520/// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If
521/// the analysis failed (no benefits expected from the unrolling, or the loop is
522/// too big to analyze), the returned value is None.
Benjamin Kramerfcdb1c12015-08-20 09:57:22 +0000523static Optional<EstimatedUnrollCost>
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000524analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, DominatorTree &DT,
525 ScalarEvolution &SE, const TargetTransformInfo &TTI,
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000526 int MaxUnrolledLoopSize) {
Chandler Carruth02156082015-05-22 17:41:35 +0000527 // We want to be able to scale offsets by the trip count and add more offsets
528 // to them without checking for overflows, and we already don't want to
529 // analyze *massive* trip counts, so we force the max to be reasonably small.
530 assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) &&
531 "The unroll iterations max is too large!");
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000532
Chandler Carruth02156082015-05-22 17:41:35 +0000533 // Don't simulate loops with a big or unknown tripcount
534 if (!UnrollMaxIterationsCountToAnalyze || !TripCount ||
535 TripCount > UnrollMaxIterationsCountToAnalyze)
536 return None;
Chandler Carrutha6ae8772015-05-12 23:32:56 +0000537
Chandler Carruth02156082015-05-22 17:41:35 +0000538 SmallSetVector<BasicBlock *, 16> BBWorklist;
539 DenseMap<Value *, Constant *> SimplifiedValues;
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000540 SmallVector<std::pair<Value *, Constant *>, 4> SimplifiedInputValues;
Chandler Carruth3b057b32015-02-13 03:57:40 +0000541
Chandler Carruth9dabd142015-06-05 17:01:43 +0000542 // The estimated cost of the unrolled form of the loop. We try to estimate
543 // this by simplifying as much as we can while computing the estimate.
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000544 int UnrolledCost = 0;
Chandler Carruth9dabd142015-06-05 17:01:43 +0000545 // We also track the estimated dynamic (that is, actually executed) cost in
546 // the rolled form. This helps identify cases when the savings from unrolling
547 // aren't just exposing dead control flows, but actual reduced dynamic
548 // instructions due to the simplifications which we expect to occur after
549 // unrolling.
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000550 int RolledDynamicCost = 0;
Chandler Carruth8c863752015-02-13 03:48:38 +0000551
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000552 // Ensure that we don't violate the loop structure invariants relied on by
553 // this analysis.
554 assert(L->isLoopSimplifyForm() && "Must put loop into normal form first.");
555 assert(L->isLCSSAForm(DT) &&
556 "Must have loops in LCSSA form to track live-out values.");
557
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000558 DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n");
559
Chandler Carruth02156082015-05-22 17:41:35 +0000560 // Simulate execution of each iteration of the loop counting instructions,
561 // which would be simplified.
562 // Since the same load will take different values on different iterations,
563 // we literally have to go through all loop's iterations.
564 for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000565 DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n");
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000566
567 // Prepare for the iteration by collecting any simplified entry or backedge
568 // inputs.
569 for (Instruction &I : *L->getHeader()) {
570 auto *PHI = dyn_cast<PHINode>(&I);
571 if (!PHI)
572 break;
573
574 // The loop header PHI nodes must have exactly two input: one from the
575 // loop preheader and one from the loop latch.
576 assert(
577 PHI->getNumIncomingValues() == 2 &&
578 "Must have an incoming value only for the preheader and the latch.");
579
580 Value *V = PHI->getIncomingValueForBlock(
581 Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch());
582 Constant *C = dyn_cast<Constant>(V);
583 if (Iteration != 0 && !C)
584 C = SimplifiedValues.lookup(V);
585 if (C)
586 SimplifiedInputValues.push_back({PHI, C});
587 }
588
589 // Now clear and re-populate the map for the next iteration.
Chandler Carruth02156082015-05-22 17:41:35 +0000590 SimplifiedValues.clear();
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000591 while (!SimplifiedInputValues.empty())
592 SimplifiedValues.insert(SimplifiedInputValues.pop_back_val());
593
Michael Zolotukhina60bdb52015-06-08 03:28:06 +0000594 UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, L, SE);
Chandler Carruthf174a152015-05-22 02:47:29 +0000595
Chandler Carruth02156082015-05-22 17:41:35 +0000596 BBWorklist.clear();
597 BBWorklist.insert(L->getHeader());
598 // Note that we *must not* cache the size, this loop grows the worklist.
599 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
600 BasicBlock *BB = BBWorklist[Idx];
Chandler Carruthf174a152015-05-22 02:47:29 +0000601
Chandler Carruth02156082015-05-22 17:41:35 +0000602 // Visit all instructions in the given basic block and try to simplify
603 // it. We don't change the actual IR, just count optimization
604 // opportunities.
605 for (Instruction &I : *BB) {
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000606 int InstCost = TTI.getUserCost(&I);
Chandler Carruth17a04962015-02-13 03:49:41 +0000607
Chandler Carruth02156082015-05-22 17:41:35 +0000608 // Visit the instruction to analyze its loop cost after unrolling,
Chandler Carruth9dabd142015-06-05 17:01:43 +0000609 // and if the visitor returns false, include this instruction in the
610 // unrolled cost.
611 if (!Analyzer.visit(I))
612 UnrolledCost += InstCost;
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000613 else {
614 DEBUG(dbgs() << " " << I
615 << " would be simplified if loop is unrolled.\n");
616 (void)0;
617 }
Chandler Carruth9dabd142015-06-05 17:01:43 +0000618
619 // Also track this instructions expected cost when executing the rolled
620 // loop form.
621 RolledDynamicCost += InstCost;
Chandler Carruth02156082015-05-22 17:41:35 +0000622
623 // If unrolled body turns out to be too big, bail out.
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000624 if (UnrolledCost > MaxUnrolledLoopSize) {
625 DEBUG(dbgs() << " Exceeded threshold.. exiting.\n"
626 << " UnrolledCost: " << UnrolledCost
627 << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize
628 << "\n");
Chandler Carruth02156082015-05-22 17:41:35 +0000629 return None;
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000630 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000631 }
Chandler Carruth415f4122015-02-13 02:17:39 +0000632
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000633 TerminatorInst *TI = BB->getTerminator();
634
635 // Add in the live successors by first checking whether we have terminator
636 // that may be simplified based on the values simplified by this call.
637 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
638 if (BI->isConditional()) {
639 if (Constant *SimpleCond =
640 SimplifiedValues.lookup(BI->getCondition())) {
Michael Zolotukhin3a7d55b2015-07-29 18:10:29 +0000641 BasicBlock *Succ = nullptr;
642 // Just take the first successor if condition is undef
643 if (isa<UndefValue>(SimpleCond))
644 Succ = BI->getSuccessor(0);
645 else
646 Succ = BI->getSuccessor(
647 cast<ConstantInt>(SimpleCond)->isZero() ? 1 : 0);
Michael Zolotukhina425c9d2015-07-28 19:21:21 +0000648 if (L->contains(Succ))
649 BBWorklist.insert(Succ);
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000650 continue;
651 }
652 }
653 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
654 if (Constant *SimpleCond =
655 SimplifiedValues.lookup(SI->getCondition())) {
Michael Zolotukhin3a7d55b2015-07-29 18:10:29 +0000656 BasicBlock *Succ = nullptr;
657 // Just take the first successor if condition is undef
658 if (isa<UndefValue>(SimpleCond))
659 Succ = SI->getSuccessor(0);
660 else
Michael Zolotukhin9f06ef72015-07-29 18:10:33 +0000661 Succ = SI->findCaseValue(cast<ConstantInt>(SimpleCond))
662 .getCaseSuccessor();
Michael Zolotukhina425c9d2015-07-28 19:21:21 +0000663 if (L->contains(Succ))
664 BBWorklist.insert(Succ);
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000665 continue;
666 }
667 }
668
Chandler Carruth02156082015-05-22 17:41:35 +0000669 // Add BB's successors to the worklist.
670 for (BasicBlock *Succ : successors(BB))
671 if (L->contains(Succ))
672 BBWorklist.insert(Succ);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000673 }
Chandler Carruth02156082015-05-22 17:41:35 +0000674
675 // If we found no optimization opportunities on the first iteration, we
676 // won't find them on later ones too.
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000677 if (UnrolledCost == RolledDynamicCost) {
678 DEBUG(dbgs() << " No opportunities found.. exiting.\n"
679 << " UnrolledCost: " << UnrolledCost << "\n");
Chandler Carruth02156082015-05-22 17:41:35 +0000680 return None;
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000681 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000682 }
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000683 DEBUG(dbgs() << "Analysis finished:\n"
684 << "UnrolledCost: " << UnrolledCost << ", "
685 << "RolledDynamicCost: " << RolledDynamicCost << "\n");
Chandler Carruth9dabd142015-06-05 17:01:43 +0000686 return {{UnrolledCost, RolledDynamicCost}};
Chandler Carruth02156082015-05-22 17:41:35 +0000687}
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000688
Dan Gohman49d08a52007-05-08 15:14:19 +0000689/// ApproximateLoopSize - Approximate the size of the loop.
Andrew Trickf7656012011-10-01 01:39:05 +0000690static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000691 bool &NotDuplicatable,
Hal Finkel57f03dd2014-09-07 13:49:57 +0000692 const TargetTransformInfo &TTI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000693 AssumptionCache *AC) {
Hal Finkel57f03dd2014-09-07 13:49:57 +0000694 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000695 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000696
Dan Gohman969e83a2009-10-31 14:54:17 +0000697 CodeMetrics Metrics;
Dan Gohman90071072008-06-22 20:18:58 +0000698 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
Dan Gohman969e83a2009-10-31 14:54:17 +0000699 I != E; ++I)
Hal Finkel57f03dd2014-09-07 13:49:57 +0000700 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
Owen Anderson04cf3fd2010-09-09 20:32:23 +0000701 NumCalls = Metrics.NumInlineCandidates;
James Molloy4f6fb952012-12-20 16:04:27 +0000702 NotDuplicatable = Metrics.notDuplicatable;
Andrew Trick279e7a62011-07-23 00:29:16 +0000703
Owen Anderson62ea1b72010-09-09 19:07:31 +0000704 unsigned LoopSize = Metrics.NumInsts;
Andrew Trick279e7a62011-07-23 00:29:16 +0000705
Owen Anderson62ea1b72010-09-09 19:07:31 +0000706 // Don't allow an estimate of size zero. This would allows unrolling of loops
707 // with huge iteration counts, which is a compile time problem even if it's
Hal Finkel38dd5902015-01-10 00:30:55 +0000708 // not a problem for code quality. Also, the code using this size may assume
709 // that each loop has at least three instructions (likely a conditional
710 // branch, a comparison feeding that branch, and some kind of loop increment
711 // feeding that comparison instruction).
712 LoopSize = std::max(LoopSize, 3u);
Andrew Trick279e7a62011-07-23 00:29:16 +0000713
Owen Anderson62ea1b72010-09-09 19:07:31 +0000714 return LoopSize;
Chris Lattner946b2552004-04-18 05:20:17 +0000715}
716
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000717// Returns the loop hint metadata node with the given name (for example,
718// "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
719// returned.
Jingyue Wu49a766e2015-02-02 20:41:11 +0000720static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
721 if (MDNode *LoopID = L->getLoopID())
722 return GetUnrollMetadata(LoopID, Name);
723 return nullptr;
Eli Benderskyff903242014-06-16 23:53:02 +0000724}
725
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000726// Returns true if the loop has an unroll(full) pragma.
727static bool HasUnrollFullPragma(const Loop *L) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000728 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
Eli Benderskyff903242014-06-16 23:53:02 +0000729}
730
Mark Heffernan89391542015-08-10 17:28:08 +0000731// Returns true if the loop has an unroll(enable) pragma. This metadata is used
732// for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives.
733static bool HasUnrollEnablePragma(const Loop *L) {
734 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.enable");
735}
736
Eli Benderskyff903242014-06-16 23:53:02 +0000737// Returns true if the loop has an unroll(disable) pragma.
738static bool HasUnrollDisablePragma(const Loop *L) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000739 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
Eli Benderskyff903242014-06-16 23:53:02 +0000740}
741
Kevin Qin715b01e2015-03-09 06:14:18 +0000742// Returns true if the loop has an runtime unroll(disable) pragma.
743static bool HasRuntimeUnrollDisablePragma(const Loop *L) {
744 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
745}
746
Eli Benderskyff903242014-06-16 23:53:02 +0000747// If loop has an unroll_count pragma return the (necessarily
748// positive) value from the pragma. Otherwise return 0.
749static unsigned UnrollCountPragmaValue(const Loop *L) {
Jingyue Wu49a766e2015-02-02 20:41:11 +0000750 MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000751 if (MD) {
752 assert(MD->getNumOperands() == 2 &&
753 "Unroll count hint metadata should have two operands.");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000754 unsigned Count =
755 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
Eli Benderskyff903242014-06-16 23:53:02 +0000756 assert(Count >= 1 && "Unroll count must be positive.");
757 return Count;
758 }
759 return 0;
760}
761
Mark Heffernan053a6862014-07-18 21:04:33 +0000762// Remove existing unroll metadata and add unroll disable metadata to
763// indicate the loop has already been unrolled. This prevents a loop
764// from being unrolled more than is directed by a pragma if the loop
765// unrolling pass is run more than once (which it generally is).
766static void SetLoopAlreadyUnrolled(Loop *L) {
767 MDNode *LoopID = L->getLoopID();
768 if (!LoopID) return;
769
770 // First remove any existing loop unrolling metadata.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000771 SmallVector<Metadata *, 4> MDs;
Mark Heffernan053a6862014-07-18 21:04:33 +0000772 // Reserve first location for self reference to the LoopID metadata node.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000773 MDs.push_back(nullptr);
Mark Heffernan053a6862014-07-18 21:04:33 +0000774 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
775 bool IsUnrollMetadata = false;
776 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
777 if (MD) {
778 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
779 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
780 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000781 if (!IsUnrollMetadata)
782 MDs.push_back(LoopID->getOperand(i));
Mark Heffernan053a6862014-07-18 21:04:33 +0000783 }
784
785 // Add unroll(disable) metadata to disable future unrolling.
786 LLVMContext &Context = L->getHeader()->getContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000787 SmallVector<Metadata *, 1> DisableOperands;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000788 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
Mark Heffernanf3764da2014-07-18 21:29:41 +0000789 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000790 MDs.push_back(DisableNode);
Mark Heffernan053a6862014-07-18 21:04:33 +0000791
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000792 MDNode *NewLoopID = MDNode::get(Context, MDs);
Mark Heffernan053a6862014-07-18 21:04:33 +0000793 // Set operand 0 to refer to the loop id itself.
794 NewLoopID->replaceOperandWith(0, NewLoopID);
795 L->setLoopID(NewLoopID);
Mark Heffernan053a6862014-07-18 21:04:33 +0000796}
797
Chandler Carruth9dabd142015-06-05 17:01:43 +0000798bool LoopUnroll::canUnrollCompletely(Loop *L, unsigned Threshold,
799 unsigned PercentDynamicCostSavedThreshold,
800 unsigned DynamicCostSavingsDiscount,
Sanjoy Dasad714b12015-06-06 05:24:10 +0000801 uint64_t UnrolledCost,
802 uint64_t RolledDynamicCost) {
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000803
804 if (Threshold == NoThreshold) {
805 DEBUG(dbgs() << " Can fully unroll, because no threshold is set.\n");
806 return true;
807 }
808
Chandler Carruth9dabd142015-06-05 17:01:43 +0000809 if (UnrolledCost <= Threshold) {
810 DEBUG(dbgs() << " Can fully unroll, because unrolled cost: "
811 << UnrolledCost << "<" << Threshold << "\n");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000812 return true;
813 }
814
Chandler Carruth9dabd142015-06-05 17:01:43 +0000815 assert(UnrolledCost && "UnrolledCost can't be 0 at this point.");
816 assert(RolledDynamicCost >= UnrolledCost &&
817 "Cannot have a higher unrolled cost than a rolled cost!");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000818
Chandler Carruth9dabd142015-06-05 17:01:43 +0000819 // Compute the percentage of the dynamic cost in the rolled form that is
820 // saved when unrolled. If unrolling dramatically reduces the estimated
821 // dynamic cost of the loop, we use a higher threshold to allow more
822 // unrolling.
823 unsigned PercentDynamicCostSaved =
824 (uint64_t)(RolledDynamicCost - UnrolledCost) * 100ull / RolledDynamicCost;
825
826 if (PercentDynamicCostSaved >= PercentDynamicCostSavedThreshold &&
827 (int64_t)UnrolledCost - (int64_t)DynamicCostSavingsDiscount <=
828 (int64_t)Threshold) {
829 DEBUG(dbgs() << " Can fully unroll, because unrolling will reduce the "
830 "expected dynamic cost by " << PercentDynamicCostSaved
831 << "% (threshold: " << PercentDynamicCostSavedThreshold
832 << "%)\n"
833 << " and the unrolled cost (" << UnrolledCost
834 << ") is less than the max threshold ("
835 << DynamicCostSavingsDiscount << ").\n");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000836 return true;
837 }
838
839 DEBUG(dbgs() << " Too large to fully unroll:\n");
Chandler Carruth9dabd142015-06-05 17:01:43 +0000840 DEBUG(dbgs() << " Threshold: " << Threshold << "\n");
841 DEBUG(dbgs() << " Max threshold: " << DynamicCostSavingsDiscount << "\n");
842 DEBUG(dbgs() << " Percent cost saved threshold: "
843 << PercentDynamicCostSavedThreshold << "%\n");
844 DEBUG(dbgs() << " Unrolled cost: " << UnrolledCost << "\n");
845 DEBUG(dbgs() << " Rolled dynamic cost: " << RolledDynamicCost << "\n");
846 DEBUG(dbgs() << " Percent cost saved: " << PercentDynamicCostSaved
847 << "\n");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000848 return false;
849}
850
Eli Benderskyff903242014-06-16 23:53:02 +0000851unsigned LoopUnroll::selectUnrollCount(
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000852 const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
Eli Benderskyff903242014-06-16 23:53:02 +0000853 unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
854 bool &SetExplicitly) {
855 SetExplicitly = true;
856
857 // User-specified count (either as a command-line option or
858 // constructor parameter) has highest precedence.
859 unsigned Count = UserCount ? CurrentCount : 0;
860
861 // If there is no user-specified count, unroll pragmas have the next
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000862 // highest precedence.
Eli Benderskyff903242014-06-16 23:53:02 +0000863 if (Count == 0) {
864 if (PragmaCount) {
865 Count = PragmaCount;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000866 } else if (PragmaFullUnroll) {
Eli Benderskyff903242014-06-16 23:53:02 +0000867 Count = TripCount;
868 }
869 }
870
871 if (Count == 0)
872 Count = UP.Count;
873
874 if (Count == 0) {
875 SetExplicitly = false;
876 if (TripCount == 0)
877 // Runtime trip count.
878 Count = UnrollRuntimeCount;
879 else
880 // Conservative heuristic: if we know the trip count, see if we can
881 // completely unroll (subject to the threshold, checked below); otherwise
882 // try to find greatest modulo of the trip count which is still under
883 // threshold value.
884 Count = TripCount;
885 }
886 if (TripCount && Count > TripCount)
887 return TripCount;
888 return Count;
889}
890
Devang Patel9779e562007-03-07 01:38:05 +0000891bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000892 if (skipOptnoneFunction(L))
893 return false;
894
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000895 Function &F = *L->getHeader()->getParent();
896
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000897 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000898 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000899 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Chandler Carruth705b1852015-01-31 03:43:40 +0000900 const TargetTransformInfo &TTI =
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000901 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000902 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Dan Gohman2980d9d2007-05-11 20:53:41 +0000903
Dan Gohman2e1f8042007-05-08 15:19:19 +0000904 BasicBlock *Header = L->getHeader();
David Greenee0b97892010-01-05 01:27:44 +0000905 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000906 << "] Loop %" << Header->getName() << "\n");
Eli Benderskyff903242014-06-16 23:53:02 +0000907
908 if (HasUnrollDisablePragma(L)) {
909 return false;
910 }
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000911 bool PragmaFullUnroll = HasUnrollFullPragma(L);
Mark Heffernan89391542015-08-10 17:28:08 +0000912 bool PragmaEnableUnroll = HasUnrollEnablePragma(L);
Eli Benderskyff903242014-06-16 23:53:02 +0000913 unsigned PragmaCount = UnrollCountPragmaValue(L);
Mark Heffernan89391542015-08-10 17:28:08 +0000914 bool HasPragma = PragmaFullUnroll || PragmaEnableUnroll || PragmaCount > 0;
Andrew Trick279e7a62011-07-23 00:29:16 +0000915
Hal Finkel8f2e7002013-09-11 19:25:43 +0000916 TargetTransformInfo::UnrollingPreferences UP;
Chandler Carruth21fc1952015-02-01 14:37:03 +0000917 getUnrollingPreferences(L, TTI, UP);
Dan Gohman2980d9d2007-05-11 20:53:41 +0000918
Andrew Trick2b6860f2011-08-11 23:36:16 +0000919 // Find trip count and trip multiple if count is not available
920 unsigned TripCount = 0;
Andrew Trick1cabe542011-07-23 00:33:05 +0000921 unsigned TripMultiple = 1;
Chandler Carruth6666c272014-10-11 00:12:11 +0000922 // If there are multiple exiting blocks but one of them is the latch, use the
923 // latch for the trip count estimation. Otherwise insist on a single exiting
924 // block for the trip count estimation.
925 BasicBlock *ExitingBlock = L->getLoopLatch();
926 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
927 ExitingBlock = L->getExitingBlock();
928 if (ExitingBlock) {
929 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
930 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +0000931 }
Hal Finkel8f2e7002013-09-11 19:25:43 +0000932
Eli Benderskyff903242014-06-16 23:53:02 +0000933 // Select an initial unroll count. This may be reduced later based
934 // on size thresholds.
935 bool CountSetExplicitly;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000936 unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
937 PragmaCount, UP, CountSetExplicitly);
Eli Benderskydc6de2c2014-06-12 18:05:39 +0000938
Eli Benderskyff903242014-06-16 23:53:02 +0000939 unsigned NumInlineCandidates;
940 bool notDuplicatable;
941 unsigned LoopSize =
Chandler Carruth66b31302015-01-04 12:03:27 +0000942 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC);
Eli Benderskyff903242014-06-16 23:53:02 +0000943 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
Hal Finkel38dd5902015-01-10 00:30:55 +0000944
945 // When computing the unrolled size, note that the conditional branch on the
946 // backedge and the comparison feeding it are not replicated like the rest of
947 // the loop body (which is why 2 is subtracted).
948 uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2;
Eli Benderskyff903242014-06-16 23:53:02 +0000949 if (notDuplicatable) {
950 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
951 << " instructions.\n");
952 return false;
953 }
954 if (NumInlineCandidates != 0) {
955 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
956 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000957 }
958
Eli Benderskyff903242014-06-16 23:53:02 +0000959 unsigned Threshold, PartialThreshold;
Chandler Carruth9dabd142015-06-05 17:01:43 +0000960 unsigned PercentDynamicCostSavedThreshold;
961 unsigned DynamicCostSavingsDiscount;
Mark Heffernan89391542015-08-10 17:28:08 +0000962 // Only use the high pragma threshold when we have a target unroll factor such
963 // as with "#pragma unroll N" or a pragma indicating full unrolling and the
964 // trip count is known. Otherwise we rely on the standard threshold to
965 // heuristically select a reasonable unroll count.
966 bool UsePragmaThreshold =
967 PragmaCount > 0 ||
968 ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount != 0);
969
970 selectThresholds(L, UsePragmaThreshold, UP, Threshold, PartialThreshold,
Chandler Carruth9dabd142015-06-05 17:01:43 +0000971 PercentDynamicCostSavedThreshold,
972 DynamicCostSavingsDiscount);
Benjamin Kramer9130cb82014-05-04 19:12:38 +0000973
Eli Benderskyff903242014-06-16 23:53:02 +0000974 // Given Count, TripCount and thresholds determine the type of
975 // unrolling which is to be performed.
976 enum { Full = 0, Partial = 1, Runtime = 2 };
977 int Unrolling;
978 if (TripCount && Count == TripCount) {
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000979 Unrolling = Partial;
980 // If the loop is really small, we don't need to run an expensive analysis.
Chandler Carruth9dabd142015-06-05 17:01:43 +0000981 if (canUnrollCompletely(L, Threshold, 100, DynamicCostSavingsDiscount,
982 UnrolledSize, UnrolledSize)) {
Eli Benderskyff903242014-06-16 23:53:02 +0000983 Unrolling = Full;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000984 } else {
985 // The loop isn't that small, but we still can fully unroll it if that
986 // helps to remove a significant number of instructions.
987 // To check that, run additional analysis on the loop.
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000988 if (Optional<EstimatedUnrollCost> Cost =
989 analyzeLoopUnrollCost(L, TripCount, DT, *SE, TTI,
990 Threshold + DynamicCostSavingsDiscount))
Chandler Carruth9dabd142015-06-05 17:01:43 +0000991 if (canUnrollCompletely(L, Threshold, PercentDynamicCostSavedThreshold,
992 DynamicCostSavingsDiscount, Cost->UnrolledCost,
993 Cost->RolledDynamicCost)) {
Chandler Carruth02156082015-05-22 17:41:35 +0000994 Unrolling = Full;
995 }
Dan Gohman2980d9d2007-05-11 20:53:41 +0000996 }
Eli Benderskyff903242014-06-16 23:53:02 +0000997 } else if (TripCount && Count < TripCount) {
998 Unrolling = Partial;
999 } else {
1000 Unrolling = Runtime;
1001 }
1002
1003 // Reduce count based on the type of unrolling and the threshold values.
1004 unsigned OriginalCount = Count;
Mark Heffernan89391542015-08-10 17:28:08 +00001005 bool AllowRuntime = PragmaEnableUnroll || (PragmaCount > 0) ||
1006 (UserRuntime ? CurrentRuntime : UP.Runtime);
Mark Heffernand7ebc242015-07-13 18:26:27 +00001007 // Don't unroll a runtime trip count loop with unroll full pragma.
1008 if (HasRuntimeUnrollDisablePragma(L) || PragmaFullUnroll) {
Kevin Qin715b01e2015-03-09 06:14:18 +00001009 AllowRuntime = false;
1010 }
Eli Benderskyff903242014-06-16 23:53:02 +00001011 if (Unrolling == Partial) {
Mark Heffernan89391542015-08-10 17:28:08 +00001012 bool AllowPartial = PragmaEnableUnroll ||
1013 (UserAllowPartial ? CurrentAllowPartial : UP.Partial);
Eli Benderskyff903242014-06-16 23:53:02 +00001014 if (!AllowPartial && !CountSetExplicitly) {
1015 DEBUG(dbgs() << " will not try to unroll partially because "
1016 << "-unroll-allow-partial not given\n");
1017 return false;
1018 }
1019 if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
1020 // Reduce unroll count to be modulo of TripCount for partial unrolling.
Hal Finkel38dd5902015-01-10 00:30:55 +00001021 Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2);
Eli Benderskyff903242014-06-16 23:53:02 +00001022 while (Count != 0 && TripCount % Count != 0)
1023 Count--;
1024 }
1025 } else if (Unrolling == Runtime) {
1026 if (!AllowRuntime && !CountSetExplicitly) {
1027 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count "
1028 << "-unroll-runtime not given\n");
1029 return false;
1030 }
1031 // Reduce unroll count to be the largest power-of-two factor of
1032 // the original count which satisfies the threshold limit.
1033 while (Count != 0 && UnrolledSize > PartialThreshold) {
1034 Count >>= 1;
Hal Finkel38dd5902015-01-10 00:30:55 +00001035 UnrolledSize = (LoopSize-2) * Count + 2;
Eli Benderskyff903242014-06-16 23:53:02 +00001036 }
1037 if (Count > UP.MaxCount)
1038 Count = UP.MaxCount;
1039 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
1040 }
1041
1042 if (HasPragma) {
Mark Heffernan9e112442014-07-23 20:05:44 +00001043 if (PragmaCount != 0)
1044 // If loop has an unroll count pragma mark loop as unrolled to prevent
1045 // unrolling beyond that requested by the pragma.
1046 SetLoopAlreadyUnrolled(L);
Mark Heffernan053a6862014-07-18 21:04:33 +00001047
Eli Benderskyff903242014-06-16 23:53:02 +00001048 // Emit optimization remarks if we are unable to unroll the loop
1049 // as directed by a pragma.
1050 DebugLoc LoopLoc = L->getStartLoc();
1051 Function *F = Header->getParent();
1052 LLVMContext &Ctx = F->getContext();
Mark Heffernan89391542015-08-10 17:28:08 +00001053 if ((PragmaCount > 0) && Count != OriginalCount) {
Eli Benderskyff903242014-06-16 23:53:02 +00001054 emitOptimizationRemarkMissed(
1055 Ctx, DEBUG_TYPE, *F, LoopLoc,
1056 "Unable to unroll loop the number of times directed by "
1057 "unroll_count pragma because unrolled size is too large.");
Mark Heffernan89391542015-08-10 17:28:08 +00001058 } else if (PragmaFullUnroll && !TripCount) {
1059 emitOptimizationRemarkMissed(
1060 Ctx, DEBUG_TYPE, *F, LoopLoc,
1061 "Unable to fully unroll loop as directed by unroll(full) pragma "
1062 "because loop has a runtime trip count.");
1063 } else if (PragmaEnableUnroll && Count != TripCount && Count < 2) {
1064 emitOptimizationRemarkMissed(
1065 Ctx, DEBUG_TYPE, *F, LoopLoc,
1066 "Unable to unroll loop as directed by unroll(enable) pragma because "
1067 "unrolled size is too large.");
1068 } else if ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount &&
1069 Count != TripCount) {
1070 emitOptimizationRemarkMissed(
1071 Ctx, DEBUG_TYPE, *F, LoopLoc,
1072 "Unable to fully unroll loop as directed by unroll pragma because "
1073 "unrolled size is too large.");
Eli Benderskyff903242014-06-16 23:53:02 +00001074 }
1075 }
1076
1077 if (Unrolling != Full && Count < 2) {
1078 // Partial unrolling by 1 is a nop. For full unrolling, a factor
1079 // of 1 makes sense because loop control can be eliminated.
1080 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +00001081 }
1082
Dan Gohman3dc2d922008-05-14 00:24:14 +00001083 // Unroll the loop.
Sanjoy Dase178f462015-04-14 03:20:38 +00001084 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, UP.AllowExpensiveTripCount,
1085 TripMultiple, LI, this, &LPM, &AC))
Dan Gohman3dc2d922008-05-14 00:24:14 +00001086 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +00001087
Chris Lattner946b2552004-04-18 05:20:17 +00001088 return true;
1089}