blob: 4467112a18184231efe8472634af1c389d8b214e [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 Carruth66b31302015-01-04 12:03:27 +000016#include "llvm/Analysis/AssumptionCache.h"
Chris Lattner679572e2011-01-02 07:35:53 +000017#include "llvm/Analysis/CodeMetrics.h"
Eric Christopherd85ffb12014-09-18 00:34:14 +000018#include "llvm/Analysis/FunctionTargetTransformInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/LoopPass.h"
Dan Gohman0141c132010-07-26 18:11:16 +000020#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000021#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
Eli Benderskyff903242014-06-16 23:53:02 +000023#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000024#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/IntrinsicInst.h"
Eli Benderskyff903242014-06-16 23:53:02 +000026#include "llvm/IR/Metadata.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000027#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000029#include "llvm/Support/raw_ostream.h"
Dan Gohman3dc2d922008-05-14 00:24:14 +000030#include "llvm/Transforms/Utils/UnrollLoop.h"
Duncan Sands67933e62008-05-16 09:30:00 +000031#include <climits>
Chris Lattner946b2552004-04-18 05:20:17 +000032
Dan Gohman3dc2d922008-05-14 00:24:14 +000033using namespace llvm;
Chris Lattner946b2552004-04-18 05:20:17 +000034
Chandler Carruth964daaa2014-04-22 02:55:47 +000035#define DEBUG_TYPE "loop-unroll"
36
Dan Gohmand78c4002008-05-13 00:00:25 +000037static cl::opt<unsigned>
Owen Andersond85c9cc2010-09-10 17:57:00 +000038UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
Dan Gohmand78c4002008-05-13 00:00:25 +000039 cl::desc("The cut-off point for automatic loop unrolling"));
40
41static cl::opt<unsigned>
42UnrollCount("unroll-count", cl::init(0), cl::Hidden,
Eli Benderskyff903242014-06-16 23:53:02 +000043 cl::desc("Use this unroll count for all loops including those with "
44 "unroll_count pragma values, for testing purposes"));
Dan Gohmand78c4002008-05-13 00:00:25 +000045
Matthijs Kooijman98b5c162008-07-29 13:21:23 +000046static cl::opt<bool>
47UnrollAllowPartial("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
Andrew Trickd04d15292011-12-09 06:19:40 +000051static cl::opt<bool>
52UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
53 cl::desc("Unroll loops with run-time trip counts"));
54
Eli Benderskyff903242014-06-16 23:53:02 +000055static cl::opt<unsigned>
56PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
Mark Heffernane6b4ba12014-07-23 17:31:37 +000057 cl::desc("Unrolled size limit for loops with an unroll(full) or "
Eli Benderskyff903242014-06-16 23:53:02 +000058 "unroll_count pragma."));
59
Chris Lattner79a42ac2006-12-19 21:40:18 +000060namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +000061 class LoopUnroll : public LoopPass {
Chris Lattner946b2552004-04-18 05:20:17 +000062 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +000063 static char ID; // Pass ID, replacement for typeid
Hal Finkel081eaef2013-11-05 00:08:03 +000064 LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
Chris Lattner35a65b22011-04-14 02:27:25 +000065 CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
66 CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
Junjie Gu7c3b4592011-04-13 16:15:29 +000067 CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
Hal Finkel081eaef2013-11-05 00:08:03 +000068 CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
Junjie Gu7c3b4592011-04-13 16:15:29 +000069
70 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
Hal Finkel8f2e7002013-09-11 19:25:43 +000071 UserAllowPartial = (P != -1) ||
72 (UnrollAllowPartial.getNumOccurrences() > 0);
Hal Finkel081eaef2013-11-05 00:08:03 +000073 UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
Hal Finkel8f2e7002013-09-11 19:25:43 +000074 UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
Andrew Trick279e7a62011-07-23 00:29:16 +000075
Owen Anderson6c18d1a2010-10-19 17:21:58 +000076 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
77 }
Devang Patel09f162c2007-05-01 21:15:47 +000078
Dan Gohman2980d9d2007-05-11 20:53:41 +000079 /// 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;
Andrew Trick279e7a62011-07-23 00:29:16 +000083
Owen Andersona4d9c782010-09-07 23:15:30 +000084 // Threshold to use when optsize is specified (and there is no
85 // explicit -unroll-threshold).
86 static const unsigned OptSizeUnrollThreshold = 50;
Andrew Trick279e7a62011-07-23 00:29:16 +000087
Andrew Trickd04d15292011-12-09 06:19:40 +000088 // Default unroll count for loops with run-time trip count if
89 // -unroll-count is not set
90 static const unsigned UnrollRuntimeCount = 8;
91
Junjie Gu7c3b4592011-04-13 16:15:29 +000092 unsigned CurrentCount;
Owen Andersona4d9c782010-09-07 23:15:30 +000093 unsigned CurrentThreshold;
Junjie Gu7c3b4592011-04-13 16:15:29 +000094 bool CurrentAllowPartial;
Hal Finkel081eaef2013-11-05 00:08:03 +000095 bool CurrentRuntime;
Hal Finkel8f2e7002013-09-11 19:25:43 +000096 bool UserCount; // CurrentCount is user-specified.
Junjie Gu7c3b4592011-04-13 16:15:29 +000097 bool UserThreshold; // CurrentThreshold is user-specified.
Hal Finkel8f2e7002013-09-11 19:25:43 +000098 bool UserAllowPartial; // CurrentAllowPartial is user-specified.
Hal Finkel081eaef2013-11-05 00:08:03 +000099 bool UserRuntime; // CurrentRuntime is user-specified.
Dan Gohman2980d9d2007-05-11 20:53:41 +0000100
Craig Topper3e4c6972014-03-05 09:10:37 +0000101 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Chris Lattner946b2552004-04-18 05:20:17 +0000102
103 /// This transformation requires natural loop information & requires that
104 /// loop preheaders be inserted into the CFG...
105 ///
Craig Topper3e4c6972014-03-05 09:10:37 +0000106 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth66b31302015-01-04 12:03:27 +0000107 AU.addRequired<AssumptionCacheTracker>();
Chris Lattner946b2552004-04-18 05:20:17 +0000108 AU.addRequired<LoopInfo>();
Chris Lattnerf2cc8412004-04-18 05:38:37 +0000109 AU.addPreserved<LoopInfo>();
Dan Gohman0141c132010-07-26 18:11:16 +0000110 AU.addRequiredID(LoopSimplifyID);
111 AU.addPreservedID(LoopSimplifyID);
112 AU.addRequiredID(LCSSAID);
113 AU.addPreservedID(LCSSAID);
Andrew Trick4d0040b2011-08-10 04:29:49 +0000114 AU.addRequired<ScalarEvolution>();
Chris Lattnerd6f46b82010-08-29 17:21:35 +0000115 AU.addPreserved<ScalarEvolution>();
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000116 AU.addRequired<TargetTransformInfo>();
Eric Christopherd85ffb12014-09-18 00:34:14 +0000117 AU.addRequired<FunctionTargetTransformInfo>();
Devang Patelf94b9822008-07-03 07:04:22 +0000118 // 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.
Chandler Carruth73523022014-01-13 13:07:17 +0000122 AU.addPreserved<DominatorTreeWrapperPass>();
Chris Lattner946b2552004-04-18 05:20:17 +0000123 }
Eli Benderskyff903242014-06-16 23:53:02 +0000124
125 // Fill in the UnrollingPreferences parameter with values from the
126 // TargetTransformationInfo.
Eric Christopherd85ffb12014-09-18 00:34:14 +0000127 void getUnrollingPreferences(Loop *L, const FunctionTargetTransformInfo &FTTI,
Eli Benderskyff903242014-06-16 23:53:02 +0000128 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;
Eric Christopherd85ffb12014-09-18 00:34:14 +0000137 FTTI.getUnrollingPreferences(L, UP);
Eli Benderskyff903242014-06-16 23:53:02 +0000138 }
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
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000145 selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
Eli Benderskyff903242014-06-16 23:53:02 +0000146 unsigned PragmaCount,
147 const TargetTransformInfo::UnrollingPreferences &UP,
148 bool &SetExplicitly);
149
Eli Benderskyff903242014-06-16 23:53:02 +0000150 // 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 }
Chris Lattner946b2552004-04-18 05:20:17 +0000183 };
Chris Lattner946b2552004-04-18 05:20:17 +0000184}
185
Dan Gohmand78c4002008-05-13 00:00:25 +0000186char LoopUnroll::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000187INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000188INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
Chandler Carruth66b31302015-01-04 12:03:27 +0000189INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Eric Christopherd85ffb12014-09-18 00:34:14 +0000190INITIALIZE_PASS_DEPENDENCY(FunctionTargetTransformInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000191INITIALIZE_PASS_DEPENDENCY(LoopInfo)
192INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
193INITIALIZE_PASS_DEPENDENCY(LCSSA)
Devang Patel88b4fa22011-10-19 23:56:07 +0000194INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000195INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000196
Hal Finkel081eaef2013-11-05 00:08:03 +0000197Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
198 int Runtime) {
199 return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
Junjie Gu7c3b4592011-04-13 16:15:29 +0000200}
Chris Lattner946b2552004-04-18 05:20:17 +0000201
Hal Finkel86b30642014-03-31 23:23:51 +0000202Pass *llvm::createSimpleLoopUnrollPass() {
203 return llvm::createLoopUnrollPass(-1, -1, 0, 0);
204}
205
Dan Gohman49d08a52007-05-08 15:14:19 +0000206/// ApproximateLoopSize - Approximate the size of the loop.
Andrew Trickf7656012011-10-01 01:39:05 +0000207static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000208 bool &NotDuplicatable,
Hal Finkel57f03dd2014-09-07 13:49:57 +0000209 const TargetTransformInfo &TTI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000210 AssumptionCache *AC) {
Hal Finkel57f03dd2014-09-07 13:49:57 +0000211 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000212 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000213
Dan Gohman969e83a2009-10-31 14:54:17 +0000214 CodeMetrics Metrics;
Dan Gohman90071072008-06-22 20:18:58 +0000215 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
Dan Gohman969e83a2009-10-31 14:54:17 +0000216 I != E; ++I)
Hal Finkel57f03dd2014-09-07 13:49:57 +0000217 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
Owen Anderson04cf3fd2010-09-09 20:32:23 +0000218 NumCalls = Metrics.NumInlineCandidates;
James Molloy4f6fb952012-12-20 16:04:27 +0000219 NotDuplicatable = Metrics.notDuplicatable;
Andrew Trick279e7a62011-07-23 00:29:16 +0000220
Owen Anderson62ea1b72010-09-09 19:07:31 +0000221 unsigned LoopSize = Metrics.NumInsts;
Andrew Trick279e7a62011-07-23 00:29:16 +0000222
Owen Anderson62ea1b72010-09-09 19:07:31 +0000223 // 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.
226 if (LoopSize == 0) LoopSize = 1;
Andrew Trick279e7a62011-07-23 00:29:16 +0000227
Owen Anderson62ea1b72010-09-09 19:07:31 +0000228 return LoopSize;
Chris Lattner946b2552004-04-18 05:20:17 +0000229}
230
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000231// Returns the loop hint metadata node with the given name (for example,
232// "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
233// returned.
Benjamin Kramer89854eb2014-09-03 21:04:12 +0000234static const MDNode *GetUnrollMetadata(const Loop *L, StringRef Name) {
Eli Benderskyff903242014-06-16 23:53:02 +0000235 MDNode *LoopID = L->getLoopID();
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000236 if (!LoopID)
237 return nullptr;
Eli Benderskyff903242014-06-16 23:53:02 +0000238
239 // First operand should refer to the loop id itself.
240 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
241 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
242
243 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
244 const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000245 if (!MD)
246 continue;
Eli Benderskyff903242014-06-16 23:53:02 +0000247
248 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000249 if (!S)
250 continue;
Eli Benderskyff903242014-06-16 23:53:02 +0000251
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000252 if (Name.equals(S->getString()))
253 return MD;
Eli Benderskyff903242014-06-16 23:53:02 +0000254 }
255 return nullptr;
256}
257
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000258// Returns true if the loop has an unroll(full) pragma.
259static bool HasUnrollFullPragma(const Loop *L) {
260 return GetUnrollMetadata(L, "llvm.loop.unroll.full");
Eli Benderskyff903242014-06-16 23:53:02 +0000261}
262
263// Returns true if the loop has an unroll(disable) pragma.
264static bool HasUnrollDisablePragma(const Loop *L) {
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000265 return GetUnrollMetadata(L, "llvm.loop.unroll.disable");
Eli Benderskyff903242014-06-16 23:53:02 +0000266}
267
268// If loop has an unroll_count pragma return the (necessarily
269// positive) value from the pragma. Otherwise return 0.
270static unsigned UnrollCountPragmaValue(const Loop *L) {
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000271 const MDNode *MD = GetUnrollMetadata(L, "llvm.loop.unroll.count");
272 if (MD) {
273 assert(MD->getNumOperands() == 2 &&
274 "Unroll count hint metadata should have two operands.");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000275 unsigned Count =
276 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
Eli Benderskyff903242014-06-16 23:53:02 +0000277 assert(Count >= 1 && "Unroll count must be positive.");
278 return Count;
279 }
280 return 0;
281}
282
Mark Heffernan053a6862014-07-18 21:04:33 +0000283// Remove existing unroll metadata and add unroll disable metadata to
284// indicate the loop has already been unrolled. This prevents a loop
285// from being unrolled more than is directed by a pragma if the loop
286// unrolling pass is run more than once (which it generally is).
287static void SetLoopAlreadyUnrolled(Loop *L) {
288 MDNode *LoopID = L->getLoopID();
289 if (!LoopID) return;
290
291 // First remove any existing loop unrolling metadata.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000292 SmallVector<Metadata *, 4> MDs;
Mark Heffernan053a6862014-07-18 21:04:33 +0000293 // Reserve first location for self reference to the LoopID metadata node.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000294 MDs.push_back(nullptr);
Mark Heffernan053a6862014-07-18 21:04:33 +0000295 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
296 bool IsUnrollMetadata = false;
297 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
298 if (MD) {
299 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
300 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
301 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000302 if (!IsUnrollMetadata)
303 MDs.push_back(LoopID->getOperand(i));
Mark Heffernan053a6862014-07-18 21:04:33 +0000304 }
305
306 // Add unroll(disable) metadata to disable future unrolling.
307 LLVMContext &Context = L->getHeader()->getContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000308 SmallVector<Metadata *, 1> DisableOperands;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000309 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
Mark Heffernanf3764da2014-07-18 21:29:41 +0000310 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000311 MDs.push_back(DisableNode);
Mark Heffernan053a6862014-07-18 21:04:33 +0000312
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000313 MDNode *NewLoopID = MDNode::get(Context, MDs);
Mark Heffernan053a6862014-07-18 21:04:33 +0000314 // Set operand 0 to refer to the loop id itself.
315 NewLoopID->replaceOperandWith(0, NewLoopID);
316 L->setLoopID(NewLoopID);
Mark Heffernan053a6862014-07-18 21:04:33 +0000317}
318
Eli Benderskyff903242014-06-16 23:53:02 +0000319unsigned LoopUnroll::selectUnrollCount(
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000320 const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
Eli Benderskyff903242014-06-16 23:53:02 +0000321 unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
322 bool &SetExplicitly) {
323 SetExplicitly = true;
324
325 // User-specified count (either as a command-line option or
326 // constructor parameter) has highest precedence.
327 unsigned Count = UserCount ? CurrentCount : 0;
328
329 // If there is no user-specified count, unroll pragmas have the next
330 // highest precendence.
331 if (Count == 0) {
332 if (PragmaCount) {
333 Count = PragmaCount;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000334 } else if (PragmaFullUnroll) {
Eli Benderskyff903242014-06-16 23:53:02 +0000335 Count = TripCount;
336 }
337 }
338
339 if (Count == 0)
340 Count = UP.Count;
341
342 if (Count == 0) {
343 SetExplicitly = false;
344 if (TripCount == 0)
345 // Runtime trip count.
346 Count = UnrollRuntimeCount;
347 else
348 // Conservative heuristic: if we know the trip count, see if we can
349 // completely unroll (subject to the threshold, checked below); otherwise
350 // try to find greatest modulo of the trip count which is still under
351 // threshold value.
352 Count = TripCount;
353 }
354 if (TripCount && Count > TripCount)
355 return TripCount;
356 return Count;
357}
358
Devang Patel9779e562007-03-07 01:38:05 +0000359bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000360 if (skipOptnoneFunction(L))
361 return false;
362
Dan Gohman3dc2d922008-05-14 00:24:14 +0000363 LoopInfo *LI = &getAnalysis<LoopInfo>();
Andrew Trick2b6860f2011-08-11 23:36:16 +0000364 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000365 const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>();
Eric Christopherd85ffb12014-09-18 00:34:14 +0000366 const FunctionTargetTransformInfo &FTTI =
367 getAnalysis<FunctionTargetTransformInfo>();
Chandler Carruth66b31302015-01-04 12:03:27 +0000368 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
369 *L->getHeader()->getParent());
Dan Gohman2980d9d2007-05-11 20:53:41 +0000370
Dan Gohman2e1f8042007-05-08 15:19:19 +0000371 BasicBlock *Header = L->getHeader();
David Greenee0b97892010-01-05 01:27:44 +0000372 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000373 << "] Loop %" << Header->getName() << "\n");
Eli Benderskyff903242014-06-16 23:53:02 +0000374
375 if (HasUnrollDisablePragma(L)) {
376 return false;
377 }
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000378 bool PragmaFullUnroll = HasUnrollFullPragma(L);
Eli Benderskyff903242014-06-16 23:53:02 +0000379 unsigned PragmaCount = UnrollCountPragmaValue(L);
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000380 bool HasPragma = PragmaFullUnroll || PragmaCount > 0;
Andrew Trick279e7a62011-07-23 00:29:16 +0000381
Hal Finkel8f2e7002013-09-11 19:25:43 +0000382 TargetTransformInfo::UnrollingPreferences UP;
Eric Christopherd85ffb12014-09-18 00:34:14 +0000383 getUnrollingPreferences(L, FTTI, UP);
Dan Gohman2980d9d2007-05-11 20:53:41 +0000384
Andrew Trick2b6860f2011-08-11 23:36:16 +0000385 // Find trip count and trip multiple if count is not available
386 unsigned TripCount = 0;
Andrew Trick1cabe542011-07-23 00:33:05 +0000387 unsigned TripMultiple = 1;
Chandler Carruth6666c272014-10-11 00:12:11 +0000388 // If there are multiple exiting blocks but one of them is the latch, use the
389 // latch for the trip count estimation. Otherwise insist on a single exiting
390 // block for the trip count estimation.
391 BasicBlock *ExitingBlock = L->getLoopLatch();
392 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
393 ExitingBlock = L->getExitingBlock();
394 if (ExitingBlock) {
395 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
396 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +0000397 }
Hal Finkel8f2e7002013-09-11 19:25:43 +0000398
Eli Benderskyff903242014-06-16 23:53:02 +0000399 // Select an initial unroll count. This may be reduced later based
400 // on size thresholds.
401 bool CountSetExplicitly;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000402 unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
403 PragmaCount, UP, CountSetExplicitly);
Eli Benderskydc6de2c2014-06-12 18:05:39 +0000404
Eli Benderskyff903242014-06-16 23:53:02 +0000405 unsigned NumInlineCandidates;
406 bool notDuplicatable;
407 unsigned LoopSize =
Chandler Carruth66b31302015-01-04 12:03:27 +0000408 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC);
Eli Benderskyff903242014-06-16 23:53:02 +0000409 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
410 uint64_t UnrolledSize = (uint64_t)LoopSize * Count;
411 if (notDuplicatable) {
412 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
413 << " instructions.\n");
414 return false;
415 }
416 if (NumInlineCandidates != 0) {
417 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
418 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000419 }
420
Eli Benderskyff903242014-06-16 23:53:02 +0000421 unsigned Threshold, PartialThreshold;
422 selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold);
Benjamin Kramer9130cb82014-05-04 19:12:38 +0000423
Eli Benderskyff903242014-06-16 23:53:02 +0000424 // Given Count, TripCount and thresholds determine the type of
425 // unrolling which is to be performed.
426 enum { Full = 0, Partial = 1, Runtime = 2 };
427 int Unrolling;
428 if (TripCount && Count == TripCount) {
429 if (Threshold != NoThreshold && UnrolledSize > Threshold) {
430 DEBUG(dbgs() << " Too large to fully unroll with count: " << Count
431 << " because size: " << UnrolledSize << ">" << Threshold
432 << "\n");
433 Unrolling = Partial;
434 } else {
435 Unrolling = Full;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000436 }
Eli Benderskyff903242014-06-16 23:53:02 +0000437 } else if (TripCount && Count < TripCount) {
438 Unrolling = Partial;
439 } else {
440 Unrolling = Runtime;
441 }
442
443 // Reduce count based on the type of unrolling and the threshold values.
444 unsigned OriginalCount = Count;
445 bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime;
446 if (Unrolling == Partial) {
447 bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
448 if (!AllowPartial && !CountSetExplicitly) {
449 DEBUG(dbgs() << " will not try to unroll partially because "
450 << "-unroll-allow-partial not given\n");
451 return false;
452 }
453 if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
454 // Reduce unroll count to be modulo of TripCount for partial unrolling.
455 Count = PartialThreshold / LoopSize;
456 while (Count != 0 && TripCount % Count != 0)
457 Count--;
458 }
459 } else if (Unrolling == Runtime) {
460 if (!AllowRuntime && !CountSetExplicitly) {
461 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count "
462 << "-unroll-runtime not given\n");
463 return false;
464 }
465 // Reduce unroll count to be the largest power-of-two factor of
466 // the original count which satisfies the threshold limit.
467 while (Count != 0 && UnrolledSize > PartialThreshold) {
468 Count >>= 1;
469 UnrolledSize = LoopSize * Count;
470 }
471 if (Count > UP.MaxCount)
472 Count = UP.MaxCount;
473 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
474 }
475
476 if (HasPragma) {
Mark Heffernan9e112442014-07-23 20:05:44 +0000477 if (PragmaCount != 0)
478 // If loop has an unroll count pragma mark loop as unrolled to prevent
479 // unrolling beyond that requested by the pragma.
480 SetLoopAlreadyUnrolled(L);
Mark Heffernan053a6862014-07-18 21:04:33 +0000481
Eli Benderskyff903242014-06-16 23:53:02 +0000482 // Emit optimization remarks if we are unable to unroll the loop
483 // as directed by a pragma.
484 DebugLoc LoopLoc = L->getStartLoc();
485 Function *F = Header->getParent();
486 LLVMContext &Ctx = F->getContext();
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000487 if (PragmaFullUnroll && PragmaCount == 0) {
Eli Benderskyff903242014-06-16 23:53:02 +0000488 if (TripCount && Count != TripCount) {
489 emitOptimizationRemarkMissed(
490 Ctx, DEBUG_TYPE, *F, LoopLoc,
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000491 "Unable to fully unroll loop as directed by unroll(full) pragma "
Eli Benderskyff903242014-06-16 23:53:02 +0000492 "because unrolled size is too large.");
493 } else if (!TripCount) {
494 emitOptimizationRemarkMissed(
495 Ctx, DEBUG_TYPE, *F, LoopLoc,
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000496 "Unable to fully unroll loop as directed by unroll(full) pragma "
Eli Benderskyff903242014-06-16 23:53:02 +0000497 "because loop has a runtime trip count.");
498 }
499 } else if (PragmaCount > 0 && Count != OriginalCount) {
500 emitOptimizationRemarkMissed(
501 Ctx, DEBUG_TYPE, *F, LoopLoc,
502 "Unable to unroll loop the number of times directed by "
503 "unroll_count pragma because unrolled size is too large.");
504 }
505 }
506
507 if (Unrolling != Full && Count < 2) {
508 // Partial unrolling by 1 is a nop. For full unrolling, a factor
509 // of 1 makes sense because loop control can be eliminated.
510 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000511 }
512
Dan Gohman3dc2d922008-05-14 00:24:14 +0000513 // Unroll the loop.
Hal Finkel74c2f352014-09-07 12:44:26 +0000514 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, TripMultiple, LI, this,
Chandler Carruth66b31302015-01-04 12:03:27 +0000515 &LPM, &AC))
Dan Gohman3dc2d922008-05-14 00:24:14 +0000516 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000517
Chris Lattner946b2552004-04-18 05:20:17 +0000518 return true;
519}