blob: 509687ce472031582dc06c67ad538dad32a70828 [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"
Michael Zolotukhin1da4afd2016-02-08 23:03:59 +000022#include "llvm/Analysis/LoopUnrollAnalyzer.h"
Dan Gohman0141c132010-07-26 18:11:16 +000023#include "llvm/Analysis/ScalarEvolution.h"
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000024#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000025#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/DataLayout.h"
Eli Benderskyff903242014-06-16 23:53:02 +000027#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000029#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/IntrinsicInst.h"
Eli Benderskyff903242014-06-16 23:53:02 +000031#include "llvm/IR/Metadata.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000032#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000034#include "llvm/Support/raw_ostream.h"
Dan Gohman3dc2d922008-05-14 00:24:14 +000035#include "llvm/Transforms/Utils/UnrollLoop.h"
Duncan Sands67933e62008-05-16 09:30:00 +000036#include <climits>
Chris Lattner946b2552004-04-18 05:20:17 +000037
Dan Gohman3dc2d922008-05-14 00:24:14 +000038using namespace llvm;
Chris Lattner946b2552004-04-18 05:20:17 +000039
Chandler Carruth964daaa2014-04-22 02:55:47 +000040#define DEBUG_TYPE "loop-unroll"
41
Dan Gohmand78c4002008-05-13 00:00:25 +000042static cl::opt<unsigned>
Justin Bognera1dd4932016-01-12 00:55:26 +000043 UnrollThreshold("unroll-threshold", cl::Hidden,
Chandler Carruth9dabd142015-06-05 17:01:43 +000044 cl::desc("The baseline cost threshold for loop unrolling"));
45
46static cl::opt<unsigned> UnrollPercentDynamicCostSavedThreshold(
Justin Bognera1dd4932016-01-12 00:55:26 +000047 "unroll-percent-dynamic-cost-saved-threshold", cl::Hidden,
Chandler Carruth9dabd142015-06-05 17:01:43 +000048 cl::desc("The percentage of estimated dynamic cost which must be saved by "
49 "unrolling to allow unrolling up to the max threshold."));
50
51static cl::opt<unsigned> UnrollDynamicCostSavingsDiscount(
Justin Bognera1dd4932016-01-12 00:55:26 +000052 "unroll-dynamic-cost-savings-discount", cl::Hidden,
Chandler Carruth9dabd142015-06-05 17:01:43 +000053 cl::desc("This is the amount discounted from the total unroll cost when "
54 "the unrolled form has a high dynamic cost savings (triggered by "
55 "the '-unroll-perecent-dynamic-cost-saved-threshold' flag)."));
Dan Gohmand78c4002008-05-13 00:00:25 +000056
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000057static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
Chandler Carruth1fbc3162015-02-13 05:31:46 +000058 "unroll-max-iteration-count-to-analyze", cl::init(0), cl::Hidden,
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000059 cl::desc("Don't allow loop unrolling to simulate more than this number of"
60 "iterations when checking full unroll profitability"));
61
Dan Gohmand78c4002008-05-13 00:00:25 +000062static cl::opt<unsigned>
Justin Bognera1dd4932016-01-12 00:55:26 +000063UnrollCount("unroll-count", cl::Hidden,
Eli Benderskyff903242014-06-16 23:53:02 +000064 cl::desc("Use this unroll count for all loops including those with "
65 "unroll_count pragma values, for testing purposes"));
Dan Gohmand78c4002008-05-13 00:00:25 +000066
Matthijs Kooijman98b5c162008-07-29 13:21:23 +000067static cl::opt<bool>
Justin Bognera1dd4932016-01-12 00:55:26 +000068UnrollAllowPartial("unroll-allow-partial", cl::Hidden,
Matthijs Kooijman98b5c162008-07-29 13:21:23 +000069 cl::desc("Allows loops to be partially unrolled until "
70 "-unroll-threshold loop size is reached."));
71
Andrew Trickd04d15292011-12-09 06:19:40 +000072static cl::opt<bool>
Justin Bognera1dd4932016-01-12 00:55:26 +000073UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::Hidden,
Andrew Trickd04d15292011-12-09 06:19:40 +000074 cl::desc("Unroll loops with run-time trip counts"));
75
Eli Benderskyff903242014-06-16 23:53:02 +000076static cl::opt<unsigned>
77PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
Mark Heffernane6b4ba12014-07-23 17:31:37 +000078 cl::desc("Unrolled size limit for loops with an unroll(full) or "
Eli Benderskyff903242014-06-16 23:53:02 +000079 "unroll_count pragma."));
80
Justin Bognera1dd4932016-01-12 00:55:26 +000081
82/// A magic value for use with the Threshold parameter to indicate
83/// that the loop unroll should be performed regardless of how much
84/// code expansion would result.
85static const unsigned NoThreshold = UINT_MAX;
86
87/// Default unroll count for loops with run-time trip count if
88/// -unroll-count is not set
89static const unsigned DefaultUnrollRuntimeCount = 8;
90
91/// Gather the various unrolling parameters based on the defaults, compiler
92/// flags, TTI overrides, pragmas, and user specified parameters.
93static TargetTransformInfo::UnrollingPreferences gatherUnrollingPreferences(
94 Loop *L, const TargetTransformInfo &TTI, Optional<unsigned> UserThreshold,
95 Optional<unsigned> UserCount, Optional<bool> UserAllowPartial,
96 Optional<bool> UserRuntime, unsigned PragmaCount, bool PragmaFullUnroll,
97 bool PragmaEnableUnroll, unsigned TripCount) {
98 TargetTransformInfo::UnrollingPreferences UP;
99
100 // Set up the defaults
101 UP.Threshold = 150;
102 UP.PercentDynamicCostSavedThreshold = 20;
103 UP.DynamicCostSavingsDiscount = 2000;
104 UP.OptSizeThreshold = 50;
105 UP.PartialThreshold = UP.Threshold;
106 UP.PartialOptSizeThreshold = UP.OptSizeThreshold;
107 UP.Count = 0;
108 UP.MaxCount = UINT_MAX;
109 UP.Partial = false;
110 UP.Runtime = false;
111 UP.AllowExpensiveTripCount = false;
112
113 // Override with any target specific settings
114 TTI.getUnrollingPreferences(L, UP);
115
116 // Apply size attributes
117 if (L->getHeader()->getParent()->optForSize()) {
118 UP.Threshold = UP.OptSizeThreshold;
119 UP.PartialThreshold = UP.PartialOptSizeThreshold;
120 }
121
122 // Apply unroll count pragmas
123 if (PragmaCount)
124 UP.Count = PragmaCount;
125 else if (PragmaFullUnroll)
126 UP.Count = TripCount;
127
128 // Apply any user values specified by cl::opt
129 if (UnrollThreshold.getNumOccurrences() > 0) {
130 UP.Threshold = UnrollThreshold;
131 UP.PartialThreshold = UnrollThreshold;
132 }
133 if (UnrollPercentDynamicCostSavedThreshold.getNumOccurrences() > 0)
134 UP.PercentDynamicCostSavedThreshold =
135 UnrollPercentDynamicCostSavedThreshold;
136 if (UnrollDynamicCostSavingsDiscount.getNumOccurrences() > 0)
137 UP.DynamicCostSavingsDiscount = UnrollDynamicCostSavingsDiscount;
138 if (UnrollCount.getNumOccurrences() > 0)
139 UP.Count = UnrollCount;
140 if (UnrollAllowPartial.getNumOccurrences() > 0)
141 UP.Partial = UnrollAllowPartial;
142 if (UnrollRuntime.getNumOccurrences() > 0)
143 UP.Runtime = UnrollRuntime;
144
145 // Apply user values provided by argument
146 if (UserThreshold.hasValue()) {
147 UP.Threshold = *UserThreshold;
148 UP.PartialThreshold = *UserThreshold;
149 }
150 if (UserCount.hasValue())
151 UP.Count = *UserCount;
152 if (UserAllowPartial.hasValue())
153 UP.Partial = *UserAllowPartial;
154 if (UserRuntime.hasValue())
155 UP.Runtime = *UserRuntime;
156
157 if (PragmaCount > 0 ||
158 ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount != 0)) {
159 // If the loop has an unrolling pragma, we want to be more aggressive with
160 // unrolling limits. Set thresholds to at least the PragmaTheshold value
161 // which is larger than the default limits.
162 if (UP.Threshold != NoThreshold)
163 UP.Threshold = std::max<unsigned>(UP.Threshold, PragmaUnrollThreshold);
164 if (UP.PartialThreshold != NoThreshold)
165 UP.PartialThreshold =
166 std::max<unsigned>(UP.PartialThreshold, PragmaUnrollThreshold);
167 }
168
169 return UP;
170}
171
Chris Lattner79a42ac2006-12-19 21:40:18 +0000172namespace {
Chandler Carruth02156082015-05-22 17:41:35 +0000173struct EstimatedUnrollCost {
Chandler Carruth9dabd142015-06-05 17:01:43 +0000174 /// \brief The estimated cost after unrolling.
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000175 int UnrolledCost;
Chandler Carruth302a1332015-02-13 02:10:56 +0000176
Chandler Carruth9dabd142015-06-05 17:01:43 +0000177 /// \brief The estimated dynamic cost of executing the instructions in the
178 /// rolled form.
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000179 int RolledDynamicCost;
Chandler Carruth02156082015-05-22 17:41:35 +0000180};
181}
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000182
Chandler Carruth02156082015-05-22 17:41:35 +0000183/// \brief Figure out if the loop is worth full unrolling.
184///
185/// Complete loop unrolling can make some loads constant, and we need to know
186/// if that would expose any further optimization opportunities. This routine
Michael Zolotukhinc4e4f332015-06-11 22:17:39 +0000187/// estimates this optimization. It computes cost of unrolled loop
188/// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By
189/// dynamic cost we mean that we won't count costs of blocks that are known not
190/// to be executed (i.e. if we have a branch in the loop and we know that at the
191/// given iteration its condition would be resolved to true, we won't add up the
192/// cost of the 'false'-block).
193/// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If
194/// the analysis failed (no benefits expected from the unrolling, or the loop is
195/// too big to analyze), the returned value is None.
Benjamin Kramerfcdb1c12015-08-20 09:57:22 +0000196static Optional<EstimatedUnrollCost>
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000197analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, DominatorTree &DT,
198 ScalarEvolution &SE, const TargetTransformInfo &TTI,
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000199 int MaxUnrolledLoopSize) {
Chandler Carruth02156082015-05-22 17:41:35 +0000200 // We want to be able to scale offsets by the trip count and add more offsets
201 // to them without checking for overflows, and we already don't want to
202 // analyze *massive* trip counts, so we force the max to be reasonably small.
203 assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) &&
204 "The unroll iterations max is too large!");
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000205
Chandler Carruth02156082015-05-22 17:41:35 +0000206 // Don't simulate loops with a big or unknown tripcount
207 if (!UnrollMaxIterationsCountToAnalyze || !TripCount ||
208 TripCount > UnrollMaxIterationsCountToAnalyze)
209 return None;
Chandler Carrutha6ae8772015-05-12 23:32:56 +0000210
Chandler Carruth02156082015-05-22 17:41:35 +0000211 SmallSetVector<BasicBlock *, 16> BBWorklist;
212 DenseMap<Value *, Constant *> SimplifiedValues;
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000213 SmallVector<std::pair<Value *, Constant *>, 4> SimplifiedInputValues;
Chandler Carruth3b057b32015-02-13 03:57:40 +0000214
Chandler Carruth9dabd142015-06-05 17:01:43 +0000215 // The estimated cost of the unrolled form of the loop. We try to estimate
216 // this by simplifying as much as we can while computing the estimate.
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000217 int UnrolledCost = 0;
Chandler Carruth9dabd142015-06-05 17:01:43 +0000218 // We also track the estimated dynamic (that is, actually executed) cost in
219 // the rolled form. This helps identify cases when the savings from unrolling
220 // aren't just exposing dead control flows, but actual reduced dynamic
221 // instructions due to the simplifications which we expect to occur after
222 // unrolling.
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000223 int RolledDynamicCost = 0;
Chandler Carruth8c863752015-02-13 03:48:38 +0000224
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000225 // Ensure that we don't violate the loop structure invariants relied on by
226 // this analysis.
227 assert(L->isLoopSimplifyForm() && "Must put loop into normal form first.");
228 assert(L->isLCSSAForm(DT) &&
229 "Must have loops in LCSSA form to track live-out values.");
230
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000231 DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n");
232
Chandler Carruth02156082015-05-22 17:41:35 +0000233 // Simulate execution of each iteration of the loop counting instructions,
234 // which would be simplified.
235 // Since the same load will take different values on different iterations,
236 // we literally have to go through all loop's iterations.
237 for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000238 DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n");
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000239
240 // Prepare for the iteration by collecting any simplified entry or backedge
241 // inputs.
242 for (Instruction &I : *L->getHeader()) {
243 auto *PHI = dyn_cast<PHINode>(&I);
244 if (!PHI)
245 break;
246
247 // The loop header PHI nodes must have exactly two input: one from the
248 // loop preheader and one from the loop latch.
249 assert(
250 PHI->getNumIncomingValues() == 2 &&
251 "Must have an incoming value only for the preheader and the latch.");
252
253 Value *V = PHI->getIncomingValueForBlock(
254 Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch());
255 Constant *C = dyn_cast<Constant>(V);
256 if (Iteration != 0 && !C)
257 C = SimplifiedValues.lookup(V);
258 if (C)
259 SimplifiedInputValues.push_back({PHI, C});
260 }
261
262 // Now clear and re-populate the map for the next iteration.
Chandler Carruth02156082015-05-22 17:41:35 +0000263 SimplifiedValues.clear();
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000264 while (!SimplifiedInputValues.empty())
265 SimplifiedValues.insert(SimplifiedInputValues.pop_back_val());
266
Benjamin Kramer6db33382015-10-15 15:08:58 +0000267 UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SE);
Chandler Carruthf174a152015-05-22 02:47:29 +0000268
Chandler Carruth02156082015-05-22 17:41:35 +0000269 BBWorklist.clear();
270 BBWorklist.insert(L->getHeader());
271 // Note that we *must not* cache the size, this loop grows the worklist.
272 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
273 BasicBlock *BB = BBWorklist[Idx];
Chandler Carruthf174a152015-05-22 02:47:29 +0000274
Chandler Carruth02156082015-05-22 17:41:35 +0000275 // Visit all instructions in the given basic block and try to simplify
276 // it. We don't change the actual IR, just count optimization
277 // opportunities.
278 for (Instruction &I : *BB) {
Chandler Carruthb2fda0d2015-08-05 18:46:21 +0000279 int InstCost = TTI.getUserCost(&I);
Chandler Carruth17a04962015-02-13 03:49:41 +0000280
Chandler Carruth02156082015-05-22 17:41:35 +0000281 // Visit the instruction to analyze its loop cost after unrolling,
Chandler Carruth9dabd142015-06-05 17:01:43 +0000282 // and if the visitor returns false, include this instruction in the
283 // unrolled cost.
284 if (!Analyzer.visit(I))
285 UnrolledCost += InstCost;
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000286 else {
287 DEBUG(dbgs() << " " << I
288 << " would be simplified if loop is unrolled.\n");
289 (void)0;
290 }
Chandler Carruth9dabd142015-06-05 17:01:43 +0000291
292 // Also track this instructions expected cost when executing the rolled
293 // loop form.
294 RolledDynamicCost += InstCost;
Chandler Carruth02156082015-05-22 17:41:35 +0000295
296 // If unrolled body turns out to be too big, bail out.
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000297 if (UnrolledCost > MaxUnrolledLoopSize) {
298 DEBUG(dbgs() << " Exceeded threshold.. exiting.\n"
299 << " UnrolledCost: " << UnrolledCost
300 << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize
301 << "\n");
Chandler Carruth02156082015-05-22 17:41:35 +0000302 return None;
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000303 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000304 }
Chandler Carruth415f4122015-02-13 02:17:39 +0000305
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000306 TerminatorInst *TI = BB->getTerminator();
307
308 // Add in the live successors by first checking whether we have terminator
309 // that may be simplified based on the values simplified by this call.
310 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
311 if (BI->isConditional()) {
312 if (Constant *SimpleCond =
313 SimplifiedValues.lookup(BI->getCondition())) {
Michael Zolotukhin3a7d55b2015-07-29 18:10:29 +0000314 BasicBlock *Succ = nullptr;
315 // Just take the first successor if condition is undef
316 if (isa<UndefValue>(SimpleCond))
317 Succ = BI->getSuccessor(0);
318 else
319 Succ = BI->getSuccessor(
320 cast<ConstantInt>(SimpleCond)->isZero() ? 1 : 0);
Michael Zolotukhina425c9d2015-07-28 19:21:21 +0000321 if (L->contains(Succ))
322 BBWorklist.insert(Succ);
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000323 continue;
324 }
325 }
326 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
327 if (Constant *SimpleCond =
328 SimplifiedValues.lookup(SI->getCondition())) {
Michael Zolotukhin3a7d55b2015-07-29 18:10:29 +0000329 BasicBlock *Succ = nullptr;
330 // Just take the first successor if condition is undef
331 if (isa<UndefValue>(SimpleCond))
332 Succ = SI->getSuccessor(0);
333 else
Michael Zolotukhin9f06ef72015-07-29 18:10:33 +0000334 Succ = SI->findCaseValue(cast<ConstantInt>(SimpleCond))
335 .getCaseSuccessor();
Michael Zolotukhina425c9d2015-07-28 19:21:21 +0000336 if (L->contains(Succ))
337 BBWorklist.insert(Succ);
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000338 continue;
339 }
340 }
341
Chandler Carruth02156082015-05-22 17:41:35 +0000342 // Add BB's successors to the worklist.
343 for (BasicBlock *Succ : successors(BB))
344 if (L->contains(Succ))
345 BBWorklist.insert(Succ);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000346 }
Chandler Carruth02156082015-05-22 17:41:35 +0000347
348 // If we found no optimization opportunities on the first iteration, we
349 // won't find them on later ones too.
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000350 if (UnrolledCost == RolledDynamicCost) {
351 DEBUG(dbgs() << " No opportunities found.. exiting.\n"
352 << " UnrolledCost: " << UnrolledCost << "\n");
Chandler Carruth02156082015-05-22 17:41:35 +0000353 return None;
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000354 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000355 }
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000356 DEBUG(dbgs() << "Analysis finished:\n"
357 << "UnrolledCost: " << UnrolledCost << ", "
358 << "RolledDynamicCost: " << RolledDynamicCost << "\n");
Chandler Carruth9dabd142015-06-05 17:01:43 +0000359 return {{UnrolledCost, RolledDynamicCost}};
Chandler Carruth02156082015-05-22 17:41:35 +0000360}
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000361
Dan Gohman49d08a52007-05-08 15:14:19 +0000362/// ApproximateLoopSize - Approximate the size of the loop.
Andrew Trickf7656012011-10-01 01:39:05 +0000363static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000364 bool &NotDuplicatable,
Hal Finkel57f03dd2014-09-07 13:49:57 +0000365 const TargetTransformInfo &TTI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000366 AssumptionCache *AC) {
Hal Finkel57f03dd2014-09-07 13:49:57 +0000367 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000368 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000369
Dan Gohman969e83a2009-10-31 14:54:17 +0000370 CodeMetrics Metrics;
Dan Gohman90071072008-06-22 20:18:58 +0000371 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
Dan Gohman969e83a2009-10-31 14:54:17 +0000372 I != E; ++I)
Hal Finkel57f03dd2014-09-07 13:49:57 +0000373 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
Owen Anderson04cf3fd2010-09-09 20:32:23 +0000374 NumCalls = Metrics.NumInlineCandidates;
James Molloy4f6fb952012-12-20 16:04:27 +0000375 NotDuplicatable = Metrics.notDuplicatable;
Andrew Trick279e7a62011-07-23 00:29:16 +0000376
Owen Anderson62ea1b72010-09-09 19:07:31 +0000377 unsigned LoopSize = Metrics.NumInsts;
Andrew Trick279e7a62011-07-23 00:29:16 +0000378
Owen Anderson62ea1b72010-09-09 19:07:31 +0000379 // Don't allow an estimate of size zero. This would allows unrolling of loops
380 // with huge iteration counts, which is a compile time problem even if it's
Hal Finkel38dd5902015-01-10 00:30:55 +0000381 // not a problem for code quality. Also, the code using this size may assume
382 // that each loop has at least three instructions (likely a conditional
383 // branch, a comparison feeding that branch, and some kind of loop increment
384 // feeding that comparison instruction).
385 LoopSize = std::max(LoopSize, 3u);
Andrew Trick279e7a62011-07-23 00:29:16 +0000386
Owen Anderson62ea1b72010-09-09 19:07:31 +0000387 return LoopSize;
Chris Lattner946b2552004-04-18 05:20:17 +0000388}
389
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000390// Returns the loop hint metadata node with the given name (for example,
391// "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
392// returned.
Jingyue Wu49a766e2015-02-02 20:41:11 +0000393static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
394 if (MDNode *LoopID = L->getLoopID())
395 return GetUnrollMetadata(LoopID, Name);
396 return nullptr;
Eli Benderskyff903242014-06-16 23:53:02 +0000397}
398
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000399// Returns true if the loop has an unroll(full) pragma.
400static bool HasUnrollFullPragma(const Loop *L) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000401 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
Eli Benderskyff903242014-06-16 23:53:02 +0000402}
403
Mark Heffernan89391542015-08-10 17:28:08 +0000404// Returns true if the loop has an unroll(enable) pragma. This metadata is used
405// for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives.
406static bool HasUnrollEnablePragma(const Loop *L) {
407 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.enable");
408}
409
Eli Benderskyff903242014-06-16 23:53:02 +0000410// Returns true if the loop has an unroll(disable) pragma.
411static bool HasUnrollDisablePragma(const Loop *L) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000412 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
Eli Benderskyff903242014-06-16 23:53:02 +0000413}
414
Kevin Qin715b01e2015-03-09 06:14:18 +0000415// Returns true if the loop has an runtime unroll(disable) pragma.
416static bool HasRuntimeUnrollDisablePragma(const Loop *L) {
417 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
418}
419
Eli Benderskyff903242014-06-16 23:53:02 +0000420// If loop has an unroll_count pragma return the (necessarily
421// positive) value from the pragma. Otherwise return 0.
422static unsigned UnrollCountPragmaValue(const Loop *L) {
Jingyue Wu49a766e2015-02-02 20:41:11 +0000423 MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000424 if (MD) {
425 assert(MD->getNumOperands() == 2 &&
426 "Unroll count hint metadata should have two operands.");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000427 unsigned Count =
428 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
Eli Benderskyff903242014-06-16 23:53:02 +0000429 assert(Count >= 1 && "Unroll count must be positive.");
430 return Count;
431 }
432 return 0;
433}
434
Mark Heffernan053a6862014-07-18 21:04:33 +0000435// Remove existing unroll metadata and add unroll disable metadata to
436// indicate the loop has already been unrolled. This prevents a loop
437// from being unrolled more than is directed by a pragma if the loop
438// unrolling pass is run more than once (which it generally is).
439static void SetLoopAlreadyUnrolled(Loop *L) {
440 MDNode *LoopID = L->getLoopID();
441 if (!LoopID) return;
442
443 // First remove any existing loop unrolling metadata.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000444 SmallVector<Metadata *, 4> MDs;
Mark Heffernan053a6862014-07-18 21:04:33 +0000445 // Reserve first location for self reference to the LoopID metadata node.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000446 MDs.push_back(nullptr);
Mark Heffernan053a6862014-07-18 21:04:33 +0000447 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
448 bool IsUnrollMetadata = false;
449 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
450 if (MD) {
451 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
452 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
453 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000454 if (!IsUnrollMetadata)
455 MDs.push_back(LoopID->getOperand(i));
Mark Heffernan053a6862014-07-18 21:04:33 +0000456 }
457
458 // Add unroll(disable) metadata to disable future unrolling.
459 LLVMContext &Context = L->getHeader()->getContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000460 SmallVector<Metadata *, 1> DisableOperands;
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000461 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
Mark Heffernanf3764da2014-07-18 21:29:41 +0000462 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000463 MDs.push_back(DisableNode);
Mark Heffernan053a6862014-07-18 21:04:33 +0000464
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000465 MDNode *NewLoopID = MDNode::get(Context, MDs);
Mark Heffernan053a6862014-07-18 21:04:33 +0000466 // Set operand 0 to refer to the loop id itself.
467 NewLoopID->replaceOperandWith(0, NewLoopID);
468 L->setLoopID(NewLoopID);
Mark Heffernan053a6862014-07-18 21:04:33 +0000469}
470
Justin Bogner921b04e2016-01-12 01:06:32 +0000471static bool canUnrollCompletely(Loop *L, unsigned Threshold,
472 unsigned PercentDynamicCostSavedThreshold,
473 unsigned DynamicCostSavingsDiscount,
474 uint64_t UnrolledCost,
475 uint64_t RolledDynamicCost) {
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000476 if (Threshold == NoThreshold) {
477 DEBUG(dbgs() << " Can fully unroll, because no threshold is set.\n");
478 return true;
479 }
480
Chandler Carruth9dabd142015-06-05 17:01:43 +0000481 if (UnrolledCost <= Threshold) {
482 DEBUG(dbgs() << " Can fully unroll, because unrolled cost: "
483 << UnrolledCost << "<" << Threshold << "\n");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000484 return true;
485 }
486
Chandler Carruth9dabd142015-06-05 17:01:43 +0000487 assert(UnrolledCost && "UnrolledCost can't be 0 at this point.");
488 assert(RolledDynamicCost >= UnrolledCost &&
489 "Cannot have a higher unrolled cost than a rolled cost!");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000490
Chandler Carruth9dabd142015-06-05 17:01:43 +0000491 // Compute the percentage of the dynamic cost in the rolled form that is
492 // saved when unrolled. If unrolling dramatically reduces the estimated
493 // dynamic cost of the loop, we use a higher threshold to allow more
494 // unrolling.
495 unsigned PercentDynamicCostSaved =
496 (uint64_t)(RolledDynamicCost - UnrolledCost) * 100ull / RolledDynamicCost;
497
498 if (PercentDynamicCostSaved >= PercentDynamicCostSavedThreshold &&
499 (int64_t)UnrolledCost - (int64_t)DynamicCostSavingsDiscount <=
500 (int64_t)Threshold) {
501 DEBUG(dbgs() << " Can fully unroll, because unrolling will reduce the "
502 "expected dynamic cost by " << PercentDynamicCostSaved
503 << "% (threshold: " << PercentDynamicCostSavedThreshold
504 << "%)\n"
505 << " and the unrolled cost (" << UnrolledCost
506 << ") is less than the max threshold ("
507 << DynamicCostSavingsDiscount << ").\n");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000508 return true;
509 }
510
511 DEBUG(dbgs() << " Too large to fully unroll:\n");
Chandler Carruth9dabd142015-06-05 17:01:43 +0000512 DEBUG(dbgs() << " Threshold: " << Threshold << "\n");
513 DEBUG(dbgs() << " Max threshold: " << DynamicCostSavingsDiscount << "\n");
514 DEBUG(dbgs() << " Percent cost saved threshold: "
515 << PercentDynamicCostSavedThreshold << "%\n");
516 DEBUG(dbgs() << " Unrolled cost: " << UnrolledCost << "\n");
517 DEBUG(dbgs() << " Rolled dynamic cost: " << RolledDynamicCost << "\n");
518 DEBUG(dbgs() << " Percent cost saved: " << PercentDynamicCostSaved
519 << "\n");
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000520 return false;
521}
522
Justin Bognerb8d82ab2016-01-12 05:21:37 +0000523static bool tryToUnrollLoop(Loop *L, DominatorTree &DT, LoopInfo *LI,
524 ScalarEvolution *SE, const TargetTransformInfo &TTI,
525 AssumptionCache &AC, bool PreserveLCSSA,
526 Optional<unsigned> ProvidedCount,
527 Optional<unsigned> ProvidedThreshold,
528 Optional<bool> ProvidedAllowPartial,
529 Optional<bool> ProvidedRuntime) {
Dan Gohman2e1f8042007-05-08 15:19:19 +0000530 BasicBlock *Header = L->getHeader();
David Greenee0b97892010-01-05 01:27:44 +0000531 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000532 << "] Loop %" << Header->getName() << "\n");
Eli Benderskyff903242014-06-16 23:53:02 +0000533
534 if (HasUnrollDisablePragma(L)) {
535 return false;
536 }
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000537 bool PragmaFullUnroll = HasUnrollFullPragma(L);
Mark Heffernan89391542015-08-10 17:28:08 +0000538 bool PragmaEnableUnroll = HasUnrollEnablePragma(L);
Eli Benderskyff903242014-06-16 23:53:02 +0000539 unsigned PragmaCount = UnrollCountPragmaValue(L);
Mark Heffernan89391542015-08-10 17:28:08 +0000540 bool HasPragma = PragmaFullUnroll || PragmaEnableUnroll || PragmaCount > 0;
Andrew Trick279e7a62011-07-23 00:29:16 +0000541
Andrew Trick2b6860f2011-08-11 23:36:16 +0000542 // Find trip count and trip multiple if count is not available
543 unsigned TripCount = 0;
Andrew Trick1cabe542011-07-23 00:33:05 +0000544 unsigned TripMultiple = 1;
Chandler Carruth6666c272014-10-11 00:12:11 +0000545 // If there are multiple exiting blocks but one of them is the latch, use the
546 // latch for the trip count estimation. Otherwise insist on a single exiting
547 // block for the trip count estimation.
548 BasicBlock *ExitingBlock = L->getLoopLatch();
549 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
550 ExitingBlock = L->getExitingBlock();
551 if (ExitingBlock) {
552 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
553 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +0000554 }
Hal Finkel8f2e7002013-09-11 19:25:43 +0000555
Justin Bognera1dd4932016-01-12 00:55:26 +0000556 TargetTransformInfo::UnrollingPreferences UP = gatherUnrollingPreferences(
557 L, TTI, ProvidedThreshold, ProvidedCount, ProvidedAllowPartial,
558 ProvidedRuntime, PragmaCount, PragmaFullUnroll, PragmaEnableUnroll,
559 TripCount);
560
561 unsigned Count = UP.Count;
562 bool CountSetExplicitly = Count != 0;
563 // Use a heuristic count if we didn't set anything explicitly.
564 if (!CountSetExplicitly)
565 Count = TripCount == 0 ? DefaultUnrollRuntimeCount : TripCount;
566 if (TripCount && Count > TripCount)
567 Count = TripCount;
Eli Benderskydc6de2c2014-06-12 18:05:39 +0000568
Eli Benderskyff903242014-06-16 23:53:02 +0000569 unsigned NumInlineCandidates;
570 bool notDuplicatable;
571 unsigned LoopSize =
Chandler Carruth66b31302015-01-04 12:03:27 +0000572 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC);
Eli Benderskyff903242014-06-16 23:53:02 +0000573 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
Hal Finkel38dd5902015-01-10 00:30:55 +0000574
575 // When computing the unrolled size, note that the conditional branch on the
576 // backedge and the comparison feeding it are not replicated like the rest of
577 // the loop body (which is why 2 is subtracted).
578 uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2;
Eli Benderskyff903242014-06-16 23:53:02 +0000579 if (notDuplicatable) {
580 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
581 << " instructions.\n");
582 return false;
583 }
584 if (NumInlineCandidates != 0) {
585 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
586 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000587 }
588
Eli Benderskyff903242014-06-16 23:53:02 +0000589 // Given Count, TripCount and thresholds determine the type of
590 // unrolling which is to be performed.
591 enum { Full = 0, Partial = 1, Runtime = 2 };
592 int Unrolling;
593 if (TripCount && Count == TripCount) {
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000594 Unrolling = Partial;
595 // If the loop is really small, we don't need to run an expensive analysis.
Justin Bognera1dd4932016-01-12 00:55:26 +0000596 if (canUnrollCompletely(L, UP.Threshold, 100, UP.DynamicCostSavingsDiscount,
Chandler Carruth9dabd142015-06-05 17:01:43 +0000597 UnrolledSize, UnrolledSize)) {
Eli Benderskyff903242014-06-16 23:53:02 +0000598 Unrolling = Full;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000599 } else {
600 // The loop isn't that small, but we still can fully unroll it if that
601 // helps to remove a significant number of instructions.
602 // To check that, run additional analysis on the loop.
Justin Bognera1dd4932016-01-12 00:55:26 +0000603 if (Optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost(
604 L, TripCount, DT, *SE, TTI,
605 UP.Threshold + UP.DynamicCostSavingsDiscount))
606 if (canUnrollCompletely(L, UP.Threshold,
607 UP.PercentDynamicCostSavedThreshold,
608 UP.DynamicCostSavingsDiscount,
609 Cost->UnrolledCost, Cost->RolledDynamicCost)) {
Chandler Carruth02156082015-05-22 17:41:35 +0000610 Unrolling = Full;
611 }
Dan Gohman2980d9d2007-05-11 20:53:41 +0000612 }
Eli Benderskyff903242014-06-16 23:53:02 +0000613 } else if (TripCount && Count < TripCount) {
614 Unrolling = Partial;
615 } else {
616 Unrolling = Runtime;
617 }
618
619 // Reduce count based on the type of unrolling and the threshold values.
620 unsigned OriginalCount = Count;
Justin Bognera1dd4932016-01-12 00:55:26 +0000621 bool AllowRuntime = PragmaEnableUnroll || (PragmaCount > 0) || UP.Runtime;
Mark Heffernand7ebc242015-07-13 18:26:27 +0000622 // Don't unroll a runtime trip count loop with unroll full pragma.
623 if (HasRuntimeUnrollDisablePragma(L) || PragmaFullUnroll) {
Kevin Qin715b01e2015-03-09 06:14:18 +0000624 AllowRuntime = false;
625 }
Eli Benderskyff903242014-06-16 23:53:02 +0000626 if (Unrolling == Partial) {
Justin Bognera1dd4932016-01-12 00:55:26 +0000627 bool AllowPartial = PragmaEnableUnroll || UP.Partial;
Eli Benderskyff903242014-06-16 23:53:02 +0000628 if (!AllowPartial && !CountSetExplicitly) {
629 DEBUG(dbgs() << " will not try to unroll partially because "
630 << "-unroll-allow-partial not given\n");
631 return false;
632 }
Justin Bognera1dd4932016-01-12 00:55:26 +0000633 if (UP.PartialThreshold != NoThreshold &&
634 UnrolledSize > UP.PartialThreshold) {
Eli Benderskyff903242014-06-16 23:53:02 +0000635 // Reduce unroll count to be modulo of TripCount for partial unrolling.
Justin Bognera1dd4932016-01-12 00:55:26 +0000636 Count = (std::max(UP.PartialThreshold, 3u) - 2) / (LoopSize - 2);
Eli Benderskyff903242014-06-16 23:53:02 +0000637 while (Count != 0 && TripCount % Count != 0)
638 Count--;
639 }
640 } else if (Unrolling == Runtime) {
641 if (!AllowRuntime && !CountSetExplicitly) {
642 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count "
643 << "-unroll-runtime not given\n");
644 return false;
645 }
646 // Reduce unroll count to be the largest power-of-two factor of
647 // the original count which satisfies the threshold limit.
Justin Bognera1dd4932016-01-12 00:55:26 +0000648 while (Count != 0 && UnrolledSize > UP.PartialThreshold) {
Eli Benderskyff903242014-06-16 23:53:02 +0000649 Count >>= 1;
Hal Finkel38dd5902015-01-10 00:30:55 +0000650 UnrolledSize = (LoopSize-2) * Count + 2;
Eli Benderskyff903242014-06-16 23:53:02 +0000651 }
652 if (Count > UP.MaxCount)
653 Count = UP.MaxCount;
654 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
655 }
656
657 if (HasPragma) {
Mark Heffernan9e112442014-07-23 20:05:44 +0000658 if (PragmaCount != 0)
659 // If loop has an unroll count pragma mark loop as unrolled to prevent
660 // unrolling beyond that requested by the pragma.
661 SetLoopAlreadyUnrolled(L);
Mark Heffernan053a6862014-07-18 21:04:33 +0000662
Eli Benderskyff903242014-06-16 23:53:02 +0000663 // Emit optimization remarks if we are unable to unroll the loop
664 // as directed by a pragma.
665 DebugLoc LoopLoc = L->getStartLoc();
666 Function *F = Header->getParent();
667 LLVMContext &Ctx = F->getContext();
Mark Heffernan89391542015-08-10 17:28:08 +0000668 if ((PragmaCount > 0) && Count != OriginalCount) {
Eli Benderskyff903242014-06-16 23:53:02 +0000669 emitOptimizationRemarkMissed(
670 Ctx, DEBUG_TYPE, *F, LoopLoc,
671 "Unable to unroll loop the number of times directed by "
672 "unroll_count pragma because unrolled size is too large.");
Mark Heffernan89391542015-08-10 17:28:08 +0000673 } else if (PragmaFullUnroll && !TripCount) {
674 emitOptimizationRemarkMissed(
675 Ctx, DEBUG_TYPE, *F, LoopLoc,
676 "Unable to fully unroll loop as directed by unroll(full) pragma "
677 "because loop has a runtime trip count.");
678 } else if (PragmaEnableUnroll && Count != TripCount && Count < 2) {
679 emitOptimizationRemarkMissed(
680 Ctx, DEBUG_TYPE, *F, LoopLoc,
681 "Unable to unroll loop as directed by unroll(enable) pragma because "
682 "unrolled size is too large.");
683 } else if ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount &&
684 Count != TripCount) {
685 emitOptimizationRemarkMissed(
686 Ctx, DEBUG_TYPE, *F, LoopLoc,
687 "Unable to fully unroll loop as directed by unroll pragma because "
688 "unrolled size is too large.");
Eli Benderskyff903242014-06-16 23:53:02 +0000689 }
690 }
691
692 if (Unrolling != Full && Count < 2) {
693 // Partial unrolling by 1 is a nop. For full unrolling, a factor
694 // of 1 makes sense because loop control can be eliminated.
695 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000696 }
697
Dan Gohman3dc2d922008-05-14 00:24:14 +0000698 // Unroll the loop.
Sanjoy Dase178f462015-04-14 03:20:38 +0000699 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, UP.AllowExpensiveTripCount,
Justin Bogner883a3ea2015-12-16 18:40:20 +0000700 TripMultiple, LI, SE, &DT, &AC, PreserveLCSSA))
Dan Gohman3dc2d922008-05-14 00:24:14 +0000701 return false;
Dan Gohman2980d9d2007-05-11 20:53:41 +0000702
Chris Lattner946b2552004-04-18 05:20:17 +0000703 return true;
704}
Justin Bognerb8d82ab2016-01-12 05:21:37 +0000705
706namespace {
707class LoopUnroll : public LoopPass {
708public:
709 static char ID; // Pass ID, replacement for typeid
710 LoopUnroll(Optional<unsigned> Threshold = None,
711 Optional<unsigned> Count = None,
712 Optional<bool> AllowPartial = None, Optional<bool> Runtime = None)
713 : LoopPass(ID), ProvidedCount(Count), ProvidedThreshold(Threshold),
714 ProvidedAllowPartial(AllowPartial), ProvidedRuntime(Runtime) {
715 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
716 }
717
718 Optional<unsigned> ProvidedCount;
719 Optional<unsigned> ProvidedThreshold;
720 Optional<bool> ProvidedAllowPartial;
721 Optional<bool> ProvidedRuntime;
722
723 bool runOnLoop(Loop *L, LPPassManager &) override {
724 if (skipOptnoneFunction(L))
725 return false;
726
727 Function &F = *L->getHeader()->getParent();
728
729 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
730 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
731 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
732 const TargetTransformInfo &TTI =
733 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
734 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
735 bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
736
737 return tryToUnrollLoop(L, DT, LI, SE, TTI, AC, PreserveLCSSA, ProvidedCount,
738 ProvidedThreshold, ProvidedAllowPartial,
739 ProvidedRuntime);
740 }
741
742 /// This transformation requires natural loop information & requires that
743 /// loop preheaders be inserted into the CFG...
744 ///
745 void getAnalysisUsage(AnalysisUsage &AU) const override {
746 AU.addRequired<AssumptionCacheTracker>();
747 AU.addRequired<DominatorTreeWrapperPass>();
748 AU.addRequired<LoopInfoWrapperPass>();
749 AU.addPreserved<LoopInfoWrapperPass>();
750 AU.addRequiredID(LoopSimplifyID);
751 AU.addPreservedID(LoopSimplifyID);
752 AU.addRequiredID(LCSSAID);
753 AU.addPreservedID(LCSSAID);
754 AU.addRequired<ScalarEvolutionWrapperPass>();
755 AU.addPreserved<ScalarEvolutionWrapperPass>();
756 AU.addRequired<TargetTransformInfoWrapperPass>();
757 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
758 // If loop unroll does not preserve dom info then LCSSA pass on next
759 // loop will receive invalid dom info.
760 // For now, recreate dom info, if loop is unrolled.
761 AU.addPreserved<DominatorTreeWrapperPass>();
762 AU.addPreserved<GlobalsAAWrapperPass>();
763 }
764};
765}
766
767char LoopUnroll::ID = 0;
768INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
769INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
770INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
771INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
772INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
773INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
774INITIALIZE_PASS_DEPENDENCY(LCSSA)
775INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
776INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
777
778Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
779 int Runtime) {
780 // TODO: It would make more sense for this function to take the optionals
781 // directly, but that's dangerous since it would silently break out of tree
782 // callers.
783 return new LoopUnroll(Threshold == -1 ? None : Optional<unsigned>(Threshold),
784 Count == -1 ? None : Optional<unsigned>(Count),
785 AllowPartial == -1 ? None
786 : Optional<bool>(AllowPartial),
787 Runtime == -1 ? None : Optional<bool>(Runtime));
788}
789
790Pass *llvm::createSimpleLoopUnrollPass() {
791 return llvm::createLoopUnrollPass(-1, -1, 0, 0);
792}