blob: a6d4164c364551736f4389fca583a03be1ea8a27 [file] [log] [blame]
Eugene Zelenko306d2992017-10-18 21:46:47 +00001//===- LoopUnroll.cpp - Loop unroller pass --------------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Misha Brukmanb1c93172005-04-21 23:48:37 +00006//
Chris Lattner946b2552004-04-18 05:20:17 +00007//===----------------------------------------------------------------------===//
8//
9// This pass implements a simple loop unroller. It works best when loops have
10// been canonicalized by the -indvars pass, allowing it to determine the trip
11// counts of loops easily.
Chris Lattner946b2552004-04-18 05:20:17 +000012//===----------------------------------------------------------------------===//
13
Sean Silvae3c18a52016-07-19 23:54:23 +000014#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/DenseMapInfo.h"
17#include "llvm/ADT/DenseSet.h"
18#include "llvm/ADT/None.h"
19#include "llvm/ADT/Optional.h"
20#include "llvm/ADT/STLExtras.h"
Chandler Carruth3b057b32015-02-13 03:57:40 +000021#include "llvm/ADT/SetVector.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000022#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/StringRef.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000025#include "llvm/Analysis/AssumptionCache.h"
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +000026#include "llvm/Analysis/BlockFrequencyInfo.h"
Chris Lattner679572e2011-01-02 07:35:53 +000027#include "llvm/Analysis/CodeMetrics.h"
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +000028#include "llvm/Analysis/LazyBlockFrequencyInfo.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000029#include "llvm/Analysis/LoopAnalysisManager.h"
30#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Analysis/LoopPass.h"
Michael Zolotukhin1da4afd2016-02-08 23:03:59 +000032#include "llvm/Analysis/LoopUnrollAnalyzer.h"
Adam Nemet0965da22017-10-09 23:19:02 +000033#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Teresa Johnson8482e562017-08-03 23:42:58 +000034#include "llvm/Analysis/ProfileSummaryInfo.h"
Dan Gohman0141c132010-07-26 18:11:16 +000035#include "llvm/Analysis/ScalarEvolution.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000036#include "llvm/Analysis/TargetTransformInfo.h"
37#include "llvm/IR/BasicBlock.h"
38#include "llvm/IR/CFG.h"
39#include "llvm/IR/Constant.h"
40#include "llvm/IR/Constants.h"
41#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000042#include "llvm/IR/Dominators.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000043#include "llvm/IR/Function.h"
44#include "llvm/IR/Instruction.h"
45#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/IntrinsicInst.h"
Eli Benderskyff903242014-06-16 23:53:02 +000047#include "llvm/IR/Metadata.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000048#include "llvm/IR/PassManager.h"
49#include "llvm/Pass.h"
50#include "llvm/Support/Casting.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000051#include "llvm/Support/CommandLine.h"
52#include "llvm/Support/Debug.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000053#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000054#include "llvm/Support/raw_ostream.h"
Dehao Chend55bc4c2016-05-05 00:54:54 +000055#include "llvm/Transforms/Scalar.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000056#include "llvm/Transforms/Scalar/LoopPassManager.h"
David Blaikiea373d182018-03-28 17:44:36 +000057#include "llvm/Transforms/Utils.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000058#include "llvm/Transforms/Utils/LoopSimplify.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000059#include "llvm/Transforms/Utils/LoopUtils.h"
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +000060#include "llvm/Transforms/Utils/SizeOpts.h"
Dan Gohman3dc2d922008-05-14 00:24:14 +000061#include "llvm/Transforms/Utils/UnrollLoop.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000062#include <algorithm>
63#include <cassert>
64#include <cstdint>
65#include <limits>
66#include <string>
67#include <tuple>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000068#include <utility>
Chris Lattner946b2552004-04-18 05:20:17 +000069
Dan Gohman3dc2d922008-05-14 00:24:14 +000070using namespace llvm;
Chris Lattner946b2552004-04-18 05:20:17 +000071
Chandler Carruth964daaa2014-04-22 02:55:47 +000072#define DEBUG_TYPE "loop-unroll"
73
Alina Sbirlead82ddfa2019-05-23 21:52:59 +000074cl::opt<bool> llvm::ForgetSCEVInLoopUnroll(
75 "forget-scev-loop-unroll", cl::init(false), cl::Hidden,
76 cl::desc("Forget everything in SCEV when doing LoopUnroll, instead of just"
77 " the current top-most loop. This is somtimes preferred to reduce"
78 " compile time."));
79
Dan Gohmand78c4002008-05-13 00:00:25 +000080static cl::opt<unsigned>
Justin Bognera1dd4932016-01-12 00:55:26 +000081 UnrollThreshold("unroll-threshold", cl::Hidden,
Dehao Chenc3f87f02017-01-17 23:39:33 +000082 cl::desc("The cost threshold for loop unrolling"));
83
84static cl::opt<unsigned> UnrollPartialThreshold(
85 "unroll-partial-threshold", cl::Hidden,
86 cl::desc("The cost threshold for partial loop unrolling"));
Chandler Carruth9dabd142015-06-05 17:01:43 +000087
Dehao Chencc763442016-12-30 00:50:28 +000088static cl::opt<unsigned> UnrollMaxPercentThresholdBoost(
89 "unroll-max-percent-threshold-boost", cl::init(400), cl::Hidden,
90 cl::desc("The maximum 'boost' (represented as a percentage >= 100) applied "
91 "to the threshold when aggressively unrolling a loop due to the "
92 "dynamic cost savings. If completely unrolling a loop will reduce "
93 "the total runtime from X to Y, we boost the loop unroll "
94 "threshold to DefaultThreshold*std::min(MaxPercentThresholdBoost, "
95 "X/Y). This limit avoids excessive code bloat."));
Dan Gohmand78c4002008-05-13 00:00:25 +000096
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000097static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
Michael Zolotukhin8f7a2422016-05-24 23:00:05 +000098 "unroll-max-iteration-count-to-analyze", cl::init(10), cl::Hidden,
Michael Zolotukhina9aadd22015-02-05 02:34:00 +000099 cl::desc("Don't allow loop unrolling to simulate more than this number of"
100 "iterations when checking full unroll profitability"));
101
Dehao Chend55bc4c2016-05-05 00:54:54 +0000102static cl::opt<unsigned> UnrollCount(
103 "unroll-count", cl::Hidden,
104 cl::desc("Use this unroll count for all loops including those with "
105 "unroll_count pragma values, for testing purposes"));
Dan Gohmand78c4002008-05-13 00:00:25 +0000106
Dehao Chend55bc4c2016-05-05 00:54:54 +0000107static cl::opt<unsigned> UnrollMaxCount(
108 "unroll-max-count", cl::Hidden,
109 cl::desc("Set the max unroll count for partial and runtime unrolling, for"
110 "testing purposes"));
Fiona Glaser045afc42016-04-06 16:57:25 +0000111
Dehao Chend55bc4c2016-05-05 00:54:54 +0000112static cl::opt<unsigned> UnrollFullMaxCount(
113 "unroll-full-max-count", cl::Hidden,
114 cl::desc(
115 "Set the max unroll count for full unrolling, for testing purposes"));
Fiona Glaser045afc42016-04-06 16:57:25 +0000116
Davide Italiano9a09ae42017-08-28 19:50:55 +0000117static cl::opt<unsigned> UnrollPeelCount(
118 "unroll-peel-count", cl::Hidden,
119 cl::desc("Set the unroll peeling count, for testing purposes"));
120
Matthijs Kooijman98b5c162008-07-29 13:21:23 +0000121static cl::opt<bool>
Dehao Chend55bc4c2016-05-05 00:54:54 +0000122 UnrollAllowPartial("unroll-allow-partial", cl::Hidden,
123 cl::desc("Allows loops to be partially unrolled until "
124 "-unroll-threshold loop size is reached."));
Matthijs Kooijman98b5c162008-07-29 13:21:23 +0000125
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000126static cl::opt<bool> UnrollAllowRemainder(
127 "unroll-allow-remainder", cl::Hidden,
128 cl::desc("Allow generation of a loop remainder (extra iterations) "
129 "when unrolling a loop."));
130
Andrew Trickd04d15292011-12-09 06:19:40 +0000131static cl::opt<bool>
Dehao Chend55bc4c2016-05-05 00:54:54 +0000132 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::Hidden,
133 cl::desc("Unroll loops with run-time trip counts"));
Andrew Trickd04d15292011-12-09 06:19:40 +0000134
Haicheng Wu1ef17e92016-10-12 21:29:38 +0000135static cl::opt<unsigned> UnrollMaxUpperBound(
136 "unroll-max-upperbound", cl::init(8), cl::Hidden,
137 cl::desc(
138 "The max of trip count upper bound that is considered in unrolling"));
139
Dehao Chend55bc4c2016-05-05 00:54:54 +0000140static cl::opt<unsigned> PragmaUnrollThreshold(
141 "pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
142 cl::desc("Unrolled size limit for loops with an unroll(full) or "
143 "unroll_count pragma."));
Justin Bognera1dd4932016-01-12 00:55:26 +0000144
Dehao Chen41d72a82016-11-17 01:17:02 +0000145static cl::opt<unsigned> FlatLoopTripCountThreshold(
146 "flat-loop-tripcount-threshold", cl::init(5), cl::Hidden,
147 cl::desc("If the runtime tripcount for the loop is lower than the "
148 "threshold, the loop is considered as flat and will be less "
149 "aggressively unrolled."));
150
Michael Kupersteinb151a642016-11-30 21:13:57 +0000151static cl::opt<bool>
Michael Kupersteinc2af82b2017-02-22 00:27:34 +0000152 UnrollAllowPeeling("unroll-allow-peeling", cl::init(true), cl::Hidden,
Michael Kupersteinb151a642016-11-30 21:13:57 +0000153 cl::desc("Allows loops to be peeled when the dynamic "
154 "trip count is known to be low."));
155
Sam Parker718c8a62017-08-14 09:25:26 +0000156static cl::opt<bool> UnrollUnrollRemainder(
157 "unroll-remainder", cl::Hidden,
158 cl::desc("Allow the loop remainder to be unrolled."));
159
Chandler Carruthce40fa12017-01-25 02:49:01 +0000160// This option isn't ever intended to be enabled, it serves to allow
161// experiments to check the assumptions about when this kind of revisit is
162// necessary.
163static cl::opt<bool> UnrollRevisitChildLoops(
164 "unroll-revisit-child-loops", cl::Hidden,
165 cl::desc("Enqueue and re-visit child loops in the loop PM after unrolling. "
166 "This shouldn't typically be needed as child loops (or their "
167 "clones) were already visited."));
168
Justin Bognera1dd4932016-01-12 00:55:26 +0000169/// A magic value for use with the Threshold parameter to indicate
170/// that the loop unroll should be performed regardless of how much
171/// code expansion would result.
Eugene Zelenko306d2992017-10-18 21:46:47 +0000172static const unsigned NoThreshold = std::numeric_limits<unsigned>::max();
Justin Bognera1dd4932016-01-12 00:55:26 +0000173
Justin Bognera1dd4932016-01-12 00:55:26 +0000174/// Gather the various unrolling parameters based on the defaults, compiler
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000175/// flags, TTI overrides and user specified parameters.
David Green963401d2018-07-01 12:47:30 +0000176TargetTransformInfo::UnrollingPreferences llvm::gatherUnrollingPreferences(
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000177 Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI,
178 BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, int OptLevel,
Dehao Chen7d230322017-02-18 03:46:51 +0000179 Optional<unsigned> UserThreshold, Optional<unsigned> UserCount,
180 Optional<bool> UserAllowPartial, Optional<bool> UserRuntime,
Serguei Katkovde67aff2019-08-02 09:32:52 +0000181 Optional<bool> UserUpperBound, Optional<bool> UserAllowPeeling,
Serguei Katkova4476882019-09-19 06:57:29 +0000182 Optional<bool> UserAllowProfileBasedPeeling,
183 Optional<unsigned> UserFullUnrollMaxCount) {
Justin Bognera1dd4932016-01-12 00:55:26 +0000184 TargetTransformInfo::UnrollingPreferences UP;
185
186 // Set up the defaults
Dehao Chen7d230322017-02-18 03:46:51 +0000187 UP.Threshold = OptLevel > 2 ? 300 : 150;
Dehao Chencc763442016-12-30 00:50:28 +0000188 UP.MaxPercentThresholdBoost = 400;
Hans Wennborg719b26b2016-05-10 21:45:55 +0000189 UP.OptSizeThreshold = 0;
Dehao Chenc3f87f02017-01-17 23:39:33 +0000190 UP.PartialThreshold = 150;
Hans Wennborg719b26b2016-05-10 21:45:55 +0000191 UP.PartialOptSizeThreshold = 0;
Justin Bognera1dd4932016-01-12 00:55:26 +0000192 UP.Count = 0;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000193 UP.PeelCount = 0;
Jonas Paulsson58c5a7f2016-09-28 09:41:38 +0000194 UP.DefaultUnrollRuntimeCount = 8;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000195 UP.MaxCount = std::numeric_limits<unsigned>::max();
196 UP.FullUnrollMaxCount = std::numeric_limits<unsigned>::max();
Evgeny Stupachenkoc2698cd2016-11-09 19:56:39 +0000197 UP.BEInsns = 2;
Justin Bognera1dd4932016-01-12 00:55:26 +0000198 UP.Partial = false;
199 UP.Runtime = false;
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000200 UP.AllowRemainder = true;
Sam Parker718c8a62017-08-14 09:25:26 +0000201 UP.UnrollRemainder = false;
Justin Bognera1dd4932016-01-12 00:55:26 +0000202 UP.AllowExpensiveTripCount = false;
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000203 UP.Force = false;
Haicheng Wu1ef17e92016-10-12 21:29:38 +0000204 UP.UpperBound = false;
Michael Kupersteinc2af82b2017-02-22 00:27:34 +0000205 UP.AllowPeeling = true;
David Green963401d2018-07-01 12:47:30 +0000206 UP.UnrollAndJam = false;
Serguei Katkovbbdcc822019-08-02 04:29:23 +0000207 UP.PeelProfiledIterations = true;
David Green963401d2018-07-01 12:47:30 +0000208 UP.UnrollAndJamInnerLoopThreshold = 60;
Justin Bognera1dd4932016-01-12 00:55:26 +0000209
210 // Override with any target specific settings
Geoff Berry66d9bdb2017-06-28 15:53:17 +0000211 TTI.getUnrollingPreferences(L, SE, UP);
Justin Bognera1dd4932016-01-12 00:55:26 +0000212
213 // Apply size attributes
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000214 bool OptForSize = L->getHeader()->getParent()->hasOptSize() ||
215 llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI);
216 if (OptForSize) {
Justin Bognera1dd4932016-01-12 00:55:26 +0000217 UP.Threshold = UP.OptSizeThreshold;
218 UP.PartialThreshold = UP.PartialOptSizeThreshold;
Florian Hahn893aea52019-04-17 15:57:43 +0000219 UP.MaxPercentThresholdBoost = 100;
Justin Bognera1dd4932016-01-12 00:55:26 +0000220 }
221
Justin Bognera1dd4932016-01-12 00:55:26 +0000222 // Apply any user values specified by cl::opt
Dehao Chenc3f87f02017-01-17 23:39:33 +0000223 if (UnrollThreshold.getNumOccurrences() > 0)
Justin Bognera1dd4932016-01-12 00:55:26 +0000224 UP.Threshold = UnrollThreshold;
Dehao Chenc3f87f02017-01-17 23:39:33 +0000225 if (UnrollPartialThreshold.getNumOccurrences() > 0)
226 UP.PartialThreshold = UnrollPartialThreshold;
Dehao Chencc763442016-12-30 00:50:28 +0000227 if (UnrollMaxPercentThresholdBoost.getNumOccurrences() > 0)
228 UP.MaxPercentThresholdBoost = UnrollMaxPercentThresholdBoost;
Fiona Glaser045afc42016-04-06 16:57:25 +0000229 if (UnrollMaxCount.getNumOccurrences() > 0)
230 UP.MaxCount = UnrollMaxCount;
231 if (UnrollFullMaxCount.getNumOccurrences() > 0)
232 UP.FullUnrollMaxCount = UnrollFullMaxCount;
Davide Italiano9a09ae42017-08-28 19:50:55 +0000233 if (UnrollPeelCount.getNumOccurrences() > 0)
234 UP.PeelCount = UnrollPeelCount;
Justin Bognera1dd4932016-01-12 00:55:26 +0000235 if (UnrollAllowPartial.getNumOccurrences() > 0)
236 UP.Partial = UnrollAllowPartial;
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000237 if (UnrollAllowRemainder.getNumOccurrences() > 0)
238 UP.AllowRemainder = UnrollAllowRemainder;
Justin Bognera1dd4932016-01-12 00:55:26 +0000239 if (UnrollRuntime.getNumOccurrences() > 0)
240 UP.Runtime = UnrollRuntime;
Haicheng Wu1ef17e92016-10-12 21:29:38 +0000241 if (UnrollMaxUpperBound == 0)
242 UP.UpperBound = false;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000243 if (UnrollAllowPeeling.getNumOccurrences() > 0)
244 UP.AllowPeeling = UnrollAllowPeeling;
Sam Parker718c8a62017-08-14 09:25:26 +0000245 if (UnrollUnrollRemainder.getNumOccurrences() > 0)
246 UP.UnrollRemainder = UnrollUnrollRemainder;
Justin Bognera1dd4932016-01-12 00:55:26 +0000247
248 // Apply user values provided by argument
249 if (UserThreshold.hasValue()) {
250 UP.Threshold = *UserThreshold;
251 UP.PartialThreshold = *UserThreshold;
252 }
253 if (UserCount.hasValue())
254 UP.Count = *UserCount;
255 if (UserAllowPartial.hasValue())
256 UP.Partial = *UserAllowPartial;
257 if (UserRuntime.hasValue())
258 UP.Runtime = *UserRuntime;
Haicheng Wu1ef17e92016-10-12 21:29:38 +0000259 if (UserUpperBound.hasValue())
260 UP.UpperBound = *UserUpperBound;
Teresa Johnson9a18a6f2017-08-03 17:52:38 +0000261 if (UserAllowPeeling.hasValue())
262 UP.AllowPeeling = *UserAllowPeeling;
Serguei Katkovde67aff2019-08-02 09:32:52 +0000263 if (UserAllowProfileBasedPeeling.hasValue())
264 UP.PeelProfiledIterations = *UserAllowProfileBasedPeeling;
Serguei Katkova4476882019-09-19 06:57:29 +0000265 if (UserFullUnrollMaxCount.hasValue())
266 UP.FullUnrollMaxCount = *UserFullUnrollMaxCount;
Justin Bognera1dd4932016-01-12 00:55:26 +0000267
Justin Bognera1dd4932016-01-12 00:55:26 +0000268 return UP;
269}
270
Chris Lattner79a42ac2006-12-19 21:40:18 +0000271namespace {
Eugene Zelenko306d2992017-10-18 21:46:47 +0000272
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000273/// A struct to densely store the state of an instruction after unrolling at
274/// each iteration.
275///
276/// This is designed to work like a tuple of <Instruction *, int> for the
277/// purposes of hashing and lookup, but to be able to associate two boolean
278/// states with each key.
279struct UnrolledInstState {
280 Instruction *I;
281 int Iteration : 30;
282 unsigned IsFree : 1;
283 unsigned IsCounted : 1;
284};
285
286/// Hashing and equality testing for a set of the instruction states.
287struct UnrolledInstStateKeyInfo {
Eugene Zelenko306d2992017-10-18 21:46:47 +0000288 using PtrInfo = DenseMapInfo<Instruction *>;
289 using PairInfo = DenseMapInfo<std::pair<Instruction *, int>>;
290
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000291 static inline UnrolledInstState getEmptyKey() {
292 return {PtrInfo::getEmptyKey(), 0, 0, 0};
293 }
Eugene Zelenko306d2992017-10-18 21:46:47 +0000294
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000295 static inline UnrolledInstState getTombstoneKey() {
296 return {PtrInfo::getTombstoneKey(), 0, 0, 0};
297 }
Eugene Zelenko306d2992017-10-18 21:46:47 +0000298
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000299 static inline unsigned getHashValue(const UnrolledInstState &S) {
300 return PairInfo::getHashValue({S.I, S.Iteration});
301 }
Eugene Zelenko306d2992017-10-18 21:46:47 +0000302
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000303 static inline bool isEqual(const UnrolledInstState &LHS,
304 const UnrolledInstState &RHS) {
305 return PairInfo::isEqual({LHS.I, LHS.Iteration}, {RHS.I, RHS.Iteration});
306 }
307};
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000308
Chandler Carruth02156082015-05-22 17:41:35 +0000309struct EstimatedUnrollCost {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000310 /// The estimated cost after unrolling.
Dehao Chenc3be2252016-12-02 03:17:07 +0000311 unsigned UnrolledCost;
Chandler Carruth302a1332015-02-13 02:10:56 +0000312
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000313 /// The estimated dynamic cost of executing the instructions in the
Chandler Carruth9dabd142015-06-05 17:01:43 +0000314 /// rolled form.
Dehao Chenc3be2252016-12-02 03:17:07 +0000315 unsigned RolledDynamicCost;
Chandler Carruth02156082015-05-22 17:41:35 +0000316};
Eugene Zelenko306d2992017-10-18 21:46:47 +0000317
318} // end anonymous namespace
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000319
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000320/// Figure out if the loop is worth full unrolling.
Chandler Carruth02156082015-05-22 17:41:35 +0000321///
322/// Complete loop unrolling can make some loads constant, and we need to know
323/// if that would expose any further optimization opportunities. This routine
Michael Zolotukhinc4e4f332015-06-11 22:17:39 +0000324/// estimates this optimization. It computes cost of unrolled loop
325/// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By
326/// dynamic cost we mean that we won't count costs of blocks that are known not
327/// to be executed (i.e. if we have a branch in the loop and we know that at the
328/// given iteration its condition would be resolved to true, we won't add up the
329/// cost of the 'false'-block).
330/// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If
331/// the analysis failed (no benefits expected from the unrolling, or the loop is
332/// too big to analyze), the returned value is None.
Andrei Elovikovf9b80352018-03-15 09:59:15 +0000333static Optional<EstimatedUnrollCost> analyzeLoopUnrollCost(
334 const Loop *L, unsigned TripCount, DominatorTree &DT, ScalarEvolution &SE,
335 const SmallPtrSetImpl<const Value *> &EphValues,
336 const TargetTransformInfo &TTI, unsigned MaxUnrolledLoopSize) {
Chandler Carruth02156082015-05-22 17:41:35 +0000337 // We want to be able to scale offsets by the trip count and add more offsets
338 // to them without checking for overflows, and we already don't want to
339 // analyze *massive* trip counts, so we force the max to be reasonably small.
Eugene Zelenko306d2992017-10-18 21:46:47 +0000340 assert(UnrollMaxIterationsCountToAnalyze <
Simon Pilgrim0444e4f2017-10-19 15:00:31 +0000341 (unsigned)(std::numeric_limits<int>::max() / 2) &&
Chandler Carruth02156082015-05-22 17:41:35 +0000342 "The unroll iterations max is too large!");
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000343
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000344 // Only analyze inner loops. We can't properly estimate cost of nested loops
345 // and we won't visit inner loops again anyway.
346 if (!L->empty())
347 return None;
348
Chandler Carruth02156082015-05-22 17:41:35 +0000349 // Don't simulate loops with a big or unknown tripcount
350 if (!UnrollMaxIterationsCountToAnalyze || !TripCount ||
351 TripCount > UnrollMaxIterationsCountToAnalyze)
352 return None;
Chandler Carrutha6ae8772015-05-12 23:32:56 +0000353
Chandler Carruth02156082015-05-22 17:41:35 +0000354 SmallSetVector<BasicBlock *, 16> BBWorklist;
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000355 SmallSetVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitWorklist;
Chandler Carruth02156082015-05-22 17:41:35 +0000356 DenseMap<Value *, Constant *> SimplifiedValues;
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000357 SmallVector<std::pair<Value *, Constant *>, 4> SimplifiedInputValues;
Chandler Carruth3b057b32015-02-13 03:57:40 +0000358
Chandler Carruth9dabd142015-06-05 17:01:43 +0000359 // The estimated cost of the unrolled form of the loop. We try to estimate
360 // this by simplifying as much as we can while computing the estimate.
Dehao Chenc3be2252016-12-02 03:17:07 +0000361 unsigned UnrolledCost = 0;
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000362
Chandler Carruth9dabd142015-06-05 17:01:43 +0000363 // We also track the estimated dynamic (that is, actually executed) cost in
364 // the rolled form. This helps identify cases when the savings from unrolling
365 // aren't just exposing dead control flows, but actual reduced dynamic
366 // instructions due to the simplifications which we expect to occur after
367 // unrolling.
Dehao Chenc3be2252016-12-02 03:17:07 +0000368 unsigned RolledDynamicCost = 0;
Chandler Carruth8c863752015-02-13 03:48:38 +0000369
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000370 // We track the simplification of each instruction in each iteration. We use
371 // this to recursively merge costs into the unrolled cost on-demand so that
372 // we don't count the cost of any dead code. This is essentially a map from
373 // <instruction, int> to <bool, bool>, but stored as a densely packed struct.
374 DenseSet<UnrolledInstState, UnrolledInstStateKeyInfo> InstCostMap;
375
376 // A small worklist used to accumulate cost of instructions from each
377 // observable and reached root in the loop.
378 SmallVector<Instruction *, 16> CostWorklist;
379
380 // PHI-used worklist used between iterations while accumulating cost.
381 SmallVector<Instruction *, 4> PHIUsedList;
382
383 // Helper function to accumulate cost for instructions in the loop.
384 auto AddCostRecursively = [&](Instruction &RootI, int Iteration) {
385 assert(Iteration >= 0 && "Cannot have a negative iteration!");
386 assert(CostWorklist.empty() && "Must start with an empty cost list");
387 assert(PHIUsedList.empty() && "Must start with an empty phi used list");
388 CostWorklist.push_back(&RootI);
389 for (;; --Iteration) {
390 do {
391 Instruction *I = CostWorklist.pop_back_val();
392
393 // InstCostMap only uses I and Iteration as a key, the other two values
394 // don't matter here.
395 auto CostIter = InstCostMap.find({I, Iteration, 0, 0});
396 if (CostIter == InstCostMap.end())
397 // If an input to a PHI node comes from a dead path through the loop
398 // we may have no cost data for it here. What that actually means is
399 // that it is free.
400 continue;
401 auto &Cost = *CostIter;
402 if (Cost.IsCounted)
403 // Already counted this instruction.
404 continue;
405
406 // Mark that we are counting the cost of this instruction now.
407 Cost.IsCounted = true;
408
409 // If this is a PHI node in the loop header, just add it to the PHI set.
410 if (auto *PhiI = dyn_cast<PHINode>(I))
411 if (PhiI->getParent() == L->getHeader()) {
412 assert(Cost.IsFree && "Loop PHIs shouldn't be evaluated as they "
413 "inherently simplify during unrolling.");
414 if (Iteration == 0)
415 continue;
416
417 // Push the incoming value from the backedge into the PHI used list
418 // if it is an in-loop instruction. We'll use this to populate the
419 // cost worklist for the next iteration (as we count backwards).
420 if (auto *OpI = dyn_cast<Instruction>(
421 PhiI->getIncomingValueForBlock(L->getLoopLatch())))
422 if (L->contains(OpI))
423 PHIUsedList.push_back(OpI);
424 continue;
425 }
426
427 // First accumulate the cost of this instruction.
428 if (!Cost.IsFree) {
429 UnrolledCost += TTI.getUserCost(I);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000430 LLVM_DEBUG(dbgs() << "Adding cost of instruction (iteration "
431 << Iteration << "): ");
432 LLVM_DEBUG(I->dump());
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000433 }
434
435 // We must count the cost of every operand which is not free,
436 // recursively. If we reach a loop PHI node, simply add it to the set
437 // to be considered on the next iteration (backwards!).
438 for (Value *Op : I->operands()) {
439 // Check whether this operand is free due to being a constant or
440 // outside the loop.
441 auto *OpI = dyn_cast<Instruction>(Op);
442 if (!OpI || !L->contains(OpI))
443 continue;
444
445 // Otherwise accumulate its cost.
446 CostWorklist.push_back(OpI);
447 }
448 } while (!CostWorklist.empty());
449
450 if (PHIUsedList.empty())
451 // We've exhausted the search.
452 break;
453
454 assert(Iteration > 0 &&
455 "Cannot track PHI-used values past the first iteration!");
456 CostWorklist.append(PHIUsedList.begin(), PHIUsedList.end());
457 PHIUsedList.clear();
458 }
459 };
460
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000461 // Ensure that we don't violate the loop structure invariants relied on by
462 // this analysis.
463 assert(L->isLoopSimplifyForm() && "Must put loop into normal form first.");
464 assert(L->isLCSSAForm(DT) &&
465 "Must have loops in LCSSA form to track live-out values.");
466
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000467 LLVM_DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n");
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000468
Chandler Carruth02156082015-05-22 17:41:35 +0000469 // Simulate execution of each iteration of the loop counting instructions,
470 // which would be simplified.
471 // Since the same load will take different values on different iterations,
472 // we literally have to go through all loop's iterations.
473 for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000474 LLVM_DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n");
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000475
476 // Prepare for the iteration by collecting any simplified entry or backedge
477 // inputs.
478 for (Instruction &I : *L->getHeader()) {
479 auto *PHI = dyn_cast<PHINode>(&I);
480 if (!PHI)
481 break;
482
483 // The loop header PHI nodes must have exactly two input: one from the
484 // loop preheader and one from the loop latch.
485 assert(
486 PHI->getNumIncomingValues() == 2 &&
487 "Must have an incoming value only for the preheader and the latch.");
488
489 Value *V = PHI->getIncomingValueForBlock(
490 Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch());
491 Constant *C = dyn_cast<Constant>(V);
492 if (Iteration != 0 && !C)
493 C = SimplifiedValues.lookup(V);
494 if (C)
495 SimplifiedInputValues.push_back({PHI, C});
496 }
497
498 // Now clear and re-populate the map for the next iteration.
Chandler Carruth02156082015-05-22 17:41:35 +0000499 SimplifiedValues.clear();
Chandler Carruth87adb7a2015-08-03 20:32:27 +0000500 while (!SimplifiedInputValues.empty())
501 SimplifiedValues.insert(SimplifiedInputValues.pop_back_val());
502
Michael Zolotukhin9f520eb2016-02-26 02:57:05 +0000503 UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SE, L);
Chandler Carruthf174a152015-05-22 02:47:29 +0000504
Chandler Carruth02156082015-05-22 17:41:35 +0000505 BBWorklist.clear();
506 BBWorklist.insert(L->getHeader());
507 // Note that we *must not* cache the size, this loop grows the worklist.
508 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
509 BasicBlock *BB = BBWorklist[Idx];
Chandler Carruthf174a152015-05-22 02:47:29 +0000510
Chandler Carruth02156082015-05-22 17:41:35 +0000511 // Visit all instructions in the given basic block and try to simplify
512 // it. We don't change the actual IR, just count optimization
513 // opportunities.
514 for (Instruction &I : *BB) {
Andrei Elovikovf9b80352018-03-15 09:59:15 +0000515 // These won't get into the final code - don't even try calculating the
516 // cost for them.
517 if (isa<DbgInfoIntrinsic>(I) || EphValues.count(&I))
Dehao Chen977853b2016-09-30 18:30:04 +0000518 continue;
519
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000520 // Track this instruction's expected baseline cost when executing the
521 // rolled loop form.
522 RolledDynamicCost += TTI.getUserCost(&I);
Chandler Carruth17a04962015-02-13 03:49:41 +0000523
Chandler Carruth02156082015-05-22 17:41:35 +0000524 // Visit the instruction to analyze its loop cost after unrolling,
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000525 // and if the visitor returns true, mark the instruction as free after
526 // unrolling and continue.
527 bool IsFree = Analyzer.visit(I);
528 bool Inserted = InstCostMap.insert({&I, (int)Iteration,
529 (unsigned)IsFree,
530 /*IsCounted*/ false}).second;
531 (void)Inserted;
532 assert(Inserted && "Cannot have a state for an unvisited instruction!");
Chandler Carruth9dabd142015-06-05 17:01:43 +0000533
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000534 if (IsFree)
535 continue;
536
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000537 // Can't properly model a cost of a call.
538 // FIXME: With a proper cost model we should be able to do it.
Matt Arsenault2c1a5702018-06-26 18:51:17 +0000539 if (auto *CI = dyn_cast<CallInst>(&I)) {
540 const Function *Callee = CI->getCalledFunction();
541 if (!Callee || TTI.isLoweredToCall(Callee)) {
542 LLVM_DEBUG(dbgs() << "Can't analyze cost of loop with call\n");
543 return None;
544 }
545 }
Chandler Carruth02156082015-05-22 17:41:35 +0000546
Haicheng Wue7877632016-08-17 22:42:58 +0000547 // If the instruction might have a side-effect recursively account for
548 // the cost of it and all the instructions leading up to it.
549 if (I.mayHaveSideEffects())
550 AddCostRecursively(I, Iteration);
551
Chandler Carruth02156082015-05-22 17:41:35 +0000552 // If unrolled body turns out to be too big, bail out.
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000553 if (UnrolledCost > MaxUnrolledLoopSize) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000554 LLVM_DEBUG(dbgs() << " Exceeded threshold.. exiting.\n"
555 << " UnrolledCost: " << UnrolledCost
556 << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize
557 << "\n");
Chandler Carruth02156082015-05-22 17:41:35 +0000558 return None;
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000559 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000560 }
Chandler Carruth415f4122015-02-13 02:17:39 +0000561
Chandler Carruthedb12a82018-10-15 10:04:59 +0000562 Instruction *TI = BB->getTerminator();
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000563
564 // Add in the live successors by first checking whether we have terminator
565 // that may be simplified based on the values simplified by this call.
Michael Zolotukhin1ecdeda2016-05-26 21:42:51 +0000566 BasicBlock *KnownSucc = nullptr;
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000567 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
568 if (BI->isConditional()) {
569 if (Constant *SimpleCond =
570 SimplifiedValues.lookup(BI->getCondition())) {
Michael Zolotukhin3a7d55b2015-07-29 18:10:29 +0000571 // Just take the first successor if condition is undef
572 if (isa<UndefValue>(SimpleCond))
Michael Zolotukhin1ecdeda2016-05-26 21:42:51 +0000573 KnownSucc = BI->getSuccessor(0);
574 else if (ConstantInt *SimpleCondVal =
575 dyn_cast<ConstantInt>(SimpleCond))
576 KnownSucc = BI->getSuccessor(SimpleCondVal->isZero() ? 1 : 0);
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000577 }
578 }
579 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
580 if (Constant *SimpleCond =
581 SimplifiedValues.lookup(SI->getCondition())) {
Michael Zolotukhin3a7d55b2015-07-29 18:10:29 +0000582 // Just take the first successor if condition is undef
583 if (isa<UndefValue>(SimpleCond))
Michael Zolotukhin1ecdeda2016-05-26 21:42:51 +0000584 KnownSucc = SI->getSuccessor(0);
585 else if (ConstantInt *SimpleCondVal =
586 dyn_cast<ConstantInt>(SimpleCond))
Chandler Carruth927d8e62017-04-12 07:27:28 +0000587 KnownSucc = SI->findCaseValue(SimpleCondVal)->getCaseSuccessor();
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000588 }
589 }
Michael Zolotukhin1ecdeda2016-05-26 21:42:51 +0000590 if (KnownSucc) {
591 if (L->contains(KnownSucc))
592 BBWorklist.insert(KnownSucc);
593 else
594 ExitWorklist.insert({BB, KnownSucc});
595 continue;
596 }
Michael Zolotukhin57776b82015-07-24 01:53:04 +0000597
Chandler Carruth02156082015-05-22 17:41:35 +0000598 // Add BB's successors to the worklist.
599 for (BasicBlock *Succ : successors(BB))
600 if (L->contains(Succ))
601 BBWorklist.insert(Succ);
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000602 else
603 ExitWorklist.insert({BB, Succ});
Michael Zolotukhind2268a72016-05-18 21:20:12 +0000604 AddCostRecursively(*TI, Iteration);
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000605 }
Chandler Carruth02156082015-05-22 17:41:35 +0000606
607 // If we found no optimization opportunities on the first iteration, we
608 // won't find them on later ones too.
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000609 if (UnrolledCost == RolledDynamicCost) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000610 LLVM_DEBUG(dbgs() << " No opportunities found.. exiting.\n"
611 << " UnrolledCost: " << UnrolledCost << "\n");
Chandler Carruth02156082015-05-22 17:41:35 +0000612 return None;
Michael Zolotukhin80d13ba2015-07-28 20:07:29 +0000613 }
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000614 }
Michael Zolotukhin963a6d92016-05-13 21:23:25 +0000615
616 while (!ExitWorklist.empty()) {
617 BasicBlock *ExitingBB, *ExitBB;
618 std::tie(ExitingBB, ExitBB) = ExitWorklist.pop_back_val();
619
620 for (Instruction &I : *ExitBB) {
621 auto *PN = dyn_cast<PHINode>(&I);
622 if (!PN)
623 break;
624
625 Value *Op = PN->getIncomingValueForBlock(ExitingBB);
626 if (auto *OpI = dyn_cast<Instruction>(Op))
627 if (L->contains(OpI))
628 AddCostRecursively(*OpI, TripCount - 1);
629 }
630 }
631
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000632 LLVM_DEBUG(dbgs() << "Analysis finished:\n"
633 << "UnrolledCost: " << UnrolledCost << ", "
634 << "RolledDynamicCost: " << RolledDynamicCost << "\n");
Chandler Carruth9dabd142015-06-05 17:01:43 +0000635 return {{UnrolledCost, RolledDynamicCost}};
Chandler Carruth02156082015-05-22 17:41:35 +0000636}
Michael Zolotukhina9aadd22015-02-05 02:34:00 +0000637
Dan Gohman49d08a52007-05-08 15:14:19 +0000638/// ApproximateLoopSize - Approximate the size of the loop.
David Green963401d2018-07-01 12:47:30 +0000639unsigned llvm::ApproximateLoopSize(
640 const Loop *L, unsigned &NumCalls, bool &NotDuplicatable, bool &Convergent,
641 const TargetTransformInfo &TTI,
642 const SmallPtrSetImpl<const Value *> &EphValues, unsigned BEInsns) {
Dan Gohman969e83a2009-10-31 14:54:17 +0000643 CodeMetrics Metrics;
Sanjay Patel5c967232016-03-08 19:06:12 +0000644 for (BasicBlock *BB : L->blocks())
645 Metrics.analyzeBasicBlock(BB, TTI, EphValues);
Owen Anderson04cf3fd2010-09-09 20:32:23 +0000646 NumCalls = Metrics.NumInlineCandidates;
James Molloy4f6fb952012-12-20 16:04:27 +0000647 NotDuplicatable = Metrics.notDuplicatable;
Justin Lebar6827de12016-03-14 23:15:34 +0000648 Convergent = Metrics.convergent;
Andrew Trick279e7a62011-07-23 00:29:16 +0000649
Owen Anderson62ea1b72010-09-09 19:07:31 +0000650 unsigned LoopSize = Metrics.NumInsts;
Andrew Trick279e7a62011-07-23 00:29:16 +0000651
Owen Anderson62ea1b72010-09-09 19:07:31 +0000652 // Don't allow an estimate of size zero. This would allows unrolling of loops
653 // with huge iteration counts, which is a compile time problem even if it's
Hal Finkel38dd5902015-01-10 00:30:55 +0000654 // not a problem for code quality. Also, the code using this size may assume
655 // that each loop has at least three instructions (likely a conditional
656 // branch, a comparison feeding that branch, and some kind of loop increment
657 // feeding that comparison instruction).
Evgeny Stupachenkoc2698cd2016-11-09 19:56:39 +0000658 LoopSize = std::max(LoopSize, BEInsns + 1);
Andrew Trick279e7a62011-07-23 00:29:16 +0000659
Owen Anderson62ea1b72010-09-09 19:07:31 +0000660 return LoopSize;
Chris Lattner946b2552004-04-18 05:20:17 +0000661}
662
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000663// Returns the loop hint metadata node with the given name (for example,
664// "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
665// returned.
Jingyue Wu49a766e2015-02-02 20:41:11 +0000666static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
667 if (MDNode *LoopID = L->getLoopID())
668 return GetUnrollMetadata(LoopID, Name);
669 return nullptr;
Eli Benderskyff903242014-06-16 23:53:02 +0000670}
671
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000672// Returns true if the loop has an unroll(full) pragma.
673static bool HasUnrollFullPragma(const Loop *L) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000674 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
Eli Benderskyff903242014-06-16 23:53:02 +0000675}
676
Mark Heffernan89391542015-08-10 17:28:08 +0000677// Returns true if the loop has an unroll(enable) pragma. This metadata is used
678// for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives.
679static bool HasUnrollEnablePragma(const Loop *L) {
680 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.enable");
681}
682
Kevin Qin715b01e2015-03-09 06:14:18 +0000683// Returns true if the loop has an runtime unroll(disable) pragma.
684static bool HasRuntimeUnrollDisablePragma(const Loop *L) {
685 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
686}
687
Eli Benderskyff903242014-06-16 23:53:02 +0000688// If loop has an unroll_count pragma return the (necessarily
689// positive) value from the pragma. Otherwise return 0.
690static unsigned UnrollCountPragmaValue(const Loop *L) {
Jingyue Wu49a766e2015-02-02 20:41:11 +0000691 MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
Mark Heffernane6b4ba12014-07-23 17:31:37 +0000692 if (MD) {
693 assert(MD->getNumOperands() == 2 &&
694 "Unroll count hint metadata should have two operands.");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000695 unsigned Count =
696 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
Eli Benderskyff903242014-06-16 23:53:02 +0000697 assert(Count >= 1 && "Unroll count must be positive.");
698 return Count;
699 }
700 return 0;
701}
702
Dehao Chencc763442016-12-30 00:50:28 +0000703// Computes the boosting factor for complete unrolling.
704// If fully unrolling the loop would save a lot of RolledDynamicCost, it would
705// be beneficial to fully unroll the loop even if unrolledcost is large. We
706// use (RolledDynamicCost / UnrolledCost) to model the unroll benefits to adjust
707// the unroll threshold.
708static unsigned getFullUnrollBoostingFactor(const EstimatedUnrollCost &Cost,
709 unsigned MaxPercentThresholdBoost) {
Eugene Zelenko306d2992017-10-18 21:46:47 +0000710 if (Cost.RolledDynamicCost >= std::numeric_limits<unsigned>::max() / 100)
Dehao Chencc763442016-12-30 00:50:28 +0000711 return 100;
712 else if (Cost.UnrolledCost != 0)
713 // The boosting factor is RolledDynamicCost / UnrolledCost
714 return std::min(100 * Cost.RolledDynamicCost / Cost.UnrolledCost,
715 MaxPercentThresholdBoost);
716 else
717 return MaxPercentThresholdBoost;
Michael Zolotukhin8c681712015-05-12 17:20:03 +0000718}
719
Evgeny Stupachenkoc2698cd2016-11-09 19:56:39 +0000720// Returns loop size estimation for unrolled loop.
721static uint64_t getUnrolledLoopSize(
722 unsigned LoopSize,
723 TargetTransformInfo::UnrollingPreferences &UP) {
724 assert(LoopSize >= UP.BEInsns && "LoopSize should not be less than BEInsns!");
725 return (uint64_t)(LoopSize - UP.BEInsns) * UP.Count + UP.BEInsns;
726}
727
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000728// Returns true if unroll count was set explicitly.
729// Calculates unroll count and writes it to UP.Count.
Michael Kruse72448522018-12-12 17:32:52 +0000730// Unless IgnoreUser is true, will also use metadata and command-line options
731// that are specific to to the LoopUnroll pass (which, for instance, are
732// irrelevant for the LoopUnrollAndJam pass).
733// FIXME: This function is used by LoopUnroll and LoopUnrollAndJam, but consumes
734// many LoopUnroll-specific options. The shared functionality should be
735// refactored into it own function.
David Green963401d2018-07-01 12:47:30 +0000736bool llvm::computeUnrollCount(
Haicheng Wu1ef17e92016-10-12 21:29:38 +0000737 Loop *L, const TargetTransformInfo &TTI, DominatorTree &DT, LoopInfo *LI,
Andrei Elovikovf9b80352018-03-15 09:59:15 +0000738 ScalarEvolution &SE, const SmallPtrSetImpl<const Value *> &EphValues,
739 OptimizationRemarkEmitter *ORE, unsigned &TripCount, unsigned MaxTripCount,
Zhaoshi Zheng1128fa02019-09-26 21:40:27 +0000740 bool MaxOrZero, unsigned &TripMultiple, unsigned LoopSize,
Haicheng Wu1ef17e92016-10-12 21:29:38 +0000741 TargetTransformInfo::UnrollingPreferences &UP, bool &UseUpperBound) {
Michael Kruse72448522018-12-12 17:32:52 +0000742
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000743 // Check for explicit Count.
744 // 1st priority is unroll count set by "unroll-count" option.
745 bool UserUnrollCount = UnrollCount.getNumOccurrences() > 0;
746 if (UserUnrollCount) {
747 UP.Count = UnrollCount;
748 UP.AllowExpensiveTripCount = true;
749 UP.Force = true;
Evgeny Stupachenkoc2698cd2016-11-09 19:56:39 +0000750 if (UP.AllowRemainder && getUnrolledLoopSize(LoopSize, UP) < UP.Threshold)
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000751 return true;
752 }
753
754 // 2nd priority is unroll count set by pragma.
755 unsigned PragmaCount = UnrollCountPragmaValue(L);
756 if (PragmaCount > 0) {
757 UP.Count = PragmaCount;
758 UP.Runtime = true;
759 UP.AllowExpensiveTripCount = true;
760 UP.Force = true;
Yaxun Liu3c42f1c2018-03-02 16:22:32 +0000761 if ((UP.AllowRemainder || (TripMultiple % PragmaCount == 0)) &&
Evgeny Stupachenkoc2698cd2016-11-09 19:56:39 +0000762 getUnrolledLoopSize(LoopSize, UP) < PragmaUnrollThreshold)
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000763 return true;
764 }
765 bool PragmaFullUnroll = HasUnrollFullPragma(L);
766 if (PragmaFullUnroll && TripCount != 0) {
767 UP.Count = TripCount;
Evgeny Stupachenkoc2698cd2016-11-09 19:56:39 +0000768 if (getUnrolledLoopSize(LoopSize, UP) < PragmaUnrollThreshold)
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000769 return false;
770 }
771
772 bool PragmaEnableUnroll = HasUnrollEnablePragma(L);
773 bool ExplicitUnroll = PragmaCount > 0 || PragmaFullUnroll ||
774 PragmaEnableUnroll || UserUnrollCount;
775
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000776 if (ExplicitUnroll && TripCount != 0) {
777 // If the loop has an unrolling pragma, we want to be more aggressive with
David Green963401d2018-07-01 12:47:30 +0000778 // unrolling limits. Set thresholds to at least the PragmaUnrollThreshold
779 // value which is larger than the default limits.
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000780 UP.Threshold = std::max<unsigned>(UP.Threshold, PragmaUnrollThreshold);
781 UP.PartialThreshold =
782 std::max<unsigned>(UP.PartialThreshold, PragmaUnrollThreshold);
783 }
784
785 // 3rd priority is full unroll count.
Haicheng Wu1ef17e92016-10-12 21:29:38 +0000786 // Full unroll makes sense only when TripCount or its upper bound could be
787 // statically calculated.
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000788 // Also we need to check if we exceed FullUnrollMaxCount.
Haicheng Wu1ef17e92016-10-12 21:29:38 +0000789 // If using the upper bound to unroll, TripMultiple should be set to 1 because
790 // we do not know when loop may exit.
Zhaoshi Zheng1128fa02019-09-26 21:40:27 +0000791
792 // We can unroll by the upper bound amount if it's generally allowed or if
793 // we know that the loop is executed either the upper bound or zero times.
794 // (MaxOrZero unrolling keeps only the first loop test, so the number of
795 // loop tests remains the same compared to the non-unrolled version, whereas
796 // the generic upper bound unrolling keeps all but the last loop test so the
797 // number of loop tests goes up which may end up being worse on targets with
798 // constrained branch predictor resources so is controlled by an option.)
799 // In addition we only unroll small upper bounds.
800 unsigned FullUnrollMaxTripCount = MaxTripCount;
801 if (!(UP.UpperBound || MaxOrZero) ||
802 FullUnrollMaxTripCount > UnrollMaxUpperBound)
803 FullUnrollMaxTripCount = 0;
804
805 // UnrollByMaxCount and ExactTripCount cannot both be non zero since we only
Haicheng Wu1ef17e92016-10-12 21:29:38 +0000806 // compute the former when the latter is zero.
807 unsigned ExactTripCount = TripCount;
Zhaoshi Zheng1128fa02019-09-26 21:40:27 +0000808 assert((ExactTripCount == 0 || FullUnrollMaxTripCount == 0) &&
809 "ExtractTripCount and UnrollByMaxCount cannot both be non zero.");
810
811 unsigned FullUnrollTripCount =
812 ExactTripCount ? ExactTripCount : FullUnrollMaxTripCount;
Evgeny Stupachenkoc2698cd2016-11-09 19:56:39 +0000813 UP.Count = FullUnrollTripCount;
Haicheng Wu1ef17e92016-10-12 21:29:38 +0000814 if (FullUnrollTripCount && FullUnrollTripCount <= UP.FullUnrollMaxCount) {
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000815 // When computing the unrolled size, note that BEInsns are not replicated
816 // like the rest of the loop body.
Dehao Chencc763442016-12-30 00:50:28 +0000817 if (getUnrolledLoopSize(LoopSize, UP) < UP.Threshold) {
Zhaoshi Zheng1128fa02019-09-26 21:40:27 +0000818 UseUpperBound = (FullUnrollMaxTripCount == FullUnrollTripCount);
Haicheng Wu1ef17e92016-10-12 21:29:38 +0000819 TripCount = FullUnrollTripCount;
820 TripMultiple = UP.UpperBound ? 1 : TripMultiple;
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000821 return ExplicitUnroll;
822 } else {
823 // The loop isn't that small, but we still can fully unroll it if that
824 // helps to remove a significant number of instructions.
825 // To check that, run additional analysis on the loop.
826 if (Optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost(
Andrei Elovikovf9b80352018-03-15 09:59:15 +0000827 L, FullUnrollTripCount, DT, SE, EphValues, TTI,
Dehao Chencc763442016-12-30 00:50:28 +0000828 UP.Threshold * UP.MaxPercentThresholdBoost / 100)) {
829 unsigned Boost =
830 getFullUnrollBoostingFactor(*Cost, UP.MaxPercentThresholdBoost);
831 if (Cost->UnrolledCost < UP.Threshold * Boost / 100) {
Zhaoshi Zheng1128fa02019-09-26 21:40:27 +0000832 UseUpperBound = (FullUnrollMaxTripCount == FullUnrollTripCount);
Haicheng Wu1ef17e92016-10-12 21:29:38 +0000833 TripCount = FullUnrollTripCount;
834 TripMultiple = UP.UpperBound ? 1 : TripMultiple;
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000835 return ExplicitUnroll;
836 }
Dehao Chencc763442016-12-30 00:50:28 +0000837 }
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000838 }
839 }
840
Neil Henningd2261f612018-10-05 09:39:07 +0000841 // 4th priority is loop peeling.
Florian Hahnfc97b612018-03-15 21:34:43 +0000842 computePeelCount(L, LoopSize, UP, TripCount, SE);
Sanjoy Daseed71b92017-03-03 18:19:10 +0000843 if (UP.PeelCount) {
844 UP.Runtime = false;
845 UP.Count = 1;
846 return ExplicitUnroll;
847 }
848
849 // 5th priority is partial unrolling.
Hiroshi Inouef2096492018-06-14 05:41:49 +0000850 // Try partial unroll only when TripCount could be statically calculated.
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000851 if (TripCount) {
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000852 UP.Partial |= ExplicitUnroll;
853 if (!UP.Partial) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000854 LLVM_DEBUG(dbgs() << " will not try to unroll partially because "
855 << "-unroll-allow-partial not given\n");
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000856 UP.Count = 0;
857 return false;
858 }
Haicheng Wu430b3e42016-10-27 18:40:02 +0000859 if (UP.Count == 0)
860 UP.Count = TripCount;
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000861 if (UP.PartialThreshold != NoThreshold) {
862 // Reduce unroll count to be modulo of TripCount for partial unrolling.
Evgeny Stupachenkoc2698cd2016-11-09 19:56:39 +0000863 if (getUnrolledLoopSize(LoopSize, UP) > UP.PartialThreshold)
864 UP.Count =
865 (std::max(UP.PartialThreshold, UP.BEInsns + 1) - UP.BEInsns) /
866 (LoopSize - UP.BEInsns);
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000867 if (UP.Count > UP.MaxCount)
868 UP.Count = UP.MaxCount;
869 while (UP.Count != 0 && TripCount % UP.Count != 0)
870 UP.Count--;
871 if (UP.AllowRemainder && UP.Count <= 1) {
872 // If there is no Count that is modulo of TripCount, set Count to
873 // largest power-of-two factor that satisfies the threshold limit.
874 // As we'll create fixup loop, do the type of unrolling only if
875 // remainder loop is allowed.
Jonas Paulsson58c5a7f2016-09-28 09:41:38 +0000876 UP.Count = UP.DefaultUnrollRuntimeCount;
Evgeny Stupachenkoc2698cd2016-11-09 19:56:39 +0000877 while (UP.Count != 0 &&
878 getUnrolledLoopSize(LoopSize, UP) > UP.PartialThreshold)
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000879 UP.Count >>= 1;
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000880 }
881 if (UP.Count < 2) {
882 if (PragmaEnableUnroll)
Vivek Pandya95906582017-10-11 17:12:59 +0000883 ORE->emit([&]() {
884 return OptimizationRemarkMissed(DEBUG_TYPE,
885 "UnrollAsDirectedTooLarge",
886 L->getStartLoc(), L->getHeader())
887 << "Unable to unroll loop as directed by unroll(enable) "
888 "pragma "
889 "because unrolled size is too large.";
890 });
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000891 UP.Count = 0;
892 }
893 } else {
894 UP.Count = TripCount;
895 }
Geoff Berryb0573542017-06-28 17:01:15 +0000896 if (UP.Count > UP.MaxCount)
897 UP.Count = UP.MaxCount;
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000898 if ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount &&
899 UP.Count != TripCount)
Vivek Pandya95906582017-10-11 17:12:59 +0000900 ORE->emit([&]() {
901 return OptimizationRemarkMissed(DEBUG_TYPE,
902 "FullUnrollAsDirectedTooLarge",
903 L->getStartLoc(), L->getHeader())
904 << "Unable to fully unroll loop as directed by unroll pragma "
905 "because "
906 "unrolled size is too large.";
907 });
Zhaoshi Zheng1128fa02019-09-26 21:40:27 +0000908 LLVM_DEBUG(dbgs() << " partially unrolling with count: " << UP.Count
909 << "\n");
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000910 return ExplicitUnroll;
911 }
912 assert(TripCount == 0 &&
913 "All cases when TripCount is constant should be covered here.");
914 if (PragmaFullUnroll)
Vivek Pandya95906582017-10-11 17:12:59 +0000915 ORE->emit([&]() {
916 return OptimizationRemarkMissed(
917 DEBUG_TYPE, "CantFullUnrollAsDirectedRuntimeTripCount",
918 L->getStartLoc(), L->getHeader())
919 << "Unable to fully unroll loop as directed by unroll(full) "
920 "pragma "
921 "because loop has a runtime trip count.";
922 });
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000923
Michael Kupersteinb151a642016-11-30 21:13:57 +0000924 // 6th priority is runtime unrolling.
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000925 // Don't unroll a runtime trip count loop when it is disabled.
926 if (HasRuntimeUnrollDisablePragma(L)) {
927 UP.Count = 0;
928 return false;
929 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000930
Zhaoshi Zheng1128fa02019-09-26 21:40:27 +0000931 // Don't unroll a small upper bound loop unless user or TTI asked to do so.
932 if (MaxTripCount && !UP.Force && MaxTripCount < UnrollMaxUpperBound) {
933 UP.Count = 0;
934 return false;
935 }
936
Michael Kupersteinb151a642016-11-30 21:13:57 +0000937 // Check if the runtime trip count is too small when profile is available.
Easwaran Ramana17f2202017-12-22 01:33:52 +0000938 if (L->getHeader()->getParent()->hasProfileData()) {
Michael Kupersteinb151a642016-11-30 21:13:57 +0000939 if (auto ProfileTripCount = getLoopEstimatedTripCount(L)) {
940 if (*ProfileTripCount < FlatLoopTripCountThreshold)
941 return false;
942 else
943 UP.AllowExpensiveTripCount = true;
944 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000945 }
Michael Kupersteinb151a642016-11-30 21:13:57 +0000946
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000947 // Reduce count based on the type of unrolling and the threshold values.
948 UP.Runtime |= PragmaEnableUnroll || PragmaCount > 0 || UserUnrollCount;
949 if (!UP.Runtime) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000950 LLVM_DEBUG(
951 dbgs() << " will not try to unroll loop with runtime trip count "
952 << "-unroll-runtime not given\n");
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000953 UP.Count = 0;
954 return false;
955 }
956 if (UP.Count == 0)
Jonas Paulsson58c5a7f2016-09-28 09:41:38 +0000957 UP.Count = UP.DefaultUnrollRuntimeCount;
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000958
959 // Reduce unroll count to be the largest power-of-two factor of
960 // the original count which satisfies the threshold limit.
Evgeny Stupachenkoc2698cd2016-11-09 19:56:39 +0000961 while (UP.Count != 0 &&
962 getUnrolledLoopSize(LoopSize, UP) > UP.PartialThreshold)
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000963 UP.Count >>= 1;
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000964
Evgeny Stupachenkob7875222016-05-28 00:14:58 +0000965#ifndef NDEBUG
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000966 unsigned OrigCount = UP.Count;
Evgeny Stupachenkob7875222016-05-28 00:14:58 +0000967#endif
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000968
969 if (!UP.AllowRemainder && UP.Count != 0 && (TripMultiple % UP.Count) != 0) {
970 while (UP.Count != 0 && TripMultiple % UP.Count != 0)
971 UP.Count >>= 1;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000972 LLVM_DEBUG(
973 dbgs() << "Remainder loop is restricted (that could architecture "
974 "specific or because the loop contains a convergent "
975 "instruction), so unroll count must divide the trip "
976 "multiple, "
977 << TripMultiple << ". Reducing unroll count from " << OrigCount
978 << " to " << UP.Count << ".\n");
Eugene Zelenko306d2992017-10-18 21:46:47 +0000979
Adam Nemetf57cc622016-09-30 03:44:16 +0000980 using namespace ore;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000981
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000982 if (PragmaCount > 0 && !UP.AllowRemainder)
Vivek Pandya95906582017-10-11 17:12:59 +0000983 ORE->emit([&]() {
984 return OptimizationRemarkMissed(DEBUG_TYPE,
985 "DifferentUnrollCountFromDirected",
986 L->getStartLoc(), L->getHeader())
987 << "Unable to unroll loop the number of times directed by "
988 "unroll_count pragma because remainder loop is restricted "
989 "(that could architecture specific or because the loop "
990 "contains a convergent instruction) and so must have an "
991 "unroll "
992 "count that divides the loop trip multiple of "
993 << NV("TripMultiple", TripMultiple) << ". Unrolling instead "
994 << NV("UnrollCount", UP.Count) << " time(s).";
995 });
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +0000996 }
997
998 if (UP.Count > UP.MaxCount)
999 UP.Count = UP.MaxCount;
Zhaoshi Zheng1128fa02019-09-26 21:40:27 +00001000
1001 if (MaxTripCount && UP.Count > MaxTripCount)
1002 UP.Count = MaxTripCount;
1003
1004 LLVM_DEBUG(dbgs() << " runtime unrolling with count: " << UP.Count
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001005 << "\n");
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +00001006 if (UP.Count < 2)
1007 UP.Count = 0;
1008 return ExplicitUnroll;
1009}
1010
Sanjoy Das4f3ebd52017-09-27 21:45:22 +00001011static LoopUnrollResult tryToUnrollLoop(
Teresa Johnson9a18a6f2017-08-03 17:52:38 +00001012 Loop *L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution &SE,
1013 const TargetTransformInfo &TTI, AssumptionCache &AC,
Serguei Katkovde67aff2019-08-02 09:32:52 +00001014 OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI,
1015 ProfileSummaryInfo *PSI, bool PreserveLCSSA, int OptLevel,
Alina Sbirlea2312a062019-04-12 19:16:07 +00001016 bool OnlyWhenForced, bool ForgetAllSCEV, Optional<unsigned> ProvidedCount,
Michael Kruse32847752018-12-18 17:16:05 +00001017 Optional<unsigned> ProvidedThreshold, Optional<bool> ProvidedAllowPartial,
1018 Optional<bool> ProvidedRuntime, Optional<bool> ProvidedUpperBound,
Serguei Katkovde67aff2019-08-02 09:32:52 +00001019 Optional<bool> ProvidedAllowPeeling,
Serguei Katkova4476882019-09-19 06:57:29 +00001020 Optional<bool> ProvidedAllowProfileBasedPeeling,
1021 Optional<unsigned> ProvidedFullUnrollMaxCount) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001022 LLVM_DEBUG(dbgs() << "Loop Unroll: F["
1023 << L->getHeader()->getParent()->getName() << "] Loop %"
1024 << L->getHeader()->getName() << "\n");
Michael Kruse32847752018-12-18 17:16:05 +00001025 TransformationMode TM = hasUnrollTransformation(L);
1026 if (TM & TM_Disable)
Sanjoy Das4f3ebd52017-09-27 21:45:22 +00001027 return LoopUnrollResult::Unmodified;
Eugene Zelenko306d2992017-10-18 21:46:47 +00001028 if (!L->isLoopSimplifyForm()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001029 LLVM_DEBUG(
Haicheng Wu731b04c2016-11-23 19:39:26 +00001030 dbgs() << " Not unrolling loop which is not in loop-simplify form.\n");
Sanjoy Das4f3ebd52017-09-27 21:45:22 +00001031 return LoopUnrollResult::Unmodified;
Eli Benderskyff903242014-06-16 23:53:02 +00001032 }
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +00001033
Michael Kruse32847752018-12-18 17:16:05 +00001034 // When automtatic unrolling is disabled, do not unroll unless overridden for
1035 // this loop.
1036 if (OnlyWhenForced && !(TM & TM_Enable))
1037 return LoopUnrollResult::Unmodified;
1038
Florian Hahn893aea52019-04-17 15:57:43 +00001039 bool OptForSize = L->getHeader()->getParent()->hasOptSize();
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +00001040 unsigned NumInlineCandidates;
1041 bool NotDuplicatable;
1042 bool Convergent;
Evgeny Stupachenkoc2698cd2016-11-09 19:56:39 +00001043 TargetTransformInfo::UnrollingPreferences UP = gatherUnrollingPreferences(
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001044 L, SE, TTI, BFI, PSI, OptLevel, ProvidedThreshold, ProvidedCount,
Teresa Johnson9a18a6f2017-08-03 17:52:38 +00001045 ProvidedAllowPartial, ProvidedRuntime, ProvidedUpperBound,
Serguei Katkova4476882019-09-19 06:57:29 +00001046 ProvidedAllowPeeling, ProvidedAllowProfileBasedPeeling,
1047 ProvidedFullUnrollMaxCount);
Florian Hahn893aea52019-04-17 15:57:43 +00001048
1049 // Exit early if unrolling is disabled. For OptForSize, we pick the loop size
1050 // as threshold later on.
1051 if (UP.Threshold == 0 && (!UP.Partial || UP.PartialThreshold == 0) &&
1052 !OptForSize)
Sanjoy Das4f3ebd52017-09-27 21:45:22 +00001053 return LoopUnrollResult::Unmodified;
Andrei Elovikovf9b80352018-03-15 09:59:15 +00001054
1055 SmallPtrSet<const Value *, 32> EphValues;
1056 CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
1057
1058 unsigned LoopSize =
1059 ApproximateLoopSize(L, NumInlineCandidates, NotDuplicatable, Convergent,
1060 TTI, EphValues, UP.BEInsns);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001061 LLVM_DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +00001062 if (NotDuplicatable) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001063 LLVM_DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
1064 << " instructions.\n");
Sanjoy Das4f3ebd52017-09-27 21:45:22 +00001065 return LoopUnrollResult::Unmodified;
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +00001066 }
Florian Hahn893aea52019-04-17 15:57:43 +00001067
Florian Hahn1bd58872019-09-17 09:02:48 +00001068 // When optimizing for size, use LoopSize + 1 as threshold (we use < Threshold
1069 // later), to (fully) unroll loops, if it does not increase code size.
Florian Hahn893aea52019-04-17 15:57:43 +00001070 if (OptForSize)
Florian Hahn1bd58872019-09-17 09:02:48 +00001071 UP.Threshold = std::max(UP.Threshold, LoopSize + 1);
Florian Hahn893aea52019-04-17 15:57:43 +00001072
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +00001073 if (NumInlineCandidates != 0) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001074 LLVM_DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
Sanjoy Das4f3ebd52017-09-27 21:45:22 +00001075 return LoopUnrollResult::Unmodified;
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +00001076 }
Andrew Trick279e7a62011-07-23 00:29:16 +00001077
Andrew Trick2b6860f2011-08-11 23:36:16 +00001078 // Find trip count and trip multiple if count is not available
1079 unsigned TripCount = 0;
Andrew Trick1cabe542011-07-23 00:33:05 +00001080 unsigned TripMultiple = 1;
Chandler Carruth6666c272014-10-11 00:12:11 +00001081 // If there are multiple exiting blocks but one of them is the latch, use the
1082 // latch for the trip count estimation. Otherwise insist on a single exiting
1083 // block for the trip count estimation.
1084 BasicBlock *ExitingBlock = L->getLoopLatch();
1085 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
1086 ExitingBlock = L->getExitingBlock();
1087 if (ExitingBlock) {
Geoff Berry66d9bdb2017-06-28 15:53:17 +00001088 TripCount = SE.getSmallConstantTripCount(L, ExitingBlock);
1089 TripMultiple = SE.getSmallConstantTripMultiple(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +00001090 }
Hal Finkel8f2e7002013-09-11 19:25:43 +00001091
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +00001092 // If the loop contains a convergent operation, the prelude we'd add
1093 // to do the first few instructions before we hit the unrolled loop
1094 // is unsafe -- it adds a control-flow dependency to the convergent
1095 // operation. Therefore restrict remainder loop (try unrollig without).
1096 //
1097 // TODO: This is quite conservative. In practice, convergent_op()
1098 // is likely to be called unconditionally in the loop. In this
1099 // case, the program would be ill-formed (on most architectures)
1100 // unless n were the same on all threads in a thread group.
1101 // Assuming n is the same on all threads, any kind of unrolling is
1102 // safe. But currently llvm's notion of convergence isn't powerful
1103 // enough to express this.
1104 if (Convergent)
1105 UP.AllowRemainder = false;
Eli Benderskydc6de2c2014-06-12 18:05:39 +00001106
John Brawn84b21832016-10-21 11:08:48 +00001107 // Try to find the trip count upper bound if we cannot find the exact trip
1108 // count.
Zhaoshi Zheng1128fa02019-09-26 21:40:27 +00001109 unsigned MaxTripCount = 0;
John Brawn84b21832016-10-21 11:08:48 +00001110 bool MaxOrZero = false;
1111 if (!TripCount) {
Geoff Berry66d9bdb2017-06-28 15:53:17 +00001112 MaxTripCount = SE.getSmallConstantMaxTripCount(L);
1113 MaxOrZero = SE.isBackedgeTakenCountMaxOrZero(L);
Haicheng Wu1ef17e92016-10-12 21:29:38 +00001114 }
1115
1116 // computeUnrollCount() decides whether it is beneficial to use upper bound to
1117 // fully unroll the loop.
1118 bool UseUpperBound = false;
Andrei Elovikovf9b80352018-03-15 09:59:15 +00001119 bool IsCountSetExplicitly = computeUnrollCount(
Zhaoshi Zheng1128fa02019-09-26 21:40:27 +00001120 L, TTI, DT, LI, SE, EphValues, &ORE, TripCount, MaxTripCount, MaxOrZero,
Andrei Elovikovf9b80352018-03-15 09:59:15 +00001121 TripMultiple, LoopSize, UP, UseUpperBound);
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +00001122 if (!UP.Count)
Sanjoy Das4f3ebd52017-09-27 21:45:22 +00001123 return LoopUnrollResult::Unmodified;
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +00001124 // Unroll factor (Count) must be less or equal to TripCount.
1125 if (TripCount && UP.Count > TripCount)
1126 UP.Count = TripCount;
Dan Gohman2980d9d2007-05-11 20:53:41 +00001127
Michael Kruse72448522018-12-12 17:32:52 +00001128 // Save loop properties before it is transformed.
1129 MDNode *OrigLoopID = L->getLoopID();
1130
Dan Gohman3dc2d922008-05-14 00:24:14 +00001131 // Unroll the loop.
Michael Kruse72448522018-12-12 17:32:52 +00001132 Loop *RemainderLoop = nullptr;
Sanjoy Das4f3ebd52017-09-27 21:45:22 +00001133 LoopUnrollResult UnrollResult = UnrollLoop(
Alina Sbirleada0f71a2019-04-18 23:43:49 +00001134 L,
1135 {UP.Count, TripCount, UP.Force, UP.Runtime, UP.AllowExpensiveTripCount,
1136 UseUpperBound, MaxOrZero, TripMultiple, UP.PeelCount, UP.UnrollRemainder,
1137 ForgetAllSCEV},
1138 LI, &SE, &DT, &AC, &ORE, PreserveLCSSA, &RemainderLoop);
Sanjoy Das4f3ebd52017-09-27 21:45:22 +00001139 if (UnrollResult == LoopUnrollResult::Unmodified)
1140 return LoopUnrollResult::Unmodified;
Dan Gohman2980d9d2007-05-11 20:53:41 +00001141
Michael Kruse72448522018-12-12 17:32:52 +00001142 if (RemainderLoop) {
1143 Optional<MDNode *> RemainderLoopID =
1144 makeFollowupLoopID(OrigLoopID, {LLVMLoopUnrollFollowupAll,
1145 LLVMLoopUnrollFollowupRemainder});
1146 if (RemainderLoopID.hasValue())
1147 RemainderLoop->setLoopID(RemainderLoopID.getValue());
1148 }
1149
1150 if (UnrollResult != LoopUnrollResult::FullyUnrolled) {
1151 Optional<MDNode *> NewLoopID =
1152 makeFollowupLoopID(OrigLoopID, {LLVMLoopUnrollFollowupAll,
1153 LLVMLoopUnrollFollowupUnrolled});
1154 if (NewLoopID.hasValue()) {
1155 L->setLoopID(NewLoopID.getValue());
1156
1157 // Do not setLoopAlreadyUnrolled if loop attributes have been specified
1158 // explicitly.
1159 return UnrollResult;
1160 }
1161 }
1162
Evgeny Stupachenkoea2aef42016-05-27 23:15:06 +00001163 // If loop has an unroll count pragma or unrolled by explicitly set count
1164 // mark loop as unrolled to prevent unrolling beyond that requested.
Michael Kupersteinb151a642016-11-30 21:13:57 +00001165 // If the loop was peeled, we already "used up" the profile information
1166 // we had, so we don't want to unroll or peel again.
Sanjoy Das4f3ebd52017-09-27 21:45:22 +00001167 if (UnrollResult != LoopUnrollResult::FullyUnrolled &&
Serguei Katkovbbdcc822019-08-02 04:29:23 +00001168 (IsCountSetExplicitly || (UP.PeelProfiledIterations && UP.PeelCount)))
Hongbin Zheng73f65042017-10-15 07:31:02 +00001169 L->setLoopAlreadyUnrolled();
Michael Kupersteinb151a642016-11-30 21:13:57 +00001170
Sanjoy Das4f3ebd52017-09-27 21:45:22 +00001171 return UnrollResult;
Chris Lattner946b2552004-04-18 05:20:17 +00001172}
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001173
1174namespace {
Eugene Zelenko306d2992017-10-18 21:46:47 +00001175
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001176class LoopUnroll : public LoopPass {
1177public:
1178 static char ID; // Pass ID, replacement for typeid
Eugene Zelenko306d2992017-10-18 21:46:47 +00001179
1180 int OptLevel;
Michael Kruse32847752018-12-18 17:16:05 +00001181
1182 /// If false, use a cost model to determine whether unrolling of a loop is
1183 /// profitable. If true, only loops that explicitly request unrolling via
1184 /// metadata are considered. All other loops are skipped.
1185 bool OnlyWhenForced;
1186
Alina Sbirlea2312a062019-04-12 19:16:07 +00001187 /// If false, when SCEV is invalidated, only forget everything in the
1188 /// top-most loop (call forgetTopMostLoop), of the loop being processed.
1189 /// Otherwise, forgetAllLoops and rebuild when needed next.
1190 bool ForgetAllSCEV;
1191
Eugene Zelenko306d2992017-10-18 21:46:47 +00001192 Optional<unsigned> ProvidedCount;
1193 Optional<unsigned> ProvidedThreshold;
1194 Optional<bool> ProvidedAllowPartial;
1195 Optional<bool> ProvidedRuntime;
1196 Optional<bool> ProvidedUpperBound;
1197 Optional<bool> ProvidedAllowPeeling;
Serguei Katkovde67aff2019-08-02 09:32:52 +00001198 Optional<bool> ProvidedAllowProfileBasedPeeling;
Serguei Katkova4476882019-09-19 06:57:29 +00001199 Optional<unsigned> ProvidedFullUnrollMaxCount;
Eugene Zelenko306d2992017-10-18 21:46:47 +00001200
Michael Kruse32847752018-12-18 17:16:05 +00001201 LoopUnroll(int OptLevel = 2, bool OnlyWhenForced = false,
Alina Sbirlea2312a062019-04-12 19:16:07 +00001202 bool ForgetAllSCEV = false, Optional<unsigned> Threshold = None,
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001203 Optional<unsigned> Count = None,
Haicheng Wu1ef17e92016-10-12 21:29:38 +00001204 Optional<bool> AllowPartial = None, Optional<bool> Runtime = None,
Teresa Johnson9a18a6f2017-08-03 17:52:38 +00001205 Optional<bool> UpperBound = None,
Serguei Katkovde67aff2019-08-02 09:32:52 +00001206 Optional<bool> AllowPeeling = None,
Serguei Katkova4476882019-09-19 06:57:29 +00001207 Optional<bool> AllowProfileBasedPeeling = None,
1208 Optional<unsigned> ProvidedFullUnrollMaxCount = None)
Michael Kruse32847752018-12-18 17:16:05 +00001209 : LoopPass(ID), OptLevel(OptLevel), OnlyWhenForced(OnlyWhenForced),
Alina Sbirlea2312a062019-04-12 19:16:07 +00001210 ForgetAllSCEV(ForgetAllSCEV), ProvidedCount(std::move(Count)),
1211 ProvidedThreshold(Threshold), ProvidedAllowPartial(AllowPartial),
1212 ProvidedRuntime(Runtime), ProvidedUpperBound(UpperBound),
Serguei Katkovde67aff2019-08-02 09:32:52 +00001213 ProvidedAllowPeeling(AllowPeeling),
Serguei Katkova4476882019-09-19 06:57:29 +00001214 ProvidedAllowProfileBasedPeeling(AllowProfileBasedPeeling),
1215 ProvidedFullUnrollMaxCount(ProvidedFullUnrollMaxCount) {
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001216 initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
1217 }
1218
Sanjoy Dasdef17292017-09-28 02:45:42 +00001219 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001220 if (skipLoop(L))
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001221 return false;
1222
1223 Function &F = *L->getHeader()->getParent();
1224
1225 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1226 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Geoff Berry66d9bdb2017-06-28 15:53:17 +00001227 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001228 const TargetTransformInfo &TTI =
1229 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001230 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Adam Nemet4f155b62016-08-26 15:58:34 +00001231 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
1232 // pass. Function analyses need to be preserved across loop transformations
1233 // but ORE cannot be preserved (see comment before the pass definition).
1234 OptimizationRemarkEmitter ORE(&F);
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001235 bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
1236
Sanjoy Dasdef17292017-09-28 02:45:42 +00001237 LoopUnrollResult Result = tryToUnrollLoop(
Serguei Katkovde67aff2019-08-02 09:32:52 +00001238 L, DT, LI, SE, TTI, AC, ORE, nullptr, nullptr, PreserveLCSSA, OptLevel,
1239 OnlyWhenForced, ForgetAllSCEV, ProvidedCount, ProvidedThreshold,
1240 ProvidedAllowPartial, ProvidedRuntime, ProvidedUpperBound,
Serguei Katkova4476882019-09-19 06:57:29 +00001241 ProvidedAllowPeeling, ProvidedAllowProfileBasedPeeling,
1242 ProvidedFullUnrollMaxCount);
Sanjoy Dasdef17292017-09-28 02:45:42 +00001243
1244 if (Result == LoopUnrollResult::FullyUnrolled)
1245 LPM.markLoopAsDeleted(*L);
1246
1247 return Result != LoopUnrollResult::Unmodified;
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001248 }
1249
1250 /// This transformation requires natural loop information & requires that
1251 /// loop preheaders be inserted into the CFG...
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001252 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001253 AU.addRequired<AssumptionCacheTracker>();
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001254 AU.addRequired<TargetTransformInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +00001255 // FIXME: Loop passes are required to preserve domtree, and for now we just
1256 // recreate dom info if anything gets unrolled.
1257 getLoopAnalysisUsage(AU);
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001258 }
1259};
Eugene Zelenko306d2992017-10-18 21:46:47 +00001260
1261} // end anonymous namespace
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001262
1263char LoopUnroll::ID = 0;
Eugene Zelenko306d2992017-10-18 21:46:47 +00001264
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001265INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001266INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth31088a92016-02-19 10:45:18 +00001267INITIALIZE_PASS_DEPENDENCY(LoopPass)
1268INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001269INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
1270
Michael Kruse32847752018-12-18 17:16:05 +00001271Pass *llvm::createLoopUnrollPass(int OptLevel, bool OnlyWhenForced,
Alina Sbirlea2312a062019-04-12 19:16:07 +00001272 bool ForgetAllSCEV, int Threshold, int Count,
1273 int AllowPartial, int Runtime, int UpperBound,
Teresa Johnson9a18a6f2017-08-03 17:52:38 +00001274 int AllowPeeling) {
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001275 // TODO: It would make more sense for this function to take the optionals
1276 // directly, but that's dangerous since it would silently break out of tree
1277 // callers.
Dehao Chen7d230322017-02-18 03:46:51 +00001278 return new LoopUnroll(
Alina Sbirlea2312a062019-04-12 19:16:07 +00001279 OptLevel, OnlyWhenForced, ForgetAllSCEV,
Michael Kruse32847752018-12-18 17:16:05 +00001280 Threshold == -1 ? None : Optional<unsigned>(Threshold),
Dehao Chen7d230322017-02-18 03:46:51 +00001281 Count == -1 ? None : Optional<unsigned>(Count),
1282 AllowPartial == -1 ? None : Optional<bool>(AllowPartial),
1283 Runtime == -1 ? None : Optional<bool>(Runtime),
Teresa Johnson9a18a6f2017-08-03 17:52:38 +00001284 UpperBound == -1 ? None : Optional<bool>(UpperBound),
1285 AllowPeeling == -1 ? None : Optional<bool>(AllowPeeling));
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001286}
1287
Alina Sbirlea2312a062019-04-12 19:16:07 +00001288Pass *llvm::createSimpleLoopUnrollPass(int OptLevel, bool OnlyWhenForced,
1289 bool ForgetAllSCEV) {
1290 return createLoopUnrollPass(OptLevel, OnlyWhenForced, ForgetAllSCEV, -1, -1,
1291 0, 0, 0, 0);
Justin Bognerb8d82ab2016-01-12 05:21:37 +00001292}
Sean Silvae3c18a52016-07-19 23:54:23 +00001293
Teresa Johnsonecd90132017-08-02 20:35:29 +00001294PreservedAnalyses LoopFullUnrollPass::run(Loop &L, LoopAnalysisManager &AM,
1295 LoopStandardAnalysisResults &AR,
1296 LPMUpdater &Updater) {
Sean Silvae3c18a52016-07-19 23:54:23 +00001297 const auto &FAM =
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001298 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
Sean Silvae3c18a52016-07-19 23:54:23 +00001299 Function *F = L.getHeader()->getParent();
1300
Adam Nemet12937c32016-07-29 19:29:47 +00001301 auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001302 // FIXME: This should probably be optional rather than required.
Adam Nemet12937c32016-07-29 19:29:47 +00001303 if (!ORE)
Teresa Johnsonecd90132017-08-02 20:35:29 +00001304 report_fatal_error(
1305 "LoopFullUnrollPass: OptimizationRemarkEmitterAnalysis not "
1306 "cached at a higher level");
Sean Silvae3c18a52016-07-19 23:54:23 +00001307
Chandler Carruthce40fa12017-01-25 02:49:01 +00001308 // Keep track of the previous loop structure so we can identify new loops
1309 // created by unrolling.
1310 Loop *ParentL = L.getParentLoop();
1311 SmallPtrSet<Loop *, 4> OldLoops;
1312 if (ParentL)
1313 OldLoops.insert(ParentL->begin(), ParentL->end());
1314 else
1315 OldLoops.insert(AR.LI.begin(), AR.LI.end());
1316
Sanjoy Dasdef17292017-09-28 02:45:42 +00001317 std::string LoopName = L.getName();
1318
Serguei Katkovde67aff2019-08-02 09:32:52 +00001319 bool Changed = tryToUnrollLoop(&L, AR.DT, &AR.LI, AR.SE, AR.TTI, AR.AC, *ORE,
1320 /*BFI*/ nullptr, /*PSI*/ nullptr,
1321 /*PreserveLCSSA*/ true, OptLevel,
1322 OnlyWhenForced, ForgetSCEV, /*Count*/ None,
1323 /*Threshold*/ None, /*AllowPartial*/ false,
1324 /*Runtime*/ false, /*UpperBound*/ false,
1325 /*AllowPeeling*/ false,
Serguei Katkova4476882019-09-19 06:57:29 +00001326 /*AllowProfileBasedPeeling*/ false,
1327 /*FullUnrollMaxCount*/ None) !=
Serguei Katkovde67aff2019-08-02 09:32:52 +00001328 LoopUnrollResult::Unmodified;
Sean Silvae3c18a52016-07-19 23:54:23 +00001329 if (!Changed)
1330 return PreservedAnalyses::all();
Chandler Carruthca68a3e2017-01-15 06:32:49 +00001331
Chandler Carruthce40fa12017-01-25 02:49:01 +00001332 // The parent must not be damaged by unrolling!
1333#ifndef NDEBUG
1334 if (ParentL)
1335 ParentL->verifyLoop();
1336#endif
1337
1338 // Unrolling can do several things to introduce new loops into a loop nest:
Chandler Carruthce40fa12017-01-25 02:49:01 +00001339 // - Full unrolling clones child loops within the current loop but then
1340 // removes the current loop making all of the children appear to be new
1341 // sibling loops.
Chandler Carruthce40fa12017-01-25 02:49:01 +00001342 //
Teresa Johnsonecd90132017-08-02 20:35:29 +00001343 // When a new loop appears as a sibling loop after fully unrolling,
1344 // its nesting structure has fundamentally changed and we want to revisit
1345 // it to reflect that.
Chandler Carruthce40fa12017-01-25 02:49:01 +00001346 //
1347 // When unrolling has removed the current loop, we need to tell the
1348 // infrastructure that it is gone.
1349 //
1350 // Finally, we support a debugging/testing mode where we revisit child loops
1351 // as well. These are not expected to require further optimizations as either
1352 // they or the loop they were cloned from have been directly visited already.
1353 // But the debugging mode allows us to check this assumption.
1354 bool IsCurrentLoopValid = false;
1355 SmallVector<Loop *, 4> SibLoops;
1356 if (ParentL)
1357 SibLoops.append(ParentL->begin(), ParentL->end());
1358 else
1359 SibLoops.append(AR.LI.begin(), AR.LI.end());
1360 erase_if(SibLoops, [&](Loop *SibLoop) {
1361 if (SibLoop == &L) {
1362 IsCurrentLoopValid = true;
1363 return true;
1364 }
1365
1366 // Otherwise erase the loop from the list if it was in the old loops.
1367 return OldLoops.count(SibLoop) != 0;
1368 });
1369 Updater.addSiblingLoops(SibLoops);
1370
1371 if (!IsCurrentLoopValid) {
Sanjoy Dasdef17292017-09-28 02:45:42 +00001372 Updater.markLoopAsDeleted(L, LoopName);
Chandler Carruthce40fa12017-01-25 02:49:01 +00001373 } else {
1374 // We can only walk child loops if the current loop remained valid.
1375 if (UnrollRevisitChildLoops) {
Teresa Johnsonecd90132017-08-02 20:35:29 +00001376 // Walk *all* of the child loops.
Chandler Carruthce40fa12017-01-25 02:49:01 +00001377 SmallVector<Loop *, 4> ChildLoops(L.begin(), L.end());
1378 Updater.addChildLoops(ChildLoops);
1379 }
1380 }
1381
Sean Silvae3c18a52016-07-19 23:54:23 +00001382 return getLoopPassPreservedAnalyses();
1383}
Teresa Johnsonecd90132017-08-02 20:35:29 +00001384
1385template <typename RangeT>
1386static SmallVector<Loop *, 8> appendLoopsToWorklist(RangeT &&Loops) {
1387 SmallVector<Loop *, 8> Worklist;
1388 // We use an internal worklist to build up the preorder traversal without
1389 // recursion.
1390 SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist;
1391
1392 for (Loop *RootL : Loops) {
1393 assert(PreOrderLoops.empty() && "Must start with an empty preorder walk.");
1394 assert(PreOrderWorklist.empty() &&
1395 "Must start with an empty preorder walk worklist.");
1396 PreOrderWorklist.push_back(RootL);
1397 do {
1398 Loop *L = PreOrderWorklist.pop_back_val();
1399 PreOrderWorklist.append(L->begin(), L->end());
1400 PreOrderLoops.push_back(L);
1401 } while (!PreOrderWorklist.empty());
1402
1403 Worklist.append(PreOrderLoops.begin(), PreOrderLoops.end());
1404 PreOrderLoops.clear();
1405 }
1406 return Worklist;
1407}
1408
1409PreservedAnalyses LoopUnrollPass::run(Function &F,
1410 FunctionAnalysisManager &AM) {
1411 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
1412 auto &LI = AM.getResult<LoopAnalysis>(F);
1413 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
1414 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1415 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1416 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1417
Chandler Carruth7c888dc2017-08-08 02:24:20 +00001418 LoopAnalysisManager *LAM = nullptr;
1419 if (auto *LAMProxy = AM.getCachedResult<LoopAnalysisManagerFunctionProxy>(F))
1420 LAM = &LAMProxy->getManager();
1421
Teresa Johnson8482e562017-08-03 23:42:58 +00001422 const ModuleAnalysisManager &MAM =
1423 AM.getResult<ModuleAnalysisManagerFunctionProxy>(F).getManager();
1424 ProfileSummaryInfo *PSI =
1425 MAM.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001426 auto *BFI = (PSI && PSI->hasProfileSummary()) ?
1427 &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;
Teresa Johnson8482e562017-08-03 23:42:58 +00001428
Teresa Johnsonecd90132017-08-02 20:35:29 +00001429 bool Changed = false;
1430
1431 // The unroller requires loops to be in simplified form, and also needs LCSSA.
1432 // Since simplification may add new inner loops, it has to run before the
1433 // legality and profitability checks. This means running the loop unroller
1434 // will simplify all loops, regardless of whether anything end up being
1435 // unrolled.
1436 for (auto &L : LI) {
Alina Sbirleaf31eba62019-05-08 17:05:36 +00001437 Changed |=
1438 simplifyLoop(L, &DT, &LI, &SE, &AC, nullptr, false /* PreserveLCSSA */);
Teresa Johnsonecd90132017-08-02 20:35:29 +00001439 Changed |= formLCSSARecursively(*L, DT, &LI, &SE);
1440 }
1441
1442 SmallVector<Loop *, 8> Worklist = appendLoopsToWorklist(LI);
1443
1444 while (!Worklist.empty()) {
1445 // Because the LoopInfo stores the loops in RPO, we walk the worklist
1446 // from back to front so that we work forward across the CFG, which
1447 // for unrolling is only needed to get optimization remarks emitted in
1448 // a forward order.
1449 Loop &L = *Worklist.pop_back_val();
Benjamin Kramerc965b302017-09-28 14:47:39 +00001450#ifndef NDEBUG
1451 Loop *ParentL = L.getParentLoop();
1452#endif
Teresa Johnsonecd90132017-08-02 20:35:29 +00001453
Teresa Johnson8482e562017-08-03 23:42:58 +00001454 // Check if the profile summary indicates that the profiled application
1455 // has a huge working set size, in which case we disable peeling to avoid
1456 // bloating it further.
Fedor Sergeev412ed342018-10-31 14:33:14 +00001457 Optional<bool> LocalAllowPeeling = UnrollOpts.AllowPeeling;
Teresa Johnson8482e562017-08-03 23:42:58 +00001458 if (PSI && PSI->hasHugeWorkingSetSize())
Fedor Sergeev412ed342018-10-31 14:33:14 +00001459 LocalAllowPeeling = false;
Sanjoy Dasdef17292017-09-28 02:45:42 +00001460 std::string LoopName = L.getName();
Fedor Sergeev412ed342018-10-31 14:33:14 +00001461 // The API here is quite complex to call and we allow to select some
1462 // flavors of unrolling during construction time (by setting UnrollOpts).
1463 LoopUnrollResult Result = tryToUnrollLoop(
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001464 &L, DT, &LI, SE, TTI, AC, ORE, BFI, PSI,
Michael Kruse32847752018-12-18 17:16:05 +00001465 /*PreserveLCSSA*/ true, UnrollOpts.OptLevel, UnrollOpts.OnlyWhenForced,
Alina Sbirlead82ddfa2019-05-23 21:52:59 +00001466 UnrollOpts.ForgetSCEV, /*Count*/ None,
Fedor Sergeev412ed342018-10-31 14:33:14 +00001467 /*Threshold*/ None, UnrollOpts.AllowPartial, UnrollOpts.AllowRuntime,
Serguei Katkovde67aff2019-08-02 09:32:52 +00001468 UnrollOpts.AllowUpperBound, LocalAllowPeeling,
Serguei Katkova4476882019-09-19 06:57:29 +00001469 UnrollOpts.AllowProfileBasedPeeling, UnrollOpts.FullUnrollMaxCount);
Sanjoy Das4f3ebd52017-09-27 21:45:22 +00001470 Changed |= Result != LoopUnrollResult::Unmodified;
Teresa Johnsonecd90132017-08-02 20:35:29 +00001471
1472 // The parent must not be damaged by unrolling!
1473#ifndef NDEBUG
Sanjoy Das4f3ebd52017-09-27 21:45:22 +00001474 if (Result != LoopUnrollResult::Unmodified && ParentL)
Teresa Johnsonecd90132017-08-02 20:35:29 +00001475 ParentL->verifyLoop();
1476#endif
Chandler Carruth7c888dc2017-08-08 02:24:20 +00001477
Sanjoy Das4f3ebd52017-09-27 21:45:22 +00001478 // Clear any cached analysis results for L if we removed it completely.
1479 if (LAM && Result == LoopUnrollResult::FullyUnrolled)
Sanjoy Dasdef17292017-09-28 02:45:42 +00001480 LAM->clear(L, LoopName);
Teresa Johnsonecd90132017-08-02 20:35:29 +00001481 }
1482
1483 if (!Changed)
1484 return PreservedAnalyses::all();
1485
1486 return getLoopPassPreservedAnalyses();
1487}