blob: caa7af4f46f607c1780d880401c9394ab22ca8a4 [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
Chandler Carruth3b057b32015-02-13 03:57:40 +000015#include "llvm/ADT/SetVector.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"
Dehao Chend55bc4c2016-05-05 00:54:54 +000018#include "llvm/Analysis/GlobalsModRef.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000019#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/Analysis/LoopPass.h"
Michael Zolotukhin1da4afd2016-02-08 23:03:59 +000021#include "llvm/Analysis/LoopUnrollAnalyzer.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"
Dehao Chend55bc4c2016-05-05 00:54:54 +000034#include "llvm/Transforms/Scalar.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000035#include "llvm/Transforms/Utils/LoopUtils.h"
Dan Gohman3dc2d922008-05-14 00:24:14 +000036#include "llvm/Transforms/Utils/UnrollLoop.h"
Duncan Sands67933e62008-05-16 09:30:00 +000037#include <climits>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000038#include <utility>
Chris Lattner946b2552004-04-18 05:20:17 +000039
Dan Gohman3dc2d922008-05-14 00:24:14 +000040using namespace llvm;
Chris Lattner946b2552004-04-18 05:20:17 +000041
Chandler Carruth964daaa2014-04-22 02:55:47 +000042#define DEBUG_TYPE "loop-unroll"
43
Dan Gohmand78c4002008-05-13 00:00:25 +000044static cl::opt<unsigned>
Justin Bognera1dd4932016-01-12 00:55:26 +000045 UnrollThreshold("unroll-threshold", cl::Hidden,
Chandler Carruth9dabd142015-06-05 17:01:43 +000046 cl::desc("The baseline cost threshold for loop unrolling"));
47
48static cl::opt<unsigned> UnrollPercentDynamicCostSavedThreshold(
Michael Zolotukhin8f7a2422016-05-24 23:00:05 +000049 "unroll-percent-dynamic-cost-saved-threshold", cl::init(50), cl::Hidden,
Chandler Carruth9dabd142015-06-05 17:01:43 +000050 cl::desc("The percentage of estimated dynamic cost which must be saved by "
51 "unrolling to allow unrolling up to the max threshold."));
52
53static cl::opt<unsigned> UnrollDynamicCostSavingsDiscount(
Michael Zolotukhin8f7a2422016-05-24 23:00:05 +000054 "unroll-dynamic-cost-savings-discount", cl::init(100), cl::Hidden,
Chandler Carruth9dabd142015-06-05 17:01:43 +000055 cl::desc("This is the amount discounted from the total unroll cost when "
56 "the unrolled form has a high dynamic cost savings (triggered by "
57 "the '-unroll-perecent-dynamic-cost-saved-threshold' flag)."));
Dan Gohmand78c4002008-05-13 00:00:25 +000058
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000059static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
Michael Zolotukhin8f7a2422016-05-24 23:00:05 +000060 "unroll-max-iteration-count-to-analyze", cl::init(10), cl::Hidden,
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000061 cl::desc("Don't allow loop unrolling to simulate more than this number of"
62 "iterations when checking full unroll profitability"));
63
Dehao Chend55bc4c2016-05-05 00:54:54 +000064static cl::opt<unsigned> UnrollCount(
65 "unroll-count", cl::Hidden,
66 cl::desc("Use this unroll count for all loops including those with "
67 "unroll_count pragma values, for testing purposes"));
Dan Gohmand78c4002008-05-13 00:00:25 +000068
Dehao Chend55bc4c2016-05-05 00:54:54 +000069static cl::opt<unsigned> UnrollMaxCount(
70 "unroll-max-count", cl::Hidden,
71 cl::desc("Set the max unroll count for partial and runtime unrolling, for"
72 "testing purposes"));
Fiona Glaser045afc42016-04-06 16:57:25 +000073
Dehao Chend55bc4c2016-05-05 00:54:54 +000074static cl::opt<unsigned> UnrollFullMaxCount(
75 "unroll-full-max-count", cl::Hidden,
76 cl::desc(
77 "Set the max unroll count for full unrolling, for testing purposes"));
Fiona Glaser045afc42016-04-06 16:57:25 +000078
Matthijs Kooijman98b5c162008-07-29 13:21:23 +000079static cl::opt<bool>
Dehao Chend55bc4c2016-05-05 00:54:54 +000080 UnrollAllowPartial("unroll-allow-partial", cl::Hidden,
81 cl::desc("Allows loops to be partially unrolled until "
82 "-unroll-threshold loop size is reached."));
Matthijs Kooijman98b5c162008-07-29 13:21:23 +000083
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +000084static cl::opt<bool> UnrollAllowRemainder(
85 "unroll-allow-remainder", cl::Hidden,
86 cl::desc("Allow generation of a loop remainder (extra iterations) "
87 "when unrolling a loop."));
88
Andrew Trickd04d15292011-12-09 06:19:40 +000089static cl::opt<bool>
Dehao Chend55bc4c2016-05-05 00:54:54 +000090 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::Hidden,
91 cl::desc("Unroll loops with run-time trip counts"));
Andrew Trickd04d15292011-12-09 06:19:40 +000092
Dehao Chend55bc4c2016-05-05 00:54:54 +000093static cl::opt<unsigned> PragmaUnrollThreshold(
94 "pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
95 cl::desc("Unrolled size limit for loops with an unroll(full) or "
96 "unroll_count pragma."));
Justin Bognera1dd4932016-01-12 00:55:26 +000097
98/// A magic value for use with the Threshold parameter to indicate
99/// that the loop unroll should be performed regardless of how much
100/// code expansion would result.
101static const unsigned NoThreshold = UINT_MAX;
102
103/// Default unroll count for loops with run-time trip count if
104/// -unroll-count is not set
105static const unsigned DefaultUnrollRuntimeCount = 8;
106
107/// Gather the various unrolling parameters based on the defaults, compiler
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000108/// flags, TTI overrides and user specified parameters.
Justin Bognera1dd4932016-01-12 00:55:26 +0000109static TargetTransformInfo::UnrollingPreferences gatherUnrollingPreferences(
110 Loop *L, const TargetTransformInfo &TTI, Optional<unsigned> UserThreshold,
111 Optional<unsigned> UserCount, Optional<bool> UserAllowPartial,
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000112 Optional<bool> UserRuntime) {
Justin Bognera1dd4932016-01-12 00:55:26 +0000113 TargetTransformInfo::UnrollingPreferences UP;
114
115 // Set up the defaults
116 UP.Threshold = 150;
117 UP.PercentDynamicCostSavedThreshold = 20;
118 UP.DynamicCostSavingsDiscount = 2000;
Hans Wennborg719b26b2016-05-10 21:45:55 +0000119 UP.OptSizeThreshold = 0;
Justin Bognera1dd4932016-01-12 00:55:26 +0000120 UP.PartialThreshold = UP.Threshold;
Hans Wennborg719b26b2016-05-10 21:45:55 +0000121 UP.PartialOptSizeThreshold = 0;
Justin Bognera1dd4932016-01-12 00:55:26 +0000122 UP.Count = 0;
123 UP.MaxCount = UINT_MAX;
Fiona Glaser045afc42016-04-06 16:57:25 +0000124 UP.FullUnrollMaxCount = UINT_MAX;
Justin Bognera1dd4932016-01-12 00:55:26 +0000125 UP.Partial = false;
126 UP.Runtime = false;
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000127 UP.AllowRemainder = true;
Justin Bognera1dd4932016-01-12 00:55:26 +0000128 UP.AllowExpensiveTripCount = false;
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000129 UP.Force = false;
Justin Bognera1dd4932016-01-12 00:55:26 +0000130
131 // Override with any target specific settings
132 TTI.getUnrollingPreferences(L, UP);
133
134 // Apply size attributes
135 if (L->getHeader()->getParent()->optForSize()) {
136 UP.Threshold = UP.OptSizeThreshold;
137 UP.PartialThreshold = UP.PartialOptSizeThreshold;
138 }
139
Justin Bognera1dd4932016-01-12 00:55:26 +0000140 // Apply any user values specified by cl::opt
141 if (UnrollThreshold.getNumOccurrences() > 0) {
142 UP.Threshold = UnrollThreshold;
143 UP.PartialThreshold = UnrollThreshold;
144 }
145 if (UnrollPercentDynamicCostSavedThreshold.getNumOccurrences() > 0)
146 UP.PercentDynamicCostSavedThreshold =
147 UnrollPercentDynamicCostSavedThreshold;
148 if (UnrollDynamicCostSavingsDiscount.getNumOccurrences() > 0)
149 UP.DynamicCostSavingsDiscount = UnrollDynamicCostSavingsDiscount;
Fiona Glaser045afc42016-04-06 16:57:25 +0000150 if (UnrollMaxCount.getNumOccurrences() > 0)
151 UP.MaxCount = UnrollMaxCount;
152 if (UnrollFullMaxCount.getNumOccurrences() > 0)
153 UP.FullUnrollMaxCount = UnrollFullMaxCount;
Justin Bognera1dd4932016-01-12 00:55:26 +0000154 if (UnrollAllowPartial.getNumOccurrences() > 0)
155 UP.Partial = UnrollAllowPartial;
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000156 if (UnrollAllowRemainder.getNumOccurrences() > 0)
157 UP.AllowRemainder = UnrollAllowRemainder;
Justin Bognera1dd4932016-01-12 00:55:26 +0000158 if (UnrollRuntime.getNumOccurrences() > 0)
159 UP.Runtime = UnrollRuntime;
160
161 // Apply user values provided by argument
162 if (UserThreshold.hasValue()) {
163 UP.Threshold = *UserThreshold;
164 UP.PartialThreshold = *UserThreshold;
165 }
166 if (UserCount.hasValue())
167 UP.Count = *UserCount;
168 if (UserAllowPartial.hasValue())
169 UP.Partial = *UserAllowPartial;
170 if (UserRuntime.hasValue())
171 UP.Runtime = *UserRuntime;
172
Justin Bognera1dd4932016-01-12 00:55:26 +0000173 return UP;
174}
175
Chris Lattner79a42ac2006-12-19 21:40:18 +0000176namespace {
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000177/// A struct to densely store the state of an instruction after unrolling at
178/// each iteration.
179///
180/// This is designed to work like a tuple of <Instruction *, int> for the
181/// purposes of hashing and lookup, but to be able to associate two boolean
182/// states with each key.
183struct UnrolledInstState {
184 Instruction *I;
185 int Iteration : 30;
186 unsigned IsFree : 1;
187 unsigned IsCounted : 1;
188};
189
190/// Hashing and equality testing for a set of the instruction states.
191struct UnrolledInstStateKeyInfo {
192 typedef DenseMapInfo<Instruction *> PtrInfo;
193 typedef DenseMapInfo<std::pair<Instruction *, int>> PairInfo;
194 static inline UnrolledInstState getEmptyKey() {
195 return {PtrInfo::getEmptyKey(), 0, 0, 0};
196 }
197 static inline UnrolledInstState getTombstoneKey() {
198 return {PtrInfo::getTombstoneKey(), 0, 0, 0};
199 }
200 static inline unsigned getHashValue(const UnrolledInstState &S) {
201 return PairInfo::getHashValue({S.I, S.Iteration});
202 }
203 static inline bool isEqual(const UnrolledInstState &LHS,
204 const UnrolledInstState &RHS) {
205 return PairInfo::isEqual({LHS.I, LHS.Iteration}, {RHS.I, RHS.Iteration});
206 }
207};
208}
209
210namespace {
Chandler Carruth02156082015-05-22 17:41:35 +0000211struct EstimatedUnrollCost {
Chandler Carruth9dabd142015-06-05 17:01:43 +0000212 /// \brief The estimated cost after unrolling.
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000213 int UnrolledCost;
Chandler Carruth302a1332015-02-13 02:10:56 +0000214
Chandler Carruth9dabd142015-06-05 17:01:43 +0000215 /// \brief The estimated dynamic cost of executing the instructions in the
216 /// rolled form.
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000217 int RolledDynamicCost;
Chandler Carruth02156082015-05-22 17:41:35 +0000218};
219}
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000220
Chandler Carruth02156082015-05-22 17:41:35 +0000221/// \brief Figure out if the loop is worth full unrolling.
222///
223/// Complete loop unrolling can make some loads constant, and we need to know
224/// if that would expose any further optimization opportunities. This routine
Michael Zolotukhinc4e4f332015-06-11 22:17:39 +0000225/// estimates this optimization. It computes cost of unrolled loop
226/// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By
227/// dynamic cost we mean that we won't count costs of blocks that are known not
228/// to be executed (i.e. if we have a branch in the loop and we know that at the
229/// given iteration its condition would be resolved to true, we won't add up the
230/// cost of the 'false'-block).
231/// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If
232/// the analysis failed (no benefits expected from the unrolling, or the loop is
233/// too big to analyze), the returned value is None.
Benjamin Kramerfcdb1c12015-08-20 09:57:22 +0000234static Optional<EstimatedUnrollCost>
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000235analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, DominatorTree &DT,
236 ScalarEvolution &SE, const TargetTransformInfo &TTI,
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000237 int MaxUnrolledLoopSize) {
Chandler Carruth02156082015-05-22 17:41:35 +0000238 // We want to be able to scale offsets by the trip count and add more offsets
239 // to them without checking for overflows, and we already don't want to
240 // analyze *massive* trip counts, so we force the max to be reasonably small.
241 assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) &&
242 "The unroll iterations max is too large!");
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000243
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000244 // Only analyze inner loops. We can't properly estimate cost of nested loops
245 // and we won't visit inner loops again anyway.
246 if (!L->empty())
247 return None;
248
Chandler Carruth02156082015-05-22 17:41:35 +0000249 // Don't simulate loops with a big or unknown tripcount
250 if (!UnrollMaxIterationsCountToAnalyze || !TripCount ||
251 TripCount > UnrollMaxIterationsCountToAnalyze)
252 return None;
Chandler Carrutha6ae8772015-05-12 23:32:56 +0000253
Chandler Carruth02156082015-05-22 17:41:35 +0000254 SmallSetVector<BasicBlock *, 16> BBWorklist;
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000255 SmallSetVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitWorklist;
Chandler Carruth02156082015-05-22 17:41:35 +0000256 DenseMap<Value *, Constant *> SimplifiedValues;
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000257 SmallVector<std::pair<Value *, Constant *>, 4> SimplifiedInputValues;
Chandler Carruth3b057b32015-02-13 03:57:40 +0000258
Chandler Carruth9dabd142015-06-05 17:01:43 +0000259 // The estimated cost of the unrolled form of the loop. We try to estimate
260 // this by simplifying as much as we can while computing the estimate.
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000261 int UnrolledCost = 0;
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000262
Chandler Carruth9dabd142015-06-05 17:01:43 +0000263 // We also track the estimated dynamic (that is, actually executed) cost in
264 // the rolled form. This helps identify cases when the savings from unrolling
265 // aren't just exposing dead control flows, but actual reduced dynamic
266 // instructions due to the simplifications which we expect to occur after
267 // unrolling.
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000268 int RolledDynamicCost = 0;
Chandler Carruth8c863752015-02-13 03:48:38 +0000269
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000270 // We track the simplification of each instruction in each iteration. We use
271 // this to recursively merge costs into the unrolled cost on-demand so that
272 // we don't count the cost of any dead code. This is essentially a map from
273 // <instruction, int> to <bool, bool>, but stored as a densely packed struct.
274 DenseSet<UnrolledInstState, UnrolledInstStateKeyInfo> InstCostMap;
275
276 // A small worklist used to accumulate cost of instructions from each
277 // observable and reached root in the loop.
278 SmallVector<Instruction *, 16> CostWorklist;
279
280 // PHI-used worklist used between iterations while accumulating cost.
281 SmallVector<Instruction *, 4> PHIUsedList;
282
283 // Helper function to accumulate cost for instructions in the loop.
284 auto AddCostRecursively = [&](Instruction &RootI, int Iteration) {
285 assert(Iteration >= 0 && "Cannot have a negative iteration!");
286 assert(CostWorklist.empty() && "Must start with an empty cost list");
287 assert(PHIUsedList.empty() && "Must start with an empty phi used list");
288 CostWorklist.push_back(&RootI);
289 for (;; --Iteration) {
290 do {
291 Instruction *I = CostWorklist.pop_back_val();
292
293 // InstCostMap only uses I and Iteration as a key, the other two values
294 // don't matter here.
295 auto CostIter = InstCostMap.find({I, Iteration, 0, 0});
296 if (CostIter == InstCostMap.end())
297 // If an input to a PHI node comes from a dead path through the loop
298 // we may have no cost data for it here. What that actually means is
299 // that it is free.
300 continue;
301 auto &Cost = *CostIter;
302 if (Cost.IsCounted)
303 // Already counted this instruction.
304 continue;
305
306 // Mark that we are counting the cost of this instruction now.
307 Cost.IsCounted = true;
308
309 // If this is a PHI node in the loop header, just add it to the PHI set.
310 if (auto *PhiI = dyn_cast<PHINode>(I))
311 if (PhiI->getParent() == L->getHeader()) {
312 assert(Cost.IsFree && "Loop PHIs shouldn't be evaluated as they "
313 "inherently simplify during unrolling.");
314 if (Iteration == 0)
315 continue;
316
317 // Push the incoming value from the backedge into the PHI used list
318 // if it is an in-loop instruction. We'll use this to populate the
319 // cost worklist for the next iteration (as we count backwards).
320 if (auto *OpI = dyn_cast<Instruction>(
321 PhiI->getIncomingValueForBlock(L->getLoopLatch())))
322 if (L->contains(OpI))
323 PHIUsedList.push_back(OpI);
324 continue;
325 }
326
327 // First accumulate the cost of this instruction.
328 if (!Cost.IsFree) {
329 UnrolledCost += TTI.getUserCost(I);
330 DEBUG(dbgs() << "Adding cost of instruction (iteration " << Iteration
331 << "): ");
332 DEBUG(I->dump());
333 }
334
335 // We must count the cost of every operand which is not free,
336 // recursively. If we reach a loop PHI node, simply add it to the set
337 // to be considered on the next iteration (backwards!).
338 for (Value *Op : I->operands()) {
339 // Check whether this operand is free due to being a constant or
340 // outside the loop.
341 auto *OpI = dyn_cast<Instruction>(Op);
342 if (!OpI || !L->contains(OpI))
343 continue;
344
345 // Otherwise accumulate its cost.
346 CostWorklist.push_back(OpI);
347 }
348 } while (!CostWorklist.empty());
349
350 if (PHIUsedList.empty())
351 // We've exhausted the search.
352 break;
353
354 assert(Iteration > 0 &&
355 "Cannot track PHI-used values past the first iteration!");
356 CostWorklist.append(PHIUsedList.begin(), PHIUsedList.end());
357 PHIUsedList.clear();
358 }
359 };
360
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000361 // Ensure that we don't violate the loop structure invariants relied on by
362 // this analysis.
363 assert(L->isLoopSimplifyForm() && "Must put loop into normal form first.");
364 assert(L->isLCSSAForm(DT) &&
365 "Must have loops in LCSSA form to track live-out values.");
366
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000367 DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n");
368
Chandler Carruth02156082015-05-22 17:41:35 +0000369 // Simulate execution of each iteration of the loop counting instructions,
370 // which would be simplified.
371 // Since the same load will take different values on different iterations,
372 // we literally have to go through all loop's iterations.
373 for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000374 DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n");
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000375
376 // Prepare for the iteration by collecting any simplified entry or backedge
377 // inputs.
378 for (Instruction &I : *L->getHeader()) {
379 auto *PHI = dyn_cast<PHINode>(&I);
380 if (!PHI)
381 break;
382
383 // The loop header PHI nodes must have exactly two input: one from the
384 // loop preheader and one from the loop latch.
385 assert(
386 PHI->getNumIncomingValues() == 2 &&
387 "Must have an incoming value only for the preheader and the latch.");
388
389 Value *V = PHI->getIncomingValueForBlock(
390 Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch());
391 Constant *C = dyn_cast<Constant>(V);
392 if (Iteration != 0 && !C)
393 C = SimplifiedValues.lookup(V);
394 if (C)
395 SimplifiedInputValues.push_back({PHI, C});
396 }
397
398 // Now clear and re-populate the map for the next iteration.
Chandler Carruth02156082015-05-22 17:41:35 +0000399 SimplifiedValues.clear();
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000400 while (!SimplifiedInputValues.empty())
401 SimplifiedValues.insert(SimplifiedInputValues.pop_back_val());
402
Michael Zolotukhin9f520eb2016-02-26 02:57:05 +0000403 UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SE, L);
Chandler Carruthf174a152015-05-22 02:47:29 +0000404
Chandler Carruth02156082015-05-22 17:41:35 +0000405 BBWorklist.clear();
406 BBWorklist.insert(L->getHeader());
407 // Note that we *must not* cache the size, this loop grows the worklist.
408 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
409 BasicBlock *BB = BBWorklist[Idx];
Chandler Carruthf174a152015-05-22 02:47:29 +0000410
Chandler Carruth02156082015-05-22 17:41:35 +0000411 // Visit all instructions in the given basic block and try to simplify
412 // it. We don't change the actual IR, just count optimization
413 // opportunities.
414 for (Instruction &I : *BB) {
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000415 // Track this instruction's expected baseline cost when executing the
416 // rolled loop form.
417 RolledDynamicCost += TTI.getUserCost(&I);
Chandler Carruth17a04962015-02-13 03:49:41 +0000418
Chandler Carruth02156082015-05-22 17:41:35 +0000419 // Visit the instruction to analyze its loop cost after unrolling,
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000420 // and if the visitor returns true, mark the instruction as free after
421 // unrolling and continue.
422 bool IsFree = Analyzer.visit(I);
423 bool Inserted = InstCostMap.insert({&I, (int)Iteration,
424 (unsigned)IsFree,
425 /*IsCounted*/ false}).second;
426 (void)Inserted;
427 assert(Inserted && "Cannot have a state for an unvisited instruction!");
Chandler Carruth9dabd142015-06-05 17:01:43 +0000428
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000429 if (IsFree)
430 continue;
431
432 // If the instruction might have a side-effect recursively account for
433 // the cost of it and all the instructions leading up to it.
434 if (I.mayHaveSideEffects())
435 AddCostRecursively(I, Iteration);
436
437 // Can't properly model a cost of a call.
438 // FIXME: With a proper cost model we should be able to do it.
439 if(isa<CallInst>(&I))
440 return None;
Chandler Carruth02156082015-05-22 17:41:35 +0000441
442 // If unrolled body turns out to be too big, bail out.
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000443 if (UnrolledCost > MaxUnrolledLoopSize) {
444 DEBUG(dbgs() << " Exceeded threshold.. exiting.\n"
445 << " UnrolledCost: " << UnrolledCost
446 << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize
447 << "\n");
Chandler Carruth02156082015-05-22 17:41:35 +0000448 return None;
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000449 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000450 }
Chandler Carruth415f4122015-02-13 02:17:39 +0000451
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000452 TerminatorInst *TI = BB->getTerminator();
453
454 // Add in the live successors by first checking whether we have terminator
455 // that may be simplified based on the values simplified by this call.
Michael Zolotukhin1ecdeda2016-05-26 21:42:51 +0000456 BasicBlock *KnownSucc = nullptr;
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000457 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
458 if (BI->isConditional()) {
459 if (Constant *SimpleCond =
460 SimplifiedValues.lookup(BI->getCondition())) {
Michael Zolotukhin3a7d55b2015-07-29 18:10:29 +0000461 // Just take the first successor if condition is undef
462 if (isa<UndefValue>(SimpleCond))
Michael Zolotukhin1ecdeda2016-05-26 21:42:51 +0000463 KnownSucc = BI->getSuccessor(0);
464 else if (ConstantInt *SimpleCondVal =
465 dyn_cast<ConstantInt>(SimpleCond))
466 KnownSucc = BI->getSuccessor(SimpleCondVal->isZero() ? 1 : 0);
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000467 }
468 }
469 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
470 if (Constant *SimpleCond =
471 SimplifiedValues.lookup(SI->getCondition())) {
Michael Zolotukhin3a7d55b2015-07-29 18:10:29 +0000472 // Just take the first successor if condition is undef
473 if (isa<UndefValue>(SimpleCond))
Michael Zolotukhin1ecdeda2016-05-26 21:42:51 +0000474 KnownSucc = SI->getSuccessor(0);
475 else if (ConstantInt *SimpleCondVal =
476 dyn_cast<ConstantInt>(SimpleCond))
477 KnownSucc = SI->findCaseValue(SimpleCondVal).getCaseSuccessor();
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000478 }
479 }
Michael Zolotukhin1ecdeda2016-05-26 21:42:51 +0000480 if (KnownSucc) {
481 if (L->contains(KnownSucc))
482 BBWorklist.insert(KnownSucc);
483 else
484 ExitWorklist.insert({BB, KnownSucc});
485 continue;
486 }
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000487
Chandler Carruth02156082015-05-22 17:41:35 +0000488 // Add BB's successors to the worklist.
489 for (BasicBlock *Succ : successors(BB))
490 if (L->contains(Succ))
491 BBWorklist.insert(Succ);
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000492 else
493 ExitWorklist.insert({BB, Succ});
Michael Zolotukhind2268a72016-05-18 21:20:12 +0000494 AddCostRecursively(*TI, Iteration);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000495 }
Chandler Carruth02156082015-05-22 17:41:35 +0000496
497 // If we found no optimization opportunities on the first iteration, we
498 // won't find them on later ones too.
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000499 if (UnrolledCost == RolledDynamicCost) {
500 DEBUG(dbgs() << " No opportunities found.. exiting.\n"
501 << " UnrolledCost: " << UnrolledCost << "\n");
Chandler Carruth02156082015-05-22 17:41:35 +0000502 return None;
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000503 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000504 }
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000505
506 while (!ExitWorklist.empty()) {
507 BasicBlock *ExitingBB, *ExitBB;
508 std::tie(ExitingBB, ExitBB) = ExitWorklist.pop_back_val();
509
510 for (Instruction &I : *ExitBB) {
511 auto *PN = dyn_cast<PHINode>(&I);
512 if (!PN)
513 break;
514
515 Value *Op = PN->getIncomingValueForBlock(ExitingBB);
516 if (auto *OpI = dyn_cast<Instruction>(Op))
517 if (L->contains(OpI))
518 AddCostRecursively(*OpI, TripCount - 1);
519 }
520 }
521
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000522 DEBUG(dbgs() << "Analysis finished:\n"
523 << "UnrolledCost: " << UnrolledCost << ", "
524 << "RolledDynamicCost: " << RolledDynamicCost << "\n");
Chandler Carruth9dabd142015-06-05 17:01:43 +0000525 return {{UnrolledCost, RolledDynamicCost}};
Chandler Carruth02156082015-05-22 17:41:35 +0000526}
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000527
Dan Gohman49d08a52007-05-08 15:14:19 +0000528/// ApproximateLoopSize - Approximate the size of the loop.
Andrew Trickf7656012011-10-01 01:39:05 +0000529static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
Justin Lebar6827de12016-03-14 23:15:34 +0000530 bool &NotDuplicatable, bool &Convergent,
Hal Finkel57f03dd2014-09-07 13:49:57 +0000531 const TargetTransformInfo &TTI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000532 AssumptionCache *AC) {
Hal Finkel57f03dd2014-09-07 13:49:57 +0000533 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000534 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000535
Dan Gohman969e83a2009-10-31 14:54:17 +0000536 CodeMetrics Metrics;
Sanjay Patel5c967232016-03-08 19:06:12 +0000537 for (BasicBlock *BB : L->blocks())
538 Metrics.analyzeBasicBlock(BB, TTI, EphValues);
Owen Anderson04cf3fd2010-09-09 20:32:23 +0000539 NumCalls = Metrics.NumInlineCandidates;
James Molloy4f6fb952012-12-20 16:04:27 +0000540 NotDuplicatable = Metrics.notDuplicatable;
Justin Lebar6827de12016-03-14 23:15:34 +0000541 Convergent = Metrics.convergent;
Andrew Trick279e7a62011-07-23 00:29:16 +0000542
Owen Anderson62ea1b72010-09-09 19:07:31 +0000543 unsigned LoopSize = Metrics.NumInsts;
Andrew Trick279e7a62011-07-23 00:29:16 +0000544
Owen Anderson62ea1b72010-09-09 19:07:31 +0000545 // Don't allow an estimate of size zero. This would allows unrolling of loops
546 // with huge iteration counts, which is a compile time problem even if it's
Hal Finkel38dd5902015-01-10 00:30:55 +0000547 // not a problem for code quality. Also, the code using this size may assume
548 // that each loop has at least three instructions (likely a conditional
549 // branch, a comparison feeding that branch, and some kind of loop increment
550 // feeding that comparison instruction).
551 LoopSize = std::max(LoopSize, 3u);
Andrew Trick279e7a62011-07-23 00:29:16 +0000552
Owen Anderson62ea1b72010-09-09 19:07:31 +0000553 return LoopSize;
Chris Lattner946b2552004-04-18 05:20:17 +0000554}
555
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000556// Returns the loop hint metadata node with the given name (for example,
557// "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
558// returned.
Jingyue Wu49a766e2015-02-02 20:41:11 +0000559static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
560 if (MDNode *LoopID = L->getLoopID())
561 return GetUnrollMetadata(LoopID, Name);
562 return nullptr;
Eli Benderskyff903242014-06-16 23:53:02 +0000563}
564
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000565// Returns true if the loop has an unroll(full) pragma.
566static bool HasUnrollFullPragma(const Loop *L) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000567 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
Eli Benderskyff903242014-06-16 23:53:02 +0000568}
569
Mark Heffernan89391542015-08-10 17:28:08 +0000570// Returns true if the loop has an unroll(enable) pragma. This metadata is used
571// for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives.
572static bool HasUnrollEnablePragma(const Loop *L) {
573 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.enable");
574}
575
Eli Benderskyff903242014-06-16 23:53:02 +0000576// Returns true if the loop has an unroll(disable) pragma.
577static bool HasUnrollDisablePragma(const Loop *L) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000578 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
Eli Benderskyff903242014-06-16 23:53:02 +0000579}
580
Kevin Qin715b01e2015-03-09 06:14:18 +0000581// Returns true if the loop has an runtime unroll(disable) pragma.
582static bool HasRuntimeUnrollDisablePragma(const Loop *L) {
583 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
584}
585
Eli Benderskyff903242014-06-16 23:53:02 +0000586// If loop has an unroll_count pragma return the (necessarily
587// positive) value from the pragma. Otherwise return 0.
588static unsigned UnrollCountPragmaValue(const Loop *L) {
Jingyue Wu49a766e2015-02-02 20:41:11 +0000589 MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000590 if (MD) {
591 assert(MD->getNumOperands() == 2 &&
592 "Unroll count hint metadata should have two operands.");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000593 unsigned Count =
594 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
Eli Benderskyff903242014-06-16 23:53:02 +0000595 assert(Count >= 1 && "Unroll count must be positive.");
596 return Count;
597 }
598 return 0;
599}
600
Mark Heffernan053a6862014-07-18 21:04:33 +0000601// Remove existing unroll metadata and add unroll disable metadata to
602// indicate the loop has already been unrolled. This prevents a loop
603// from being unrolled more than is directed by a pragma if the loop
604// unrolling pass is run more than once (which it generally is).
605static void SetLoopAlreadyUnrolled(Loop *L) {
606 MDNode *LoopID = L->getLoopID();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000607 if (!LoopID)
608 return;
Mark Heffernan053a6862014-07-18 21:04:33 +0000609
610 // First remove any existing loop unrolling metadata.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000611 SmallVector<Metadata *, 4> MDs;
Mark Heffernan053a6862014-07-18 21:04:33 +0000612 // Reserve first location for self reference to the LoopID metadata node.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000613 MDs.push_back(nullptr);
Mark Heffernan053a6862014-07-18 21:04:33 +0000614 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
615 bool IsUnrollMetadata = false;
616 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
617 if (MD) {
618 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
619 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
620 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000621 if (!IsUnrollMetadata)
622 MDs.push_back(LoopID->getOperand(i));
Mark Heffernan053a6862014-07-18 21:04:33 +0000623 }
624
625 // Add unroll(disable) metadata to disable future unrolling.
626 LLVMContext &Context = L->getHeader()->getContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000627 SmallVector<Metadata *, 1> DisableOperands;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000628 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
Mark Heffernanf3764da2014-07-18 21:29:41 +0000629 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000630 MDs.push_back(DisableNode);
Mark Heffernan053a6862014-07-18 21:04:33 +0000631
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000632 MDNode *NewLoopID = MDNode::get(Context, MDs);
Mark Heffernan053a6862014-07-18 21:04:33 +0000633 // Set operand 0 to refer to the loop id itself.
634 NewLoopID->replaceOperandWith(0, NewLoopID);
635 L->setLoopID(NewLoopID);
Mark Heffernan053a6862014-07-18 21:04:33 +0000636}
637
Justin Bogner921b04e2016-01-12 01:06:32 +0000638static bool canUnrollCompletely(Loop *L, unsigned Threshold,
639 unsigned PercentDynamicCostSavedThreshold,
640 unsigned DynamicCostSavingsDiscount,
641 uint64_t UnrolledCost,
642 uint64_t RolledDynamicCost) {
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000643 if (Threshold == NoThreshold) {
644 DEBUG(dbgs() << " Can fully unroll, because no threshold is set.\n");
645 return true;
646 }
647
Chandler Carruth9dabd142015-06-05 17:01:43 +0000648 if (UnrolledCost <= Threshold) {
649 DEBUG(dbgs() << " Can fully unroll, because unrolled cost: "
650 << UnrolledCost << "<" << Threshold << "\n");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000651 return true;
652 }
653
Chandler Carruth9dabd142015-06-05 17:01:43 +0000654 assert(UnrolledCost && "UnrolledCost can't be 0 at this point.");
655 assert(RolledDynamicCost >= UnrolledCost &&
656 "Cannot have a higher unrolled cost than a rolled cost!");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000657
Chandler Carruth9dabd142015-06-05 17:01:43 +0000658 // Compute the percentage of the dynamic cost in the rolled form that is
659 // saved when unrolled. If unrolling dramatically reduces the estimated
660 // dynamic cost of the loop, we use a higher threshold to allow more
661 // unrolling.
662 unsigned PercentDynamicCostSaved =
663 (uint64_t)(RolledDynamicCost - UnrolledCost) * 100ull / RolledDynamicCost;
664
665 if (PercentDynamicCostSaved >= PercentDynamicCostSavedThreshold &&
666 (int64_t)UnrolledCost - (int64_t)DynamicCostSavingsDiscount <=
667 (int64_t)Threshold) {
668 DEBUG(dbgs() << " Can fully unroll, because unrolling will reduce the "
Dehao Chend55bc4c2016-05-05 00:54:54 +0000669 "expected dynamic cost by "
670 << PercentDynamicCostSaved << "% (threshold: "
671 << PercentDynamicCostSavedThreshold << "%)\n"
Chandler Carruth9dabd142015-06-05 17:01:43 +0000672 << " and the unrolled cost (" << UnrolledCost
673 << ") is less than the max threshold ("
674 << DynamicCostSavingsDiscount << ").\n");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000675 return true;
676 }
677
678 DEBUG(dbgs() << " Too large to fully unroll:\n");
Chandler Carruth9dabd142015-06-05 17:01:43 +0000679 DEBUG(dbgs() << " Threshold: " << Threshold << "\n");
680 DEBUG(dbgs() << " Max threshold: " << DynamicCostSavingsDiscount << "\n");
681 DEBUG(dbgs() << " Percent cost saved threshold: "
682 << PercentDynamicCostSavedThreshold << "%\n");
683 DEBUG(dbgs() << " Unrolled cost: " << UnrolledCost << "\n");
684 DEBUG(dbgs() << " Rolled dynamic cost: " << RolledDynamicCost << "\n");
685 DEBUG(dbgs() << " Percent cost saved: " << PercentDynamicCostSaved
686 << "\n");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000687 return false;
688}
689
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000690// Returns true if unroll count was set explicitly.
691// Calculates unroll count and writes it to UP.Count.
692static bool computeUnrollCount(Loop *L, const TargetTransformInfo &TTI,
693 DominatorTree &DT, LoopInfo *LI,
694 ScalarEvolution *SE, unsigned TripCount,
695 unsigned TripMultiple, unsigned LoopSize,
696 TargetTransformInfo::UnrollingPreferences &UP) {
697 // BEInsns represents number of instructions optimized when "back edge"
698 // becomes "fall through" in unrolled loop.
699 // For now we count a conditional branch on a backedge and a comparison
700 // feeding it.
701 unsigned BEInsns = 2;
702 // Check for explicit Count.
703 // 1st priority is unroll count set by "unroll-count" option.
704 bool UserUnrollCount = UnrollCount.getNumOccurrences() > 0;
705 if (UserUnrollCount) {
706 UP.Count = UnrollCount;
707 UP.AllowExpensiveTripCount = true;
708 UP.Force = true;
709 if (UP.AllowRemainder &&
710 (LoopSize - BEInsns) * UP.Count + BEInsns < UP.Threshold)
711 return true;
712 }
713
714 // 2nd priority is unroll count set by pragma.
715 unsigned PragmaCount = UnrollCountPragmaValue(L);
716 if (PragmaCount > 0) {
717 UP.Count = PragmaCount;
718 UP.Runtime = true;
719 UP.AllowExpensiveTripCount = true;
720 UP.Force = true;
721 if (UP.AllowRemainder &&
722 (LoopSize - BEInsns) * UP.Count + BEInsns < PragmaUnrollThreshold)
723 return true;
724 }
725 bool PragmaFullUnroll = HasUnrollFullPragma(L);
726 if (PragmaFullUnroll && TripCount != 0) {
727 UP.Count = TripCount;
728 if ((LoopSize - BEInsns) * UP.Count + BEInsns < PragmaUnrollThreshold)
729 return false;
730 }
731
732 bool PragmaEnableUnroll = HasUnrollEnablePragma(L);
733 bool ExplicitUnroll = PragmaCount > 0 || PragmaFullUnroll ||
734 PragmaEnableUnroll || UserUnrollCount;
735
736 uint64_t UnrolledSize;
737 DebugLoc LoopLoc = L->getStartLoc();
738 Function *F = L->getHeader()->getParent();
739 LLVMContext &Ctx = F->getContext();
740
741 if (ExplicitUnroll && TripCount != 0) {
742 // If the loop has an unrolling pragma, we want to be more aggressive with
743 // unrolling limits. Set thresholds to at least the PragmaThreshold value
744 // which is larger than the default limits.
745 UP.Threshold = std::max<unsigned>(UP.Threshold, PragmaUnrollThreshold);
746 UP.PartialThreshold =
747 std::max<unsigned>(UP.PartialThreshold, PragmaUnrollThreshold);
748 }
749
750 // 3rd priority is full unroll count.
751 // Full unroll make sense only when TripCount could be staticaly calculated.
752 // Also we need to check if we exceed FullUnrollMaxCount.
753 if (TripCount && TripCount <= UP.FullUnrollMaxCount) {
754 // When computing the unrolled size, note that BEInsns are not replicated
755 // like the rest of the loop body.
756 UnrolledSize = (uint64_t)(LoopSize - BEInsns) * TripCount + BEInsns;
757 if (canUnrollCompletely(L, UP.Threshold, 100, UP.DynamicCostSavingsDiscount,
758 UnrolledSize, UnrolledSize)) {
759 UP.Count = TripCount;
760 return ExplicitUnroll;
761 } else {
762 // The loop isn't that small, but we still can fully unroll it if that
763 // helps to remove a significant number of instructions.
764 // To check that, run additional analysis on the loop.
765 if (Optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost(
766 L, TripCount, DT, *SE, TTI,
767 UP.Threshold + UP.DynamicCostSavingsDiscount))
768 if (canUnrollCompletely(L, UP.Threshold,
769 UP.PercentDynamicCostSavedThreshold,
770 UP.DynamicCostSavingsDiscount,
771 Cost->UnrolledCost, Cost->RolledDynamicCost)) {
772 UP.Count = TripCount;
773 return ExplicitUnroll;
774 }
775 }
776 }
777
778 // 4rd priority is partial unrolling.
779 // Try partial unroll only when TripCount could be staticaly calculated.
780 if (TripCount) {
781 if (UP.Count == 0)
782 UP.Count = TripCount;
783 UP.Partial |= ExplicitUnroll;
784 if (!UP.Partial) {
785 DEBUG(dbgs() << " will not try to unroll partially because "
786 << "-unroll-allow-partial not given\n");
787 UP.Count = 0;
788 return false;
789 }
790 if (UP.PartialThreshold != NoThreshold) {
791 // Reduce unroll count to be modulo of TripCount for partial unrolling.
792 UnrolledSize = (uint64_t)(LoopSize - BEInsns) * UP.Count + BEInsns;
793 if (UnrolledSize > UP.PartialThreshold)
794 UP.Count = (std::max(UP.PartialThreshold, 3u) - BEInsns) /
795 (LoopSize - BEInsns);
796 if (UP.Count > UP.MaxCount)
797 UP.Count = UP.MaxCount;
798 while (UP.Count != 0 && TripCount % UP.Count != 0)
799 UP.Count--;
800 if (UP.AllowRemainder && UP.Count <= 1) {
801 // If there is no Count that is modulo of TripCount, set Count to
802 // largest power-of-two factor that satisfies the threshold limit.
803 // As we'll create fixup loop, do the type of unrolling only if
804 // remainder loop is allowed.
805 UP.Count = DefaultUnrollRuntimeCount;
806 UnrolledSize = (LoopSize - BEInsns) * UP.Count + BEInsns;
807 while (UP.Count != 0 && UnrolledSize > UP.PartialThreshold) {
808 UP.Count >>= 1;
809 UnrolledSize = (LoopSize - BEInsns) * UP.Count + BEInsns;
810 }
811 }
812 if (UP.Count < 2) {
813 if (PragmaEnableUnroll)
814 emitOptimizationRemarkMissed(
815 Ctx, DEBUG_TYPE, *F, LoopLoc,
816 "Unable to unroll loop as directed by unroll(enable) pragma "
817 "because unrolled size is too large.");
818 UP.Count = 0;
819 }
820 } else {
821 UP.Count = TripCount;
822 }
823 if ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount &&
824 UP.Count != TripCount)
825 emitOptimizationRemarkMissed(
826 Ctx, DEBUG_TYPE, *F, LoopLoc,
827 "Unable to fully unroll loop as directed by unroll pragma because "
828 "unrolled size is too large.");
829 return ExplicitUnroll;
830 }
831 assert(TripCount == 0 &&
832 "All cases when TripCount is constant should be covered here.");
833 if (PragmaFullUnroll)
834 emitOptimizationRemarkMissed(
835 Ctx, DEBUG_TYPE, *F, LoopLoc,
836 "Unable to fully unroll loop as directed by unroll(full) pragma "
837 "because loop has a runtime trip count.");
838
839 // 5th priority is runtime unrolling.
840 // Don't unroll a runtime trip count loop when it is disabled.
841 if (HasRuntimeUnrollDisablePragma(L)) {
842 UP.Count = 0;
843 return false;
844 }
845 // Reduce count based on the type of unrolling and the threshold values.
846 UP.Runtime |= PragmaEnableUnroll || PragmaCount > 0 || UserUnrollCount;
847 if (!UP.Runtime) {
848 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count "
849 << "-unroll-runtime not given\n");
850 UP.Count = 0;
851 return false;
852 }
853 if (UP.Count == 0)
854 UP.Count = DefaultUnrollRuntimeCount;
855 UnrolledSize = (LoopSize - BEInsns) * UP.Count + BEInsns;
856
857 // Reduce unroll count to be the largest power-of-two factor of
858 // the original count which satisfies the threshold limit.
859 while (UP.Count != 0 && UnrolledSize > UP.PartialThreshold) {
860 UP.Count >>= 1;
861 UnrolledSize = (LoopSize - BEInsns) * UP.Count + BEInsns;
862 }
863
864 unsigned OrigCount = UP.Count;
865
866 if (!UP.AllowRemainder && UP.Count != 0 && (TripMultiple % UP.Count) != 0) {
867 while (UP.Count != 0 && TripMultiple % UP.Count != 0)
868 UP.Count >>= 1;
869 DEBUG(dbgs() << "Remainder loop is restricted (that could architecture "
870 "specific or because the loop contains a convergent "
871 "instruction), so unroll count must divide the trip "
872 "multiple, "
873 << TripMultiple << ". Reducing unroll count from "
874 << OrigCount << " to " << UP.Count << ".\n");
875 if (PragmaCount > 0 && !UP.AllowRemainder)
876 emitOptimizationRemarkMissed(
877 Ctx, DEBUG_TYPE, *F, LoopLoc,
878 Twine("Unable to unroll loop the number of times directed by "
879 "unroll_count pragma because remainder loop is restricted "
880 "(that could architecture specific or because the loop "
881 "contains a convergent instruction) and so must have an unroll "
882 "count that divides the loop trip multiple of ") +
883 Twine(TripMultiple) + ". Unrolling instead " + Twine(UP.Count) +
884 " time(s).");
885 }
886
887 if (UP.Count > UP.MaxCount)
888 UP.Count = UP.MaxCount;
889 DEBUG(dbgs() << " partially unrolling with count: " << UP.Count << "\n");
890 if (UP.Count < 2)
891 UP.Count = 0;
892 return ExplicitUnroll;
893}
894
Justin Bognerb8d82ab2016-01-12 05:21:37 +0000895static bool tryToUnrollLoop(Loop *L, DominatorTree &DT, LoopInfo *LI,
896 ScalarEvolution *SE, const TargetTransformInfo &TTI,
897 AssumptionCache &AC, bool PreserveLCSSA,
898 Optional<unsigned> ProvidedCount,
899 Optional<unsigned> ProvidedThreshold,
900 Optional<bool> ProvidedAllowPartial,
901 Optional<bool> ProvidedRuntime) {
Dan Gohman2e1f8042007-05-08 15:19:19 +0000902 BasicBlock *Header = L->getHeader();
David Greenee0b97892010-01-05 01:27:44 +0000903 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
Dehao Chend55bc4c2016-05-05 00:54:54 +0000904 << "] Loop %" << Header->getName() << "\n");
Eli Benderskyff903242014-06-16 23:53:02 +0000905 if (HasUnrollDisablePragma(L)) {
906 return false;
907 }
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000908
909 unsigned NumInlineCandidates;
910 bool NotDuplicatable;
911 bool Convergent;
912 unsigned LoopSize = ApproximateLoopSize(
913 L, NumInlineCandidates, NotDuplicatable, Convergent, TTI, &AC);
914 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
915 if (NotDuplicatable) {
916 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
917 << " instructions.\n");
918 return false;
919 }
920 if (NumInlineCandidates != 0) {
921 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
922 return false;
923 }
Andrew Trick279e7a62011-07-23 00:29:16 +0000924
Andrew Trick2b6860f2011-08-11 23:36:16 +0000925 // Find trip count and trip multiple if count is not available
926 unsigned TripCount = 0;
Andrew Trick1cabe542011-07-23 00:33:05 +0000927 unsigned TripMultiple = 1;
Chandler Carruth6666c272014-10-11 00:12:11 +0000928 // If there are multiple exiting blocks but one of them is the latch, use the
929 // latch for the trip count estimation. Otherwise insist on a single exiting
930 // block for the trip count estimation.
931 BasicBlock *ExitingBlock = L->getLoopLatch();
932 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
933 ExitingBlock = L->getExitingBlock();
934 if (ExitingBlock) {
935 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
936 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +0000937 }
Hal Finkel8f2e7002013-09-11 19:25:43 +0000938
Justin Bognera1dd4932016-01-12 00:55:26 +0000939 TargetTransformInfo::UnrollingPreferences UP = gatherUnrollingPreferences(
940 L, TTI, ProvidedThreshold, ProvidedCount, ProvidedAllowPartial,
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000941 ProvidedRuntime);
Justin Bognera1dd4932016-01-12 00:55:26 +0000942
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000943 // If the loop contains a convergent operation, the prelude we'd add
944 // to do the first few instructions before we hit the unrolled loop
945 // is unsafe -- it adds a control-flow dependency to the convergent
946 // operation. Therefore restrict remainder loop (try unrollig without).
947 //
948 // TODO: This is quite conservative. In practice, convergent_op()
949 // is likely to be called unconditionally in the loop. In this
950 // case, the program would be ill-formed (on most architectures)
951 // unless n were the same on all threads in a thread group.
952 // Assuming n is the same on all threads, any kind of unrolling is
953 // safe. But currently llvm's notion of convergence isn't powerful
954 // enough to express this.
955 if (Convergent)
956 UP.AllowRemainder = false;
Eli Benderskydc6de2c2014-06-12 18:05:39 +0000957
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000958 bool IsCountSetExplicitly = computeUnrollCount(L, TTI, DT, LI, SE, TripCount,
959 TripMultiple, LoopSize, UP);
960 if (!UP.Count)
Eli Benderskyff903242014-06-16 23:53:02 +0000961 return false;
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000962 // Unroll factor (Count) must be less or equal to TripCount.
963 if (TripCount && UP.Count > TripCount)
964 UP.Count = TripCount;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000965
Dan Gohman3dc2d922008-05-14 00:24:14 +0000966 // Unroll the loop.
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000967 if (!UnrollLoop(L, UP.Count, TripCount, UP.Force, UP.Runtime,
968 UP.AllowExpensiveTripCount, TripMultiple, LI, SE, &DT, &AC,
969 PreserveLCSSA))
Dan Gohman3dc2d922008-05-14 00:24:14 +0000970 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000971
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000972 // If loop has an unroll count pragma or unrolled by explicitly set count
973 // mark loop as unrolled to prevent unrolling beyond that requested.
974 if (IsCountSetExplicitly)
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000975 SetLoopAlreadyUnrolled(L);
Chris Lattner946b2552004-04-18 05:20:17 +0000976 return true;
977}
Justin Bognerb8d82ab2016-01-12 05:21:37 +0000978
979namespace {
980class LoopUnroll : public LoopPass {
981public:
982 static char ID; // Pass ID, replacement for typeid
983 LoopUnroll(Optional<unsigned> Threshold = None,
984 Optional<unsigned> Count = None,
985 Optional<bool> AllowPartial = None, Optional<bool> Runtime = None)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000986 : LoopPass(ID), ProvidedCount(std::move(Count)),
987 ProvidedThreshold(Threshold), ProvidedAllowPartial(AllowPartial),
988 ProvidedRuntime(Runtime) {
Justin Bognerb8d82ab2016-01-12 05:21:37 +0000989 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
990 }
991
992 Optional<unsigned> ProvidedCount;
993 Optional<unsigned> ProvidedThreshold;
994 Optional<bool> ProvidedAllowPartial;
995 Optional<bool> ProvidedRuntime;
996
997 bool runOnLoop(Loop *L, LPPassManager &) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000998 if (skipLoop(L))
Justin Bognerb8d82ab2016-01-12 05:21:37 +0000999 return false;
1000
1001 Function &F = *L->getHeader()->getParent();
1002
1003 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1004 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1005 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1006 const TargetTransformInfo &TTI =
1007 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1008 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1009 bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
1010
1011 return tryToUnrollLoop(L, DT, LI, SE, TTI, AC, PreserveLCSSA, ProvidedCount,
1012 ProvidedThreshold, ProvidedAllowPartial,
1013 ProvidedRuntime);
1014 }
1015
1016 /// This transformation requires natural loop information & requires that
1017 /// loop preheaders be inserted into the CFG...
1018 ///
1019 void getAnalysisUsage(AnalysisUsage &AU) const override {
1020 AU.addRequired<AssumptionCacheTracker>();
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001021 AU.addRequired<TargetTransformInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +00001022 // FIXME: Loop passes are required to preserve domtree, and for now we just
1023 // recreate dom info if anything gets unrolled.
1024 getLoopAnalysisUsage(AU);
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001025 }
1026};
1027}
1028
1029char LoopUnroll::ID = 0;
1030INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001031INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth31088a92016-02-19 10:45:18 +00001032INITIALIZE_PASS_DEPENDENCY(LoopPass)
1033INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001034INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
1035
1036Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
1037 int Runtime) {
1038 // TODO: It would make more sense for this function to take the optionals
1039 // directly, but that's dangerous since it would silently break out of tree
1040 // callers.
1041 return new LoopUnroll(Threshold == -1 ? None : Optional<unsigned>(Threshold),
1042 Count == -1 ? None : Optional<unsigned>(Count),
1043 AllowPartial == -1 ? None
1044 : Optional<bool>(AllowPartial),
1045 Runtime == -1 ? None : Optional<bool>(Runtime));
1046}
1047
1048Pass *llvm::createSimpleLoopUnrollPass() {
1049 return llvm::createLoopUnrollPass(-1, -1, 0, 0);
1050}