blob: 4ed3302b56350950cd7c7067c90917f24987f240 [file] [log] [blame]
Michael Kruse2133cb92016-06-28 01:37:20 +00001//===--------- ScopInfo.cpp ----------------------------------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser5624d3c2015-12-21 12:38:56 +000020#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000021#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000022#include "polly/Options.h"
Michael Kruse73fa33b2016-06-28 01:37:28 +000023#include "polly/ScopBuilder.h"
Tobias Grosser75805372011-04-29 06:27:02 +000024#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000025#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000026#include "polly/Support/ScopHelper.h"
Tobias Grosser9737c7b2015-11-22 11:06:51 +000027#include "llvm/ADT/DepthFirstIterator.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000028#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000029#include "llvm/ADT/PostOrderIterator.h"
30#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000031#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000032#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000033#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000034#include "llvm/Analysis/AliasAnalysis.h"
Michael Kruse89b1f942017-03-17 13:56:53 +000035#include "llvm/Analysis/AssumptionCache.h"
Johannes Doerfert1dc12af2016-04-23 12:59:18 +000036#include "llvm/Analysis/Loads.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000037#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000038#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000039#include "llvm/Analysis/RegionIterator.h"
40#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000041#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000042#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000043#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000045#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000047#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000048#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000049#include "isl/schedule.h"
50#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000051#include "isl/set.h"
52#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000053#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000054#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000055#include <sstream>
56#include <string>
57#include <vector>
58
59using namespace llvm;
60using namespace polly;
61
Chandler Carruth95fef942014-04-22 03:30:19 +000062#define DEBUG_TYPE "polly-scops"
63
Johannes Doerfert81aa6e82016-11-18 14:37:08 +000064STATISTIC(AssumptionsAliasing, "Number of aliasing assumptions taken.");
65STATISTIC(AssumptionsInbounds, "Number of inbounds assumptions taken.");
66STATISTIC(AssumptionsWrapping, "Number of wrapping assumptions taken.");
67STATISTIC(AssumptionsUnsigned, "Number of unsigned assumptions taken.");
68STATISTIC(AssumptionsComplexity, "Number of too complex SCoPs.");
69STATISTIC(AssumptionsUnprofitable, "Number of unprofitable SCoPs.");
70STATISTIC(AssumptionsErrorBlock, "Number of error block assumptions taken.");
71STATISTIC(AssumptionsInfiniteLoop, "Number of bounded loop assumptions taken.");
72STATISTIC(AssumptionsInvariantLoad,
Johannes Doerfertcd195322016-11-17 21:41:08 +000073 "Number of invariant loads assumptions taken.");
Johannes Doerfert81aa6e82016-11-18 14:37:08 +000074STATISTIC(AssumptionsDelinearization,
Johannes Doerfertcd195322016-11-17 21:41:08 +000075 "Number of delinearization assumptions taken.");
76
Tobias Grossercd01a362017-02-17 08:12:36 +000077STATISTIC(NumLoopsInScop, "Number of loops in scops");
78STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
79STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
80STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
81STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
82STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
83STATISTIC(NumScopsDepthLarger,
84 "Number of scops with maximal loop depth 6 and larger");
85STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
86
Tobias Grosser75dc40c2015-12-20 13:31:48 +000087// The maximal number of basic sets we allow during domain construction to
88// be created. More complex scops will result in very high compile time and
89// are also unlikely to result in good code
Tobias Grosser90411a92017-02-16 19:11:33 +000090static int const MaxDisjunctsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +000091
Tobias Grosserc8a82762017-02-16 19:11:25 +000092// The number of disjunct in the context after which we stop to add more
93// disjuncts. This parameter is there to avoid exponential growth in the
94// number of disjunct when adding non-convex sets to the context.
95static int const MaxDisjunctsInContext = 4;
96
Tobias Grosser45e9fd12017-05-19 03:45:00 +000097static cl::opt<int> OptComputeOut(
98 "polly-analysis-computeout",
99 cl::desc("Bound the dependence analysis by a maximal amount of "
100 "computational steps (0 means no bound)"),
101 cl::Hidden, cl::init(1000000), cl::ZeroOrMore, cl::cat(PollyCategory));
102
Johannes Doerfert2f705842016-04-12 16:09:44 +0000103static cl::opt<bool> PollyRemarksMinimal(
104 "polly-remarks-minimal",
105 cl::desc("Do not emit remarks about assumptions that are known"),
106 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
107
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +0000108// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000109// operations can overflow easily. Additive reductions and bit operations
110// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +0000111static cl::opt<bool> DisableMultiplicativeReductions(
112 "polly-disable-multiplicative-reductions",
113 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
114 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000115
Johannes Doerfert9143d672014-09-27 11:02:39 +0000116static cl::opt<unsigned> RunTimeChecksMaxParameters(
117 "polly-rtc-max-parameters",
118 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
119 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
120
Tobias Grosser71500722015-03-28 15:11:14 +0000121static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
122 "polly-rtc-max-arrays-per-group",
123 cl::desc("The maximal number of arrays to compare in each alias group."),
124 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000125
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000126static cl::opt<std::string> UserContextStr(
127 "polly-context", cl::value_desc("isl parameter set"),
128 cl::desc("Provide additional constraints on the context parameters"),
129 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000130
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000131static cl::opt<bool> DetectReductions("polly-detect-reductions",
132 cl::desc("Detect and exploit reductions"),
133 cl::Hidden, cl::ZeroOrMore,
134 cl::init(true), cl::cat(PollyCategory));
135
Tobias Grosser2937b592016-04-29 11:43:20 +0000136static cl::opt<bool>
137 IslOnErrorAbort("polly-on-isl-error-abort",
138 cl::desc("Abort if an isl error is encountered"),
139 cl::init(true), cl::cat(PollyCategory));
140
Tobias Grosserd7c49752017-02-28 09:45:54 +0000141static cl::opt<bool> PollyPreciseInbounds(
142 "polly-precise-inbounds",
143 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
144 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
145
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000146static cl::opt<bool>
147 PollyIgnoreInbounds("polly-ignore-inbounds",
148 cl::desc("Do not take inbounds assumptions at all"),
149 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
150
Tobias Grosser5842dee2017-03-17 13:00:53 +0000151static cl::opt<bool> PollyIgnoreParamBounds(
152 "polly-ignore-parameter-bounds",
153 cl::desc(
154 "Do not add parameter bounds and do no gist simplify sets accordingly"),
155 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
156
Tobias Grosserc2f15102017-03-01 21:11:27 +0000157static cl::opt<bool> PollyPreciseFoldAccesses(
158 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000159 cl::desc("Fold memory accesses to model more possible delinearizations "
160 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000161 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000162
Michael Kruse5ae08c02017-05-06 14:03:58 +0000163bool polly::UseInstructionNames;
164static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000165 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000166 cl::desc("Use LLVM-IR names when deriving statement names"),
167 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
168 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000169
Michael Kruse7bf39442015-09-10 12:46:52 +0000170//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000171
Michael Kruse046dde42015-08-10 13:01:57 +0000172// Create a sequence of two schedules. Either argument may be null and is
173// interpreted as the empty schedule. Can also return null if both schedules are
174// empty.
175static __isl_give isl_schedule *
176combineInSequence(__isl_take isl_schedule *Prev,
177 __isl_take isl_schedule *Succ) {
178 if (!Prev)
179 return Succ;
180 if (!Succ)
181 return Prev;
182
183 return isl_schedule_sequence(Prev, Succ);
184}
185
Johannes Doerferte7044942015-02-24 11:58:30 +0000186static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
187 const ConstantRange &Range,
188 int dim,
189 enum isl_dim_type type) {
190 isl_val *V;
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000191 isl_ctx *Ctx = isl_set_get_ctx(S);
Johannes Doerferte7044942015-02-24 11:58:30 +0000192
Tobias Grosser3281f602017-02-16 18:39:14 +0000193 // The upper and lower bound for a parameter value is derived either from
194 // the data type of the parameter or from the - possibly more restrictive -
195 // range metadata.
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000196 V = isl_valFromAPInt(Ctx, Range.getSignedMin(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000197 S = isl_set_lower_bound_val(S, type, dim, V);
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000198 V = isl_valFromAPInt(Ctx, Range.getSignedMax(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000199 S = isl_set_upper_bound_val(S, type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000200
Tobias Grosser3281f602017-02-16 18:39:14 +0000201 if (Range.isFullSet())
202 return S;
203
Tobias Grosserc8a82762017-02-16 19:11:25 +0000204 if (isl_set_n_basic_set(S) > MaxDisjunctsInContext)
205 return S;
206
Tobias Grosser3281f602017-02-16 18:39:14 +0000207 // In case of signed wrapping, we can refine the set of valid values by
208 // excluding the part not covered by the wrapping range.
209 if (Range.isSignWrappedSet()) {
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000210 V = isl_valFromAPInt(Ctx, Range.getLower(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000211 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
212
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000213 V = isl_valFromAPInt(Ctx, Range.getUpper(), true);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000214 V = isl_val_sub_ui(V, 1);
Tobias Grosser3281f602017-02-16 18:39:14 +0000215 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
216 S = isl_set_union(SLB, SUB);
217 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000218
Tobias Grosser3281f602017-02-16 18:39:14 +0000219 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000220}
221
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000222static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
223 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
224 if (!BasePtrLI)
225 return nullptr;
226
Johannes Doerfert952b5302016-05-23 12:40:48 +0000227 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000228 return nullptr;
229
230 ScalarEvolution &SE = *S->getSE();
231
232 auto *OriginBaseSCEV =
233 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
234 if (!OriginBaseSCEV)
235 return nullptr;
236
237 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
238 if (!OriginBaseSCEVUnknown)
239 return nullptr;
240
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000241 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000242 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000243}
244
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000245ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000246 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000247 const DataLayout &DL, Scop *S,
248 const char *BaseName)
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000249 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000250 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000251 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000252 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
253 Kind == MemoryKind::PHI ? "__phi" : "",
254 UseInstructionNames);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000255 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000256
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000257 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000258
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000259 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000260 BasePtrOriginSAI = nullptr;
261 return;
262 }
263
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000264 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
265 if (BasePtrOriginSAI)
266 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000267}
268
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000269__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000270 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000271 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
272 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
273 return Space;
274}
275
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000276bool ScopArrayInfo::isReadOnly() {
277 isl_union_set *WriteSet = isl_union_map_range(S.getWrites());
278 isl_space *Space = getSpace();
279 WriteSet = isl_union_set_intersect(
280 WriteSet, isl_union_set_from_set(isl_set_universe(Space)));
281
282 bool IsReadOnly = isl_union_set_is_empty(WriteSet);
283 isl_union_set_free(WriteSet);
284
285 return IsReadOnly;
286}
287
Tobias Grosserf3adab42017-05-10 10:59:58 +0000288bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
289 if (Array->getElementType() != getElementType())
290 return false;
291
292 if (Array->getNumberOfDimensions() != getNumberOfDimensions())
293 return false;
294
295 for (unsigned i = 0; i < getNumberOfDimensions(); i++)
296 if (Array->getDimensionSize(i) != getDimensionSize(i))
297 return false;
298
299 return true;
300}
301
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000302void ScopArrayInfo::updateElementType(Type *NewElementType) {
303 if (NewElementType == ElementType)
304 return;
305
Tobias Grosserd840fc72016-02-04 13:18:42 +0000306 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
307 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
308
Johannes Doerferta7920982016-02-25 14:08:48 +0000309 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000310 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000311
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000312 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
313 ElementType = NewElementType;
314 } else {
315 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
316 ElementType = IntegerType::get(ElementType->getContext(), GCD);
317 }
318}
319
Tobias Grosserbedef002016-12-02 08:10:56 +0000320bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
321 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000322 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
323 int ExtraDimsNew = NewSizes.size() - SharedDims;
324 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000325
Tobias Grosserbedef002016-12-02 08:10:56 +0000326 if (CheckConsistency) {
327 for (int i = 0; i < SharedDims; i++) {
328 auto *NewSize = NewSizes[i + ExtraDimsNew];
329 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
330 if (NewSize && KnownSize && NewSize != KnownSize)
331 return false;
332 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000333
Tobias Grosserbedef002016-12-02 08:10:56 +0000334 if (DimensionSizes.size() >= NewSizes.size())
335 return true;
336 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000337
338 DimensionSizes.clear();
339 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
340 NewSizes.end());
341 for (isl_pw_aff *Size : DimensionSizesPw)
342 isl_pw_aff_free(Size);
343 DimensionSizesPw.clear();
344 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000345 if (!Expr) {
346 DimensionSizesPw.push_back(nullptr);
347 continue;
348 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000349 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000350 DimensionSizesPw.push_back(Size);
351 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000352 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000353}
354
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000355ScopArrayInfo::~ScopArrayInfo() {
356 isl_id_free(Id);
357 for (isl_pw_aff *Size : DimensionSizesPw)
358 isl_pw_aff_free(Size);
359}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000360
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000361std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
362
363int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000364 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000365}
366
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000367__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
368 return isl_id_copy(Id);
369}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000370
371void ScopArrayInfo::dump() const { print(errs()); }
372
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000373void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000374 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000375 unsigned u = 0;
376 if (getNumberOfDimensions() > 0 && !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000377 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000378 u++;
379 }
380 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000381 OS << "[";
382
Tobias Grosser26253842015-11-10 14:24:21 +0000383 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000384 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000385 OS << " " << Size << " ";
386 isl_pw_aff_free(Size);
387 } else {
388 OS << *getDimensionSize(u);
389 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000390
391 OS << "]";
392 }
393
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000394 OS << ";";
395
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000396 if (BasePtrOriginSAI)
397 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
398
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000399 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000400}
401
402const ScopArrayInfo *
403ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
404 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
405 assert(Id && "Output dimension didn't have an ID");
406 return getFromId(Id);
407}
408
Michael Krused56b90a2016-09-01 09:03:27 +0000409const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000410 void *User = isl_id_get_user(Id);
411 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
412 isl_id_free(Id);
413 return SAI;
414}
415
Michael Kruse3b425ff2016-04-11 14:34:08 +0000416void MemoryAccess::wrapConstantDimensions() {
417 auto *SAI = getScopArrayInfo();
418 auto *ArraySpace = SAI->getSpace();
419 auto *Ctx = isl_space_get_ctx(ArraySpace);
420 unsigned DimsArray = SAI->getNumberOfDimensions();
421
422 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
423 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
424 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
425
426 // Begin with last dimension, to iteratively carry into higher dimensions.
427 for (int i = DimsArray - 1; i > 0; i--) {
428 auto *DimSize = SAI->getDimensionSize(i);
429 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
430
431 // This transformation is not applicable to dimensions with dynamic size.
432 if (!DimSizeCst)
433 continue;
434
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000435 // This transformation is not applicable to dimensions of size zero.
436 if (DimSize->isZero())
437 continue;
438
Michael Kruse3b425ff2016-04-11 14:34:08 +0000439 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
440 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
441 isl_dim_set, i);
442 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
443 isl_dim_set, i - 1);
444
445 // Compute: index % size
446 // Modulo must apply in the divide of the previous iteration, if any.
447 auto *Modulo = isl_aff_copy(Var);
448 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
449 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
450
451 // Compute: floor(index / size)
452 auto *Divide = Var;
453 Divide = isl_aff_div(
454 Divide,
455 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
456 Divide = isl_aff_floor(Divide);
457 Divide = isl_aff_add(Divide, PrevVar);
458 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
459
460 // Apply Modulo and Divide.
461 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
462 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
463 }
464
465 // Apply all modulo/divides on the accesses.
466 AccessRelation =
467 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
468 AccessRelation = isl_map_detect_equalities(AccessRelation);
469 isl_local_space_free(LArraySpace);
470}
471
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000472void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000473 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000474 auto *ArraySpace = SAI->getSpace();
475 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000476 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000477
478 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
479 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
480 auto DimsMissing = DimsArray - DimsAccess;
481
Michael Kruse375cb5f2016-02-24 22:08:24 +0000482 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000483 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000484 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000485 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000486
Johannes Doerferta90943d2016-02-21 16:37:25 +0000487 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000488 isl_set_universe(AccessSpace),
489 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000490
491 for (unsigned i = 0; i < DimsMissing; i++)
492 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
493
494 for (unsigned i = DimsMissing; i < DimsArray; i++)
495 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
496
497 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000498
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000499 // For the non delinearized arrays, divide the access function of the last
500 // subscript by the size of the elements in the array.
501 //
502 // A stride one array access in C expressed as A[i] is expressed in
503 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
504 // two subsequent values of 'i' index two values that are stored next to
505 // each other in memory. By this division we make this characteristic
506 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000507 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000508 // that divides the offsets of all accesses to this base pointer.
509 if (DimsAccess == 1) {
510 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
511 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
512 }
513
Michael Kruse3b425ff2016-04-11 14:34:08 +0000514 // We currently do this only if we added at least one dimension, which means
515 // some dimension's indices have not been specified, an indicator that some
516 // index values have been added together.
517 // TODO: Investigate general usefulness; Effect on unit tests is to make index
518 // expressions more complicated.
519 if (DimsMissing)
520 wrapConstantDimensions();
521
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000522 if (!isAffine())
523 computeBoundsOnAccessRelation(ArrayElemSize);
524
Tobias Grosserd840fc72016-02-04 13:18:42 +0000525 // Introduce multi-element accesses in case the type loaded by this memory
526 // access is larger than the canonical element type of the array.
527 //
528 // An access ((float *)A)[i] to an array char *A is modeled as
529 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000530 if (ElemBytes > ArrayElemSize) {
531 assert(ElemBytes % ArrayElemSize == 0 &&
532 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000533 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000534 isl_set_universe(isl_space_copy(ArraySpace)),
535 isl_set_universe(isl_space_copy(ArraySpace)));
536 for (unsigned i = 0; i < DimsArray - 1; i++)
537 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
538
Tobias Grosserd840fc72016-02-04 13:18:42 +0000539 isl_constraint *C;
540 isl_local_space *LS;
541
542 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000543 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
544
545 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
546 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000547 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000548 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
549 Map = isl_map_add_constraint(Map, C);
550
551 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000552 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000553 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
554 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
555 Map = isl_map_add_constraint(Map, C);
556 AccessRelation = isl_map_apply_range(AccessRelation, Map);
557 }
558
559 isl_space_free(ArraySpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000560}
561
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000562const std::string
563MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
564 switch (RT) {
565 case MemoryAccess::RT_NONE:
566 llvm_unreachable("Requested a reduction operator string for a memory "
567 "access which isn't a reduction");
568 case MemoryAccess::RT_ADD:
569 return "+";
570 case MemoryAccess::RT_MUL:
571 return "*";
572 case MemoryAccess::RT_BOR:
573 return "|";
574 case MemoryAccess::RT_BXOR:
575 return "^";
576 case MemoryAccess::RT_BAND:
577 return "&";
578 }
579 llvm_unreachable("Unknown reduction type");
580 return "";
581}
582
Tobias Grosserc80d6972016-09-02 06:33:33 +0000583/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000584static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
585 const Instruction *Load) {
586 if (!BinOp)
587 return MemoryAccess::RT_NONE;
588 switch (BinOp->getOpcode()) {
589 case Instruction::FAdd:
590 if (!BinOp->hasUnsafeAlgebra())
591 return MemoryAccess::RT_NONE;
592 // Fall through
593 case Instruction::Add:
594 return MemoryAccess::RT_ADD;
595 case Instruction::Or:
596 return MemoryAccess::RT_BOR;
597 case Instruction::Xor:
598 return MemoryAccess::RT_BXOR;
599 case Instruction::And:
600 return MemoryAccess::RT_BAND;
601 case Instruction::FMul:
602 if (!BinOp->hasUnsafeAlgebra())
603 return MemoryAccess::RT_NONE;
604 // Fall through
605 case Instruction::Mul:
606 if (DisableMultiplicativeReductions)
607 return MemoryAccess::RT_NONE;
608 return MemoryAccess::RT_MUL;
609 default:
610 return MemoryAccess::RT_NONE;
611 }
612}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000613
Tobias Grosser75805372011-04-29 06:27:02 +0000614MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000615 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000616 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000617 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000618 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000619}
620
Michael Kruse2fa35192016-09-01 19:53:31 +0000621const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000622 isl_id *ArrayId = getArrayId();
623 void *User = isl_id_get_user(ArrayId);
624 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
625 isl_id_free(ArrayId);
626 return SAI;
627}
628
Michael Kruse2fa35192016-09-01 19:53:31 +0000629const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
630 isl_id *ArrayId = getLatestArrayId();
631 void *User = isl_id_get_user(ArrayId);
632 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
633 isl_id_free(ArrayId);
634 return SAI;
635}
636
637__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000638 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
639}
640
Michael Kruse2fa35192016-09-01 19:53:31 +0000641__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
642 if (!hasNewAccessRelation())
643 return getOriginalArrayId();
644 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
645}
646
Tobias Grosserd840fc72016-02-04 13:18:42 +0000647__isl_give isl_map *MemoryAccess::getAddressFunction() const {
648 return isl_map_lexmin(getAccessRelation());
649}
650
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000651__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
652 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000653 isl_map *Schedule, *ScheduledAccRel;
654 isl_union_set *UDomain;
655
656 UDomain = isl_union_set_from_set(getStatement()->getDomain());
657 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
658 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000659 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000660 return isl_pw_multi_aff_from_map(ScheduledAccRel);
661}
662
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000663__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000664 return isl_map_copy(AccessRelation);
665}
666
Johannes Doerferta99130f2014-10-13 12:58:03 +0000667std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000668 return stringFromIslObj(AccessRelation);
669}
670
Johannes Doerferta99130f2014-10-13 12:58:03 +0000671__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000672 return isl_map_get_space(AccessRelation);
673}
674
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000675__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000676 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000677}
678
Tobias Grosser6f730082015-09-05 07:46:47 +0000679std::string MemoryAccess::getNewAccessRelationStr() const {
680 return stringFromIslObj(NewAccessRelation);
681}
682
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000683__isl_give isl_basic_map *
684MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000685 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000686 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000687
Tobias Grosser084d8f72012-05-29 09:29:44 +0000688 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000689 isl_basic_set_universe(Statement->getDomainSpace()),
690 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000691}
692
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000693// Formalize no out-of-bound access assumption
694//
695// When delinearizing array accesses we optimistically assume that the
696// delinearized accesses do not access out of bound locations (the subscript
697// expression of each array evaluates for each statement instance that is
698// executed to a value that is larger than zero and strictly smaller than the
699// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000700// dimension for which we do not need to assume any upper bound. At this point
701// we formalize this assumption to ensure that at code generation time the
702// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000703//
704// To find the set of constraints necessary to avoid out of bound accesses, we
705// first build the set of data locations that are not within array bounds. We
706// then apply the reverse access relation to obtain the set of iterations that
707// may contain invalid accesses and reduce this set of iterations to the ones
708// that are actually executed by intersecting them with the domain of the
709// statement. If we now project out all loop dimensions, we obtain a set of
710// parameters that may cause statement instances to be executed that may
711// possibly yield out of bound memory accesses. The complement of these
712// constraints is the set of constraints that needs to be assumed to ensure such
713// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000714void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000715 if (PollyIgnoreInbounds)
716 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000717 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000718 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000719 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000720 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000721 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
722 isl_pw_aff *Var =
723 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
724 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
725
726 isl_set *DimOutside;
727
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000728 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000729 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000730 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
731 isl_space_dim(Space, isl_dim_set));
732 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
733 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000734
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000735 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000736
737 Outside = isl_set_union(Outside, DimOutside);
738 }
739
740 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
741 Outside = isl_set_intersect(Outside, Statement->getDomain());
742 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000743
744 // Remove divs to avoid the construction of overly complicated assumptions.
745 // Doing so increases the set of parameter combinations that are assumed to
746 // not appear. This is always save, but may make the resulting run-time check
747 // bail out more often than strictly necessary.
748 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000749 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000750 const auto &Loc = getAccessInstruction()
751 ? getAccessInstruction()->getDebugLoc()
752 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000753 if (!PollyPreciseInbounds)
754 Outside = isl_set_gist(Outside, isl_set_params(Statement->getDomain()));
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000755 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
756 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000757 isl_space_free(Space);
758}
759
Johannes Doerfertcea61932016-02-21 19:13:19 +0000760void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000761 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000762 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000763
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000764 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000765 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000766
767 isl_map *LengthMap;
768 if (Subscripts[1] == nullptr) {
769 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
770 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000771 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000772 LengthMap = isl_map_from_pw_aff(LengthPWA);
773 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
774 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
775 }
776 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
777 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000778 SubscriptMap =
779 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000780 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
781 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
782 getStatement()->getDomainId());
783}
784
Johannes Doerferte7044942015-02-24 11:58:30 +0000785void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
786 ScalarEvolution *SE = Statement->getParent()->getSE();
787
Johannes Doerfertcea61932016-02-21 19:13:19 +0000788 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000789 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000790 return;
791
792 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000793 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
794 return;
795
796 auto *PtrSCEV = SE->getSCEV(Ptr);
797 if (isa<SCEVCouldNotCompute>(PtrSCEV))
798 return;
799
800 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
801 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
802 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
803
804 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
805 if (Range.isFullSet())
806 return;
807
Michael Kruse960c0d02017-05-18 21:55:36 +0000808 if (Range.isWrappedSet() || Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000809 return;
810
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000811 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000812
Johannes Doerferte7044942015-02-24 11:58:30 +0000813 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000814 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000815 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000816 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000817
818 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000819 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000820
Tobias Grosserb3a85882017-02-12 08:11:12 +0000821 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
822
Johannes Doerferte7044942015-02-24 11:58:30 +0000823 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
824 AccessRange =
825 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
826 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
827}
828
Tobias Grosser491b7992016-12-02 05:21:22 +0000829void MemoryAccess::foldAccessRelation() {
830 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
831 return;
832
Michael Krusee2bccbb2015-09-18 19:59:43 +0000833 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000834
Tobias Grosserc2f15102017-03-01 21:11:27 +0000835 isl_map *OldAccessRelation = isl_map_copy(AccessRelation);
836
Tobias Grosser619190d2015-03-30 17:22:28 +0000837 for (int i = Size - 2; i >= 0; --i) {
838 isl_space *Space;
839 isl_map *MapOne, *MapTwo;
Roman Gareevf5aff702016-09-12 17:08:31 +0000840 isl_pw_aff *DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000841
842 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
843 isl_pw_aff_free(DimSize);
844 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
845
846 Space = isl_map_get_space(AccessRelation);
847 Space = isl_space_map_from_set(isl_space_range(Space));
848 Space = isl_space_align_params(Space, SpaceSize);
849
850 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
851 isl_id_free(ParamId);
852
853 MapOne = isl_map_universe(isl_space_copy(Space));
854 for (int j = 0; j < Size; ++j)
855 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
856 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
857
858 MapTwo = isl_map_universe(isl_space_copy(Space));
859 for (int j = 0; j < Size; ++j)
860 if (j < i || j > i + 1)
861 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
862
863 isl_local_space *LS = isl_local_space_from_space(Space);
864 isl_constraint *C;
865 C = isl_equality_alloc(isl_local_space_copy(LS));
866 C = isl_constraint_set_constant_si(C, -1);
867 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
868 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
869 MapTwo = isl_map_add_constraint(MapTwo, C);
870 C = isl_equality_alloc(LS);
871 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
872 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
873 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
874 MapTwo = isl_map_add_constraint(MapTwo, C);
875 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
876
877 MapOne = isl_map_union(MapOne, MapTwo);
878 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
879 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000880
881 isl_id *BaseAddrId = getScopArrayInfo()->getBasePtrId();
882 auto Space = Statement->getDomainSpace();
883 AccessRelation = isl_map_set_tuple_id(
884 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
885 AccessRelation =
886 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
887 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Tobias Grosserc2f15102017-03-01 21:11:27 +0000888
889 // Access dimension folding might in certain cases increase the number of
890 // disjuncts in the memory access, which can possibly complicate the generated
891 // run-time checks and can lead to costly compilation.
892 if (!PollyPreciseFoldAccesses && isl_map_n_basic_map(AccessRelation) >
893 isl_map_n_basic_map(OldAccessRelation)) {
894 isl_map_free(AccessRelation);
895 AccessRelation = OldAccessRelation;
896 } else {
897 isl_map_free(OldAccessRelation);
898 }
899
Tobias Grosser491b7992016-12-02 05:21:22 +0000900 isl_space_free(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000901}
902
Tobias Grosserc80d6972016-09-02 06:33:33 +0000903/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000904static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000905 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000906 if (Size == 1)
907 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000908
909 // Only one factor needs to be divisible.
910 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
911 for (auto *FactorExpr : MulExpr->operands())
912 if (isDivisible(FactorExpr, Size, SE))
913 return true;
914 return false;
915 }
916
917 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
918 // to be divisble.
919 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
920 for (auto *OpExpr : NAryExpr->operands())
921 if (!isDivisible(OpExpr, Size, SE))
922 return false;
923 return true;
924 }
925
926 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
927 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
928 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
929 return MulSCEV == Expr;
930}
931
Michael Krusee2bccbb2015-09-18 19:59:43 +0000932void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
933 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000934
Johannes Doerfert85676e32016-04-23 14:32:34 +0000935 // Initialize the invalid domain which describes all iterations for which the
936 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000937 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
938 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
939 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000940
Michael Krusee2bccbb2015-09-18 19:59:43 +0000941 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000942 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000943
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000944 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
945 buildMemIntrinsicAccessRelation();
946 AccessRelation =
947 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
948 return;
949 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000950
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000951 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000952 // We overapproximate non-affine accesses with a possible access to the
953 // whole array. For read accesses it does not make a difference, if an
954 // access must or may happen. However, for write accesses it is important to
955 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000956 if (!AccessRelation)
957 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
958
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000959 AccessRelation =
960 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000961 return;
962 }
963
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000964 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000965 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000966
Michael Krusee2bccbb2015-09-18 19:59:43 +0000967 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000968 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000969 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000970 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000971 }
972
Tobias Grosser79baa212014-04-10 08:38:02 +0000973 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000974 AccessRelation = isl_map_set_tuple_id(
975 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000976 AccessRelation =
977 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
978
Tobias Grosseraa660a92015-03-30 00:07:50 +0000979 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000980 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000981}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000982
Michael Krusecac948e2015-10-02 13:53:07 +0000983MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000984 AccessType AccType, Value *BaseAddress,
985 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000986 ArrayRef<const SCEV *> Subscripts,
987 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +0000988 MemoryKind Kind)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000989 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Tobias Grosser81331282017-05-03 07:57:35 +0000990 InvalidDomain(nullptr), BaseAddr(BaseAddress), ElementType(ElementType),
991 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
992 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000993 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +0000994 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000995 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +0000996 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000997
Tobias Grosser81331282017-05-03 07:57:35 +0000998 std::string IdName = Stmt->getBaseName() + Access;
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000999 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1000}
Michael Krusee2bccbb2015-09-18 19:59:43 +00001001
Roman Gareevb3224ad2016-09-14 06:26:09 +00001002MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
1003 __isl_take isl_map *AccRel)
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001004 : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
1005 Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001006 IsAffine(true), AccessRelation(nullptr), NewAccessRelation(AccRel),
1007 FAD(nullptr) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001008 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
1009 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1010 Sizes.push_back(nullptr);
1011 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1012 Sizes.push_back(SAI->getDimensionSize(i));
1013 ElementType = SAI->getElementType();
1014 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001015 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001016 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001017
Tobias Grosser81331282017-05-03 07:57:35 +00001018 std::string IdName = Stmt->getBaseName() + Access;
Roman Gareevb3224ad2016-09-14 06:26:09 +00001019 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1020}
1021
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001022void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +00001023 auto *Ctx = Statement->getParent()->getContext();
1024 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1025 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001026}
1027
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001028const std::string MemoryAccess::getReductionOperatorStr() const {
1029 return MemoryAccess::getReductionOperatorStr(getReductionType());
1030}
1031
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001032__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
1033
Johannes Doerfertf6183392014-07-01 20:52:51 +00001034raw_ostream &polly::operator<<(raw_ostream &OS,
1035 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001036 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001037 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001038 else
1039 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001040 return OS;
1041}
1042
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001043void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001044
Tobias Grosser75805372011-04-29 06:27:02 +00001045void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001046 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001047 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001048 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001049 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001050 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001051 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001052 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001053 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001054 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001055 break;
1056 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001057
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001058 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001059
1060 if (FAD) {
1061 OS << "[Fortran array descriptor: " << FAD->getName();
1062 OS << "] ";
1063 };
1064
Tobias Grossera535dff2015-12-13 19:59:01 +00001065 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001066 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001067 if (hasNewAccessRelation())
1068 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001069}
1070
Tobias Grosser74394f02013-01-14 22:40:23 +00001071void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +00001072
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001073__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
1074 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001075 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +00001076 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
1077 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
1078 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +00001079 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001080}
1081
Tobias Grosser75805372011-04-29 06:27:02 +00001082// Create a map in the size of the provided set domain, that maps from the
1083// one element of the provided set domain to another element of the provided
1084// set domain.
1085// The mapping is limited to all points that are equal in all but the last
1086// dimension and for which the last dimension of the input is strict smaller
1087// than the last dimension of the output.
1088//
1089// getEqualAndLarger(set[i0, i1, ..., iX]):
1090//
1091// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1092// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1093//
Tobias Grosser2a526fe2016-09-08 11:18:56 +00001094static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +00001095 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001096 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +00001097 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001098
1099 // Set all but the last dimension to be equal for the input and output
1100 //
1101 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1102 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001103 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +00001104 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001105
1106 // Set the last dimension of the input to be strict smaller than the
1107 // last dimension of the output.
1108 //
1109 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001110 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1111 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001112 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001113}
1114
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001115__isl_give isl_set *
1116MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001117 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +00001118 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +00001119 isl_space *Space = isl_space_range(isl_map_get_space(S));
1120 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001121
Sebastian Popa00a0292012-12-18 07:46:06 +00001122 S = isl_map_reverse(S);
1123 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001124
Sebastian Popa00a0292012-12-18 07:46:06 +00001125 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1126 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1127 NextScatt = isl_map_apply_domain(NextScatt, S);
1128 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001129
Sebastian Popa00a0292012-12-18 07:46:06 +00001130 isl_set *Deltas = isl_map_deltas(NextScatt);
1131 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001132}
1133
Sebastian Popa00a0292012-12-18 07:46:06 +00001134bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001135 int StrideWidth) const {
1136 isl_set *Stride, *StrideX;
1137 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001138
Sebastian Popa00a0292012-12-18 07:46:06 +00001139 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001140 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001141 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1142 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1143 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1144 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001145 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001146
Tobias Grosser28dd4862012-01-24 16:42:16 +00001147 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001148 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001149
Tobias Grosser28dd4862012-01-24 16:42:16 +00001150 return IsStrideX;
1151}
1152
Michael Krused56b90a2016-09-01 09:03:27 +00001153bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001154 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001155}
1156
Michael Krused56b90a2016-09-01 09:03:27 +00001157bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001158 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001159}
1160
Tobias Grosserbedef002016-12-02 08:10:56 +00001161void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
1162 isl_map_free(AccessRelation);
1163 AccessRelation = NewAccess;
1164}
1165
Michael Krused56b90a2016-09-01 09:03:27 +00001166void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001167 assert(NewAccess);
1168
1169#ifndef NDEBUG
1170 // Check domain space compatibility.
1171 auto *NewSpace = isl_map_get_space(NewAccess);
1172 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1173 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1174 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1175 isl_space_free(NewDomainSpace);
1176 isl_space_free(OriginalDomainSpace);
1177
1178 // Check whether there is an access for every statement instance.
1179 auto *StmtDomain = getStatement()->getDomain();
1180 StmtDomain = isl_set_intersect_params(
1181 StmtDomain, getStatement()->getParent()->getContext());
1182 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1183 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1184 "Partial accesses not supported");
1185 isl_set_free(NewDomain);
1186 isl_set_free(StmtDomain);
1187
Michael Kruse772ce722016-09-01 19:16:58 +00001188 auto *NewAccessSpace = isl_space_range(NewSpace);
1189 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1190 "Must specify the array that is accessed");
1191 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1192 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1193 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001194
1195 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1196 InvariantEquivClassTy *EqClass =
1197 getStatement()->getParent()->lookupInvariantEquivClass(
1198 SAI->getBasePtr());
1199 assert(EqClass &&
1200 "Access functions to indirect arrays must have an invariant and "
1201 "hoisted base pointer");
1202 }
1203
1204 // Check whether access dimensions correspond to number of dimensions of the
1205 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001206 auto Dims = SAI->getNumberOfDimensions();
1207 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1208 "Access dims must match array dims");
1209 isl_space_free(NewAccessSpace);
1210 isl_id_free(NewArrayId);
1211#endif
1212
Tobias Grosser166c4222015-09-05 07:46:40 +00001213 isl_map_free(NewAccessRelation);
1214 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001215}
Tobias Grosser75805372011-04-29 06:27:02 +00001216
1217//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001218
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001219__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001220 isl_set *Domain = getDomain();
1221 if (isl_set_is_empty(Domain)) {
1222 isl_set_free(Domain);
1223 return isl_map_from_aff(
1224 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1225 }
1226 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001227 if (!Schedule) {
1228 isl_set_free(Domain);
1229 return nullptr;
1230 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001231 Schedule = isl_union_map_intersect_domain(
1232 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1233 if (isl_union_map_is_empty(Schedule)) {
1234 isl_set_free(Domain);
1235 isl_union_map_free(Schedule);
1236 return isl_map_from_aff(
1237 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1238 }
1239 auto *M = isl_map_from_union_map(Schedule);
1240 M = isl_map_coalesce(M);
1241 M = isl_map_gist_domain(M, Domain);
1242 M = isl_map_coalesce(M);
1243 return M;
1244}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001245
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001246__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1247 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001248 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1249 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001250}
1251
Tobias Grosser37eb4222014-02-20 21:43:54 +00001252void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1253 assert(isl_set_is_subset(NewDomain, Domain) &&
1254 "New domain is not a subset of old domain!");
1255 isl_set_free(Domain);
1256 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001257}
1258
Michael Krusecac948e2015-10-02 13:53:07 +00001259void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001260 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001261 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001262 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001263
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001264 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001265 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001266 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001267 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001268 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001269 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001270 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001271 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001272 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001273
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001274 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1275 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001276 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001277 }
1278}
1279
Michael Kruse4c276432017-05-11 22:56:46 +00001280MemoryAccess *ScopStmt::lookupPHIReadOf(PHINode *PHI) const {
1281 for (auto *MA : *this) {
1282 if (!MA->isRead())
1283 continue;
1284 if (!MA->isLatestAnyPHIKind())
1285 continue;
1286
1287 if (MA->getAccessInstruction() == PHI)
1288 return MA;
1289 }
1290 return nullptr;
1291}
1292
Michael Krusecac948e2015-10-02 13:53:07 +00001293void ScopStmt::addAccess(MemoryAccess *Access) {
1294 Instruction *AccessInst = Access->getAccessInstruction();
1295
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001296 if (Access->isArrayKind()) {
1297 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1298 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001299 } else if (Access->isValueKind() && Access->isWrite()) {
1300 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001301 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001302 assert(!ValueWrites.lookup(AccessVal));
1303
1304 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001305 } else if (Access->isValueKind() && Access->isRead()) {
1306 Value *AccessVal = Access->getAccessValue();
1307 assert(!ValueReads.lookup(AccessVal));
1308
1309 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001310 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001311 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001312 assert(!PHIWrites.lookup(PHI));
1313
1314 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001315 }
1316
1317 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001318}
1319
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001320void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001321 for (MemoryAccess *MA : *this)
1322 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001323
Johannes Doerferta60ad842016-05-10 12:18:22 +00001324 auto *Ctx = Parent.getContext();
1325 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1326 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001327}
1328
Tobias Grosserc80d6972016-09-02 06:33:33 +00001329/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001330static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1331 void *User) {
1332 isl_set **BoundedParts = static_cast<isl_set **>(User);
1333 if (isl_basic_set_is_bounded(BSet))
1334 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1335 else
1336 isl_basic_set_free(BSet);
1337 return isl_stat_ok;
1338}
1339
Tobias Grosserc80d6972016-09-02 06:33:33 +00001340/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001341static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1342 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1343 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1344 isl_set_free(S);
1345 return BoundedParts;
1346}
1347
Tobias Grosserc80d6972016-09-02 06:33:33 +00001348/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001349///
1350/// @returns A separation of @p S into first an unbounded then a bounded subset,
1351/// both with regards to the dimension @p Dim.
1352static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1353partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1354
1355 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001356 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001357
1358 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001359 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001360
1361 // Remove dimensions that are greater than Dim as they are not interesting.
1362 assert(NumDimsS >= Dim + 1);
1363 OnlyDimS =
1364 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1365
1366 // Create artificial parametric upper bounds for dimensions smaller than Dim
1367 // as we are not interested in them.
1368 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1369 for (unsigned u = 0; u < Dim; u++) {
1370 isl_constraint *C = isl_inequality_alloc(
1371 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1372 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1373 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1374 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1375 }
1376
1377 // Collect all bounded parts of OnlyDimS.
1378 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1379
1380 // Create the dimensions greater than Dim again.
1381 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1382 NumDimsS - Dim - 1);
1383
1384 // Remove the artificial upper bound parameters again.
1385 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1386
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001387 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001388 return std::make_pair(UnboundedParts, BoundedParts);
1389}
1390
Tobias Grosserc80d6972016-09-02 06:33:33 +00001391/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001392static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1393 __isl_take isl_set *To) {
1394 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1395 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1396 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1397 }
1398 return To;
1399}
1400
Tobias Grosserc80d6972016-09-02 06:33:33 +00001401/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001402static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001403 __isl_take isl_pw_aff *L,
1404 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001405 switch (Pred) {
1406 case ICmpInst::ICMP_EQ:
1407 return isl_pw_aff_eq_set(L, R);
1408 case ICmpInst::ICMP_NE:
1409 return isl_pw_aff_ne_set(L, R);
1410 case ICmpInst::ICMP_SLT:
1411 return isl_pw_aff_lt_set(L, R);
1412 case ICmpInst::ICMP_SLE:
1413 return isl_pw_aff_le_set(L, R);
1414 case ICmpInst::ICMP_SGT:
1415 return isl_pw_aff_gt_set(L, R);
1416 case ICmpInst::ICMP_SGE:
1417 return isl_pw_aff_ge_set(L, R);
1418 case ICmpInst::ICMP_ULT:
1419 return isl_pw_aff_lt_set(L, R);
1420 case ICmpInst::ICMP_UGT:
1421 return isl_pw_aff_gt_set(L, R);
1422 case ICmpInst::ICMP_ULE:
1423 return isl_pw_aff_le_set(L, R);
1424 case ICmpInst::ICMP_UGE:
1425 return isl_pw_aff_ge_set(L, R);
1426 default:
1427 llvm_unreachable("Non integer predicate not supported");
1428 }
1429}
1430
Tobias Grosserc80d6972016-09-02 06:33:33 +00001431/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001432///
1433/// Helper function that will make sure the dimensions of the result have the
1434/// same isl_id's as the @p Domain.
1435static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1436 __isl_take isl_pw_aff *L,
1437 __isl_take isl_pw_aff *R,
1438 __isl_keep isl_set *Domain) {
1439 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1440 return setDimensionIds(Domain, ConsequenceCondSet);
1441}
1442
Tobias Grosserc80d6972016-09-02 06:33:33 +00001443/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001444///
1445/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001446/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1447/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001448static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001449buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1450 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001451 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1452
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001453 Value *Condition = getConditionFromTerminator(SI);
1454 assert(Condition && "No condition for switch");
1455
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001456 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001457 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001458 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001459 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001460
1461 unsigned NumSuccessors = SI->getNumSuccessors();
1462 ConditionSets.resize(NumSuccessors);
1463 for (auto &Case : SI->cases()) {
1464 unsigned Idx = Case.getSuccessorIndex();
1465 ConstantInt *CaseValue = Case.getCaseValue();
1466
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001467 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001468 isl_set *CaseConditionSet =
1469 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1470 ConditionSets[Idx] = isl_set_coalesce(
1471 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1472 }
1473
1474 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1475 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1476 for (unsigned u = 2; u < NumSuccessors; u++)
1477 ConditionSetUnion =
1478 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1479 ConditionSets[0] = setDimensionIds(
1480 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1481
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001482 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001483
1484 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001485}
1486
Tobias Grosserc80d6972016-09-02 06:33:33 +00001487/// Build the conditions sets for the branch condition @p Condition in
1488/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001489///
1490/// This will fill @p ConditionSets with the conditions under which control
1491/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001492/// have as many elements as @p TI has successors. If @p TI is nullptr the
1493/// context under which @p Condition is true/false will be returned as the
1494/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001495static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001496buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1497 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001498 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1499
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001500 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001501 isl_set *ConsequenceCondSet = nullptr;
1502 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1503 if (CCond->isZero())
1504 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1505 else
1506 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1507 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1508 auto Opcode = BinOp->getOpcode();
1509 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1510
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001511 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1512 ConditionSets) &&
1513 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1514 ConditionSets);
1515 if (!Valid) {
1516 while (!ConditionSets.empty())
1517 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001518 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001519 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001520
1521 isl_set_free(ConditionSets.pop_back_val());
1522 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1523 isl_set_free(ConditionSets.pop_back_val());
1524 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1525
1526 if (Opcode == Instruction::And)
1527 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1528 else
1529 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1530 } else {
1531 auto *ICond = dyn_cast<ICmpInst>(Condition);
1532 assert(ICond &&
1533 "Condition of exiting branch was neither constant nor ICmp!");
1534
1535 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001536 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001537 // For unsigned comparisons we assumed the signed bit of neither operand
1538 // to be set. The comparison is equal to a signed comparison under this
1539 // assumption.
1540 bool NonNeg = ICond->isUnsigned();
1541 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1542 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001543 ConsequenceCondSet =
1544 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1545 }
1546
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001547 // If no terminator was given we are only looking for parameter constraints
1548 // under which @p Condition is true/false.
1549 if (!TI)
1550 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001551 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001552 ConsequenceCondSet = isl_set_coalesce(
1553 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001554
Johannes Doerfertb2885792016-04-26 09:20:41 +00001555 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001556 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001557 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001558
Michael Krusef7a4a942016-05-02 12:25:36 +00001559 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001560 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1561 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001562 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001563 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001564 }
1565
Michael Krusef7a4a942016-05-02 12:25:36 +00001566 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001567 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001568 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001569 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001570 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001571 }
1572
1573 ConditionSets.push_back(ConsequenceCondSet);
1574 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001575
1576 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001577}
1578
Tobias Grosserc80d6972016-09-02 06:33:33 +00001579/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001580///
1581/// This will fill @p ConditionSets with the conditions under which control
1582/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1583/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001584static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001585buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001586 __isl_keep isl_set *Domain,
1587 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1588
1589 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001590 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001591
1592 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1593
1594 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001595 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001596 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001597 }
1598
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001599 Value *Condition = getConditionFromTerminator(TI);
1600 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001601
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001602 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001603}
1604
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001605void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001606 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001607
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001608 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001609 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001610}
1611
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001612void ScopStmt::collectSurroundingLoops() {
1613 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1614 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1615 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1616 isl_id_free(DimId);
1617 }
1618}
1619
Michael Kruse55454072017-03-15 22:16:43 +00001620ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001621 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
Michael Kruse55454072017-03-15 22:16:43 +00001622 R(&R), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001623
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001624 BaseName = getIslCompatibleName(
1625 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001626}
1627
Michael Kruse55454072017-03-15 22:16:43 +00001628ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001629 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Michael Kruse55454072017-03-15 22:16:43 +00001630 R(nullptr), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Tobias Grosser75805372011-04-29 06:27:02 +00001631
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001632 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), "",
1633 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001634}
1635
Roman Gareevb3224ad2016-09-14 06:26:09 +00001636ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1637 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1638 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1639 R(nullptr), Build(nullptr) {
1640 BaseName = getIslCompatibleName("CopyStmt_", "",
1641 std::to_string(parent.getCopyStmtsNum()));
1642 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1643 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1644 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1645 auto *Access =
1646 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1647 parent.addAccessFunction(Access);
1648 addAccess(Access);
1649 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1650 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1651 parent.addAccessFunction(Access);
1652 addAccess(Access);
1653}
1654
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001655void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001656 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001657
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001658 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001659 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001660 buildAccessRelations();
1661
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001662 if (DetectReductions)
1663 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001664}
1665
Tobias Grosserc80d6972016-09-02 06:33:33 +00001666/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001667///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001668/// Check if the stored value for @p StoreMA is a binary operator with one or
1669/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001670/// used only once (by @p StoreMA) and its load operands are also used only
1671/// once, we have found a possible reduction chain. It starts at an operand
1672/// load and includes the binary operator and @p StoreMA.
1673///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001674/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001675/// escape this block or into any other store except @p StoreMA.
1676void ScopStmt::collectCandiateReductionLoads(
1677 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1678 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1679 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001680 return;
1681
1682 // Skip if there is not one binary operator between the load and the store
1683 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001684 if (!BinOp)
1685 return;
1686
1687 // Skip if the binary operators has multiple uses
1688 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001689 return;
1690
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001691 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001692 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1693 return;
1694
Johannes Doerfert9890a052014-07-01 00:32:29 +00001695 // Skip if the binary operator is outside the current SCoP
1696 if (BinOp->getParent() != Store->getParent())
1697 return;
1698
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001699 // Skip if it is a multiplicative reduction and we disabled them
1700 if (DisableMultiplicativeReductions &&
1701 (BinOp->getOpcode() == Instruction::Mul ||
1702 BinOp->getOpcode() == Instruction::FMul))
1703 return;
1704
Johannes Doerferte58a0122014-06-27 20:31:28 +00001705 // Check the binary operator operands for a candidate load
1706 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1707 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1708 if (!PossibleLoad0 && !PossibleLoad1)
1709 return;
1710
1711 // A load is only a candidate if it cannot escape (thus has only this use)
1712 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001713 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001714 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001715 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001716 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001717 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001718}
1719
Tobias Grosserc80d6972016-09-02 06:33:33 +00001720/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001721///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001722/// Iterate over all store memory accesses and check for valid binary reduction
1723/// like chains. For all candidates we check if they have the same base address
1724/// and there are no other accesses which overlap with them. The base address
1725/// check rules out impossible reductions candidates early. The overlap check,
1726/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001727/// guarantees that none of the intermediate results will escape during
1728/// execution of the loop nest. We basically check here that no other memory
1729/// access can access the same memory as the potential reduction.
1730void ScopStmt::checkForReductions() {
1731 SmallVector<MemoryAccess *, 2> Loads;
1732 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1733
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001734 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001735 // stores and collecting possible reduction loads.
1736 for (MemoryAccess *StoreMA : MemAccs) {
1737 if (StoreMA->isRead())
1738 continue;
1739
1740 Loads.clear();
1741 collectCandiateReductionLoads(StoreMA, Loads);
1742 for (MemoryAccess *LoadMA : Loads)
1743 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1744 }
1745
1746 // Then check each possible candidate pair.
1747 for (const auto &CandidatePair : Candidates) {
1748 bool Valid = true;
1749 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1750 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1751
1752 // Skip those with obviously unequal base addresses.
1753 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1754 isl_map_free(LoadAccs);
1755 isl_map_free(StoreAccs);
1756 continue;
1757 }
1758
1759 // And check if the remaining for overlap with other memory accesses.
1760 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1761 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1762 isl_set *AllAccs = isl_map_range(AllAccsRel);
1763
1764 for (MemoryAccess *MA : MemAccs) {
1765 if (MA == CandidatePair.first || MA == CandidatePair.second)
1766 continue;
1767
1768 isl_map *AccRel =
1769 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1770 isl_set *Accs = isl_map_range(AccRel);
1771
Tobias Grosser55a7af72016-09-08 14:08:07 +00001772 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001773 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1774 Valid = Valid && isl_set_is_empty(OverlapAccs);
1775 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001776 } else {
1777 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001778 }
1779 }
1780
1781 isl_set_free(AllAccs);
1782 if (!Valid)
1783 continue;
1784
Johannes Doerfertf6183392014-07-01 20:52:51 +00001785 const LoadInst *Load =
1786 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1787 MemoryAccess::ReductionType RT =
1788 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1789
Johannes Doerferte58a0122014-06-27 20:31:28 +00001790 // If no overlapping access was found we mark the load and store as
1791 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001792 CandidatePair.first->markAsReductionLike(RT);
1793 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001794 }
Tobias Grosser75805372011-04-29 06:27:02 +00001795}
1796
Tobias Grosser74394f02013-01-14 22:40:23 +00001797std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001798
Tobias Grosser54839312015-04-21 11:37:25 +00001799std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001800 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001801 if (!S)
1802 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001803 auto Str = stringFromIslObj(S);
1804 isl_map_free(S);
1805 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001806}
1807
Johannes Doerferta3519512016-04-23 13:02:23 +00001808void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1809 isl_set_free(InvalidDomain);
1810 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001811}
1812
Michael Kruse375cb5f2016-02-24 22:08:24 +00001813BasicBlock *ScopStmt::getEntryBlock() const {
1814 if (isBlockStmt())
1815 return getBasicBlock();
1816 return getRegion()->getEntry();
1817}
1818
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001819unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001820
Tobias Grosser75805372011-04-29 06:27:02 +00001821const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1822
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001823Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001824 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001825}
1826
Tobias Grosser74394f02013-01-14 22:40:23 +00001827isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001828
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001829__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001830
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001831__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001832 return isl_set_get_space(Domain);
1833}
1834
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001835__isl_give isl_id *ScopStmt::getDomainId() const {
1836 return isl_set_get_tuple_id(Domain);
1837}
Tobias Grossercd95b772012-08-30 11:49:38 +00001838
Johannes Doerfert7c013572016-04-12 09:57:34 +00001839ScopStmt::~ScopStmt() {
1840 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001841 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001842}
Tobias Grosser75805372011-04-29 06:27:02 +00001843
1844void ScopStmt::print(raw_ostream &OS) const {
1845 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001846 OS.indent(12) << "Domain :=\n";
1847
1848 if (Domain) {
1849 OS.indent(16) << getDomainStr() << ";\n";
1850 } else
1851 OS.indent(16) << "n/a\n";
1852
Tobias Grosser54839312015-04-21 11:37:25 +00001853 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001854
1855 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001856 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001857 } else
1858 OS.indent(16) << "n/a\n";
1859
Tobias Grosser083d3d32014-06-28 08:59:45 +00001860 for (MemoryAccess *Access : MemAccs)
1861 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001862}
1863
1864void ScopStmt::dump() const { print(dbgs()); }
1865
Michael Krusee60eca72017-05-11 22:56:12 +00001866void ScopStmt::removeAccessData(MemoryAccess *MA) {
1867 if (MA->isRead() && MA->isOriginalValueKind()) {
1868 bool Found = ValueReads.erase(MA->getAccessValue());
1869 (void)Found;
1870 assert(Found && "Expected access data not found");
1871 }
1872 if (MA->isWrite() && MA->isOriginalValueKind()) {
1873 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1874 (void)Found;
1875 assert(Found && "Expected access data not found");
1876 }
1877 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1878 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1879 (void)Found;
1880 assert(Found && "Expected access data not found");
1881 }
1882}
1883
Michael Kruse10071822016-05-23 14:45:58 +00001884void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001885 // Remove the memory accesses from this statement together with all scalar
1886 // accesses that were caused by it. MemoryKind::Value READs have no access
1887 // instruction, hence would not be removed by this function. However, it is
1888 // only used for invariant LoadInst accesses, its arguments are always affine,
1889 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1890 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001891 auto Predicate = [&](MemoryAccess *Acc) {
1892 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1893 };
Michael Krusee60eca72017-05-11 22:56:12 +00001894 for (auto *MA : MemAccs) {
1895 if (Predicate(MA))
1896 removeAccessData(MA);
1897 }
Michael Kruse10071822016-05-23 14:45:58 +00001898 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1899 MemAccs.end());
1900 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001901}
1902
Michael Kruse0446d812017-03-10 16:05:24 +00001903void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
1904 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1905 assert(MAIt != MemAccs.end());
1906 MemAccs.erase(MAIt);
1907
Michael Krusee60eca72017-05-11 22:56:12 +00001908 removeAccessData(MA);
1909
Michael Kruse0446d812017-03-10 16:05:24 +00001910 auto It = InstructionToAccess.find(MA->getAccessInstruction());
1911 if (It != InstructionToAccess.end()) {
1912 It->second.remove(MA);
1913 if (It->second.empty())
1914 InstructionToAccess.erase(MA->getAccessInstruction());
1915 }
1916}
1917
Tobias Grosser75805372011-04-29 06:27:02 +00001918//===----------------------------------------------------------------------===//
1919/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001920
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001921void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001922 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1923 isl_set_free(Context);
1924 Context = NewContext;
1925}
1926
Tobias Grosserc80d6972016-09-02 06:33:33 +00001927/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001928struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001929 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001930 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001931
1932public:
1933 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001934 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001935
1936 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1937 ValueToValueMap &VMap) {
1938 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1939 return SSPR.visit(E);
1940 }
1941
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001942 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1943 auto *Start = visit(E->getStart());
1944 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1945 visit(E->getStepRecurrence(SE)),
1946 E->getLoop(), SCEV::FlagAnyWrap);
1947 return SE.getAddExpr(Start, AddRec);
1948 }
1949
1950 const SCEV *visitUnknown(const SCEVUnknown *E) {
1951 if (auto *NewValue = VMap.lookup(E->getValue()))
1952 return SE.getUnknown(NewValue);
1953 return E;
1954 }
1955};
1956
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001957const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001958 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001959}
1960
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001961void Scop::createParameterId(const SCEV *Parameter) {
1962 assert(Parameters.count(Parameter));
1963 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001964
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001965 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001966
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001967 if (UseInstructionNames) {
1968 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1969 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001970
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001971 // If this parameter references a specific Value and this value has a name
1972 // we use this name as it is likely to be unique and more useful than just
1973 // a number.
1974 if (Val->hasName())
1975 ParameterName = Val->getName();
1976 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1977 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1978 if (LoadOrigin->hasName()) {
1979 ParameterName += "_loaded_from_";
1980 ParameterName +=
1981 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1982 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001983 }
1984 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001985
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001986 ParameterName = getIslCompatibleName("", ParameterName, "");
1987 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001988
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001989 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1990 const_cast<void *>((const void *)Parameter));
1991 ParameterIds[Parameter] = Id;
1992}
1993
1994void Scop::addParams(const ParameterSetTy &NewParameters) {
1995 for (const SCEV *Parameter : NewParameters) {
1996 // Normalize the SCEV to get the representing element for an invariant load.
1997 Parameter = extractConstantFactor(Parameter, *SE).second;
1998 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1999
2000 if (Parameters.insert(Parameter))
2001 createParameterId(Parameter);
2002 }
2003}
2004
2005__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
2006 // Normalize the SCEV to get the representing element for an invariant load.
2007 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2008 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00002009}
Tobias Grosser75805372011-04-29 06:27:02 +00002010
Michael Krused56b90a2016-09-01 09:03:27 +00002011__isl_give isl_set *
2012Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002013 isl_set *DomainContext = isl_union_set_params(getDomains());
2014 return isl_set_intersect_params(C, DomainContext);
2015}
2016
Johannes Doerferte0b08072016-05-23 12:43:44 +00002017bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2018 return DT.dominates(BB, getEntry());
2019}
2020
Michael Kruse89b1f942017-03-17 13:56:53 +00002021void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
2022 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002023 auto &F = getFunction();
Michael Kruse89b1f942017-03-17 13:56:53 +00002024 for (auto &Assumption : AC.assumptions()) {
2025 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2026 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002027 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002028
Michael Kruse89b1f942017-03-17 13:56:53 +00002029 bool InScop = contains(CI);
2030 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2031 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002032
Michael Kruse89b1f942017-03-17 13:56:53 +00002033 auto *L = LI.getLoopFor(CI->getParent());
2034 auto *Val = CI->getArgOperand(0);
2035 ParameterSetTy DetectedParams;
2036 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
2037 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
2038 CI->getDebugLoc(),
2039 "Non-affine user assumption ignored.");
2040 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002041 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002042
2043 // Collect all newly introduced parameters.
2044 ParameterSetTy NewParams;
2045 for (auto *Param : DetectedParams) {
2046 Param = extractConstantFactor(Param, *SE).second;
2047 Param = getRepresentingInvariantLoadSCEV(Param);
2048 if (Parameters.count(Param))
2049 continue;
2050 NewParams.insert(Param);
2051 }
2052
2053 SmallVector<isl_set *, 2> ConditionSets;
2054 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
2055 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
2056 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
2057 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
2058 isl_set_free(Dom);
2059
2060 if (!Valid)
2061 continue;
2062
2063 isl_set *AssumptionCtx = nullptr;
2064 if (InScop) {
2065 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2066 isl_set_free(ConditionSets[0]);
2067 } else {
2068 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2069 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2070 }
2071
2072 // Project out newly introduced parameters as they are not otherwise useful.
2073 if (!NewParams.empty()) {
2074 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2075 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2076 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2077 isl_id_free(Id);
2078
2079 if (!NewParams.count(Param))
2080 continue;
2081
2082 AssumptionCtx =
2083 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2084 }
2085 }
2086
2087 emitOptimizationRemarkAnalysis(
2088 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
2089 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
2090 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002091 }
2092}
2093
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002094void Scop::addUserContext() {
2095 if (UserContextStr.empty())
2096 return;
2097
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002098 isl_set *UserContext =
2099 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002100 isl_space *Space = getParamSpace();
2101 if (isl_space_dim(Space, isl_dim_param) !=
2102 isl_set_dim(UserContext, isl_dim_param)) {
2103 auto SpaceStr = isl_space_to_str(Space);
2104 errs() << "Error: the context provided in -polly-context has not the same "
2105 << "number of dimensions than the computed context. Due to this "
2106 << "mismatch, the -polly-context option is ignored. Please provide "
2107 << "the context in the parameter space: " << SpaceStr << ".\n";
2108 free(SpaceStr);
2109 isl_set_free(UserContext);
2110 isl_space_free(Space);
2111 return;
2112 }
2113
2114 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002115 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2116 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002117
2118 if (strcmp(NameContext, NameUserContext) != 0) {
2119 auto SpaceStr = isl_space_to_str(Space);
2120 errs() << "Error: the name of dimension " << i
2121 << " provided in -polly-context "
2122 << "is '" << NameUserContext << "', but the name in the computed "
2123 << "context is '" << NameContext
2124 << "'. Due to this name mismatch, "
2125 << "the -polly-context option is ignored. Please provide "
2126 << "the context in the parameter space: " << SpaceStr << ".\n";
2127 free(SpaceStr);
2128 isl_set_free(UserContext);
2129 isl_space_free(Space);
2130 return;
2131 }
2132
2133 UserContext =
2134 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2135 isl_space_get_dim_id(Space, isl_dim_param, i));
2136 }
2137
2138 Context = isl_set_intersect(Context, UserContext);
2139 isl_space_free(Space);
2140}
2141
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002142void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002143 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002144
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002145 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002146 for (LoadInst *LInst : RIL) {
2147 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2148
Johannes Doerfert96e54712016-02-07 17:30:13 +00002149 Type *Ty = LInst->getType();
2150 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002151 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002152 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002153 continue;
2154 }
2155
2156 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002157 InvariantEquivClasses.emplace_back(
2158 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002159 }
2160}
2161
Tobias Grosser6be480c2011-11-08 15:41:13 +00002162void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002163 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002164 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002165 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002166 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002167}
2168
Tobias Grosser18daaca2012-05-22 10:47:27 +00002169void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002170 unsigned PDim = 0;
2171 for (auto *Parameter : Parameters) {
2172 ConstantRange SRange = SE->getSignedRange(Parameter);
2173 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002174 }
2175}
2176
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002177void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002178 if (PollyIgnoreParamBounds)
2179 return;
2180
Tobias Grosser6be480c2011-11-08 15:41:13 +00002181 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002182 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002183
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002184 unsigned PDim = 0;
2185 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002186 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002187 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002188 }
2189
2190 // Align the parameters of all data structures to the model.
2191 Context = isl_set_align_params(Context, Space);
2192
Johannes Doerferta60ad842016-05-10 12:18:22 +00002193 // As all parameters are known add bounds to them.
2194 addParameterBounds();
2195
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002196 for (ScopStmt &Stmt : *this)
2197 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002198
2199 // Simplify the schedule according to the context too.
2200 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002201}
2202
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002203static __isl_give isl_set *
2204simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2205 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002206 // If we have modeled all blocks in the SCoP that have side effects we can
2207 // simplify the context with the constraints that are needed for anything to
2208 // be executed at all. However, if we have error blocks in the SCoP we already
2209 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002210 // domains, thus we cannot use the remaining domain to simplify the
2211 // assumptions.
2212 if (!S.hasErrorBlock()) {
2213 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2214 AssumptionContext =
2215 isl_set_gist_params(AssumptionContext, DomainParameters);
2216 }
2217
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002218 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2219 return AssumptionContext;
2220}
2221
2222void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002223 // The parameter constraints of the iteration domains give us a set of
2224 // constraints that need to hold for all cases where at least a single
2225 // statement iteration is executed in the whole scop. We now simplify the
2226 // assumed context under the assumption that such constraints hold and at
2227 // least a single statement iteration is executed. For cases where no
2228 // statement instances are executed, the assumptions we have taken about
2229 // the executed code do not matter and can be changed.
2230 //
2231 // WARNING: This only holds if the assumptions we have taken do not reduce
2232 // the set of statement instances that are executed. Otherwise we
2233 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002234 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002235 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002236 // performed. In such a case, modifying the run-time conditions and
2237 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002238 // to not be executed.
2239 //
2240 // Example:
2241 //
2242 // When delinearizing the following code:
2243 //
2244 // for (long i = 0; i < 100; i++)
2245 // for (long j = 0; j < m; j++)
2246 // A[i+p][j] = 1.0;
2247 //
2248 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002249 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002250 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002251 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002252 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002253}
2254
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002255struct MinMaxData {
2256 Scop::MinMaxVectorTy &MinMaxAccesses;
2257 Scop &S;
2258};
2259
Tobias Grosserc80d6972016-09-02 06:33:33 +00002260/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002261static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002262 auto Data = (struct MinMaxData *)User;
2263 Scop::MinMaxVectorTy *MinMaxAccesses = &Data->MinMaxAccesses;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002264 isl_pw_multi_aff *MinPMA, *MaxPMA;
2265 isl_pw_aff *LastDimAff;
2266 isl_aff *OneAff;
2267 unsigned Pos;
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002268 isl_ctx *Ctx = isl_set_get_ctx(Set);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002269
Johannes Doerfert6296d952016-04-22 11:38:19 +00002270 Set = isl_set_remove_divs(Set);
2271
Tobias Grosser90411a92017-02-16 19:11:33 +00002272 if (isl_set_n_basic_set(Set) >= MaxDisjunctsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002273 isl_set_free(Set);
2274 return isl_stat_error;
2275 }
2276
Johannes Doerfert9143d672014-09-27 11:02:39 +00002277 // Restrict the number of parameters involved in the access as the lexmin/
2278 // lexmax computation will take too long if this number is high.
2279 //
2280 // Experiments with a simple test case using an i7 4800MQ:
2281 //
2282 // #Parameters involved | Time (in sec)
2283 // 6 | 0.01
2284 // 7 | 0.04
2285 // 8 | 0.12
2286 // 9 | 0.40
2287 // 10 | 1.54
2288 // 11 | 6.78
2289 // 12 | 30.38
2290 //
2291 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2292 unsigned InvolvedParams = 0;
2293 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2294 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2295 InvolvedParams++;
2296
2297 if (InvolvedParams > RunTimeChecksMaxParameters) {
2298 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002299 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002300 }
2301 }
2302
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002303 {
2304 IslMaxOperationsGuard MaxOpGuard(isl_set_get_ctx(Set), OptComputeOut);
2305 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2306 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2307 }
2308
2309 if (isl_ctx_last_error(Ctx) == isl_error_quota) {
2310 MinPMA = isl_pw_multi_aff_free(MinPMA);
2311 MaxPMA = isl_pw_multi_aff_free(MaxPMA);
2312 Set = isl_set_free(Set);
2313 Data->S.invalidate(COMPLEXITY, DebugLoc());
2314 return isl_stat_error;
2315 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002316
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002317 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2318 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2319
Johannes Doerfertb164c792014-09-18 11:17:17 +00002320 // Adjust the last dimension of the maximal access by one as we want to
2321 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2322 // we test during code generation might now point after the end of the
2323 // allocated array but we will never dereference it anyway.
2324 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2325 "Assumed at least one output dimension");
2326 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2327 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2328 OneAff = isl_aff_zero_on_domain(
2329 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2330 OneAff = isl_aff_add_constant_si(OneAff, 1);
2331 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2332 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2333
2334 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2335
2336 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002337 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002338}
2339
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002340static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2341 isl_set *Domain = MA->getStatement()->getDomain();
2342 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2343 return isl_set_reset_tuple_id(Domain);
2344}
2345
Tobias Grosserc80d6972016-09-02 06:33:33 +00002346/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002347static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002348 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002349
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002350 struct MinMaxData Data = {MinMaxAccesses, S};
2351 Data.MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002352
2353 isl_union_set *Domains = S.getDomains();
2354 isl_union_map *Accesses = isl_union_map_empty(S.getParamSpace());
2355
2356 for (MemoryAccess *MA : AliasGroup)
2357 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2358
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002359 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2360 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002361 Locations = isl_union_set_coalesce(Locations);
2362 Locations = isl_union_set_detect_equalities(Locations);
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002363 bool Valid =
2364 (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess, &Data));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002365 isl_union_set_free(Locations);
2366 return Valid;
2367}
2368
Tobias Grosserc80d6972016-09-02 06:33:33 +00002369/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002370///
2371///{
2372
Tobias Grosserc80d6972016-09-02 06:33:33 +00002373/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002374static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2375 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2376 : RN->getNodeAs<BasicBlock>();
2377}
2378
Tobias Grosserc80d6972016-09-02 06:33:33 +00002379/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002380static inline BasicBlock *
2381getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002382 if (RN->isSubRegion()) {
2383 assert(idx == 0);
2384 return RN->getNodeAs<Region>()->getExit();
2385 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002386 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002387}
2388
Tobias Grosserc80d6972016-09-02 06:33:33 +00002389/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002390static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002391 if (!RN->isSubRegion()) {
2392 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2393 Loop *L = LI.getLoopFor(BB);
2394
2395 // Unreachable statements are not considered to belong to a LLVM loop, as
2396 // they are not part of an actual loop in the control flow graph.
2397 // Nevertheless, we handle certain unreachable statements that are common
2398 // when modeling run-time bounds checks as being part of the loop to be
2399 // able to model them and to later eliminate the run-time bounds checks.
2400 //
2401 // Specifically, for basic blocks that terminate in an unreachable and
2402 // where the immeditate predecessor is part of a loop, we assume these
2403 // basic blocks belong to the loop the predecessor belongs to. This
2404 // allows us to model the following code.
2405 //
2406 // for (i = 0; i < N; i++) {
2407 // if (i > 1024)
2408 // abort(); <- this abort might be translated to an
2409 // unreachable
2410 //
2411 // A[i] = ...
2412 // }
2413 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2414 L = LI.getLoopFor(BB->getPrevNode());
2415 return L;
2416 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002417
2418 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2419 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2420 while (L && NonAffineSubRegion->contains(L))
2421 L = L->getParentLoop();
2422 return L;
2423}
2424
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002425/// Get the number of blocks in @p L.
2426///
2427/// The number of blocks in a loop are the number of basic blocks actually
2428/// belonging to the loop, as well as all single basic blocks that the loop
2429/// exits to and which terminate in an unreachable instruction. We do not
2430/// allow such basic blocks in the exit of a scop, hence they belong to the
2431/// scop and represent run-time conditions which we want to model and
2432/// subsequently speculate away.
2433///
2434/// @see getRegionNodeLoop for additional details.
2435long getNumBlocksInLoop(Loop *L) {
2436 long NumBlocks = L->getNumBlocks();
2437 SmallVector<llvm::BasicBlock *, 4> ExitBlocks;
2438 L->getExitBlocks(ExitBlocks);
2439
2440 for (auto ExitBlock : ExitBlocks) {
2441 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2442 NumBlocks++;
2443 }
2444 return NumBlocks;
2445}
2446
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002447static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2448 if (!RN->isSubRegion())
2449 return 1;
2450
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002451 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002452 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002453}
2454
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002455static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2456 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002457 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002458 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002459 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002460 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002461 return true;
2462 return false;
2463}
2464
Johannes Doerfert96425c22015-08-30 21:13:53 +00002465///}
2466
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002467static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2468 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002469 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002470 isl_id *DimId =
2471 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2472 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2473}
2474
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002475__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002476 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002477}
2478
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002479__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002480 auto DIt = DomainMap.find(BB);
2481 if (DIt != DomainMap.end())
2482 return isl_set_copy(DIt->getSecond());
2483
2484 auto &RI = *R.getRegionInfo();
2485 auto *BBR = RI.getRegionFor(BB);
2486 while (BBR->getEntry() == BB)
2487 BBR = BBR->getParent();
2488 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002489}
2490
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002491bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002492
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002493 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002494 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002495 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2496 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002497 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002498
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002499 while (LD-- >= 0) {
2500 S = addDomainDimId(S, LD + 1, L);
2501 L = L->getParentLoop();
2502 }
2503
Johannes Doerferta3519512016-04-23 13:02:23 +00002504 // Initialize the invalid domain.
2505 auto *EntryStmt = getStmtFor(EntryBB);
2506 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2507
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002508 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002509
Johannes Doerfert432658d2016-01-26 11:01:41 +00002510 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002511 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002512
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002513 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002514 return false;
2515
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002516 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002517 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002518
2519 // Error blocks and blocks dominated by them have been assumed to never be
2520 // executed. Representing them in the Scop does not add any value. In fact,
2521 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002522 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002523 // will cause problems when building up a ScopStmt for them.
2524 // Furthermore, basic blocks dominated by error blocks may reference
2525 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002526 // can themselves not be constructed properly. To this end we will replace
2527 // the domains of error blocks and those only reachable via error blocks
2528 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002529 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002530 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002531 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002532 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002533
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002534 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002535}
2536
Tobias Grosserc80d6972016-09-02 06:33:33 +00002537/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002538/// to be compatible to domains constructed for loop @p NewL.
2539///
2540/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2541/// edge from @p OldL to @p NewL.
2542static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2543 __isl_take isl_set *Dom,
2544 Loop *OldL, Loop *NewL) {
2545
2546 // If the loops are the same there is nothing to do.
2547 if (NewL == OldL)
2548 return Dom;
2549
2550 int OldDepth = S.getRelativeLoopDepth(OldL);
2551 int NewDepth = S.getRelativeLoopDepth(NewL);
2552 // If both loops are non-affine loops there is nothing to do.
2553 if (OldDepth == -1 && NewDepth == -1)
2554 return Dom;
2555
2556 // Distinguish three cases:
2557 // 1) The depth is the same but the loops are not.
2558 // => One loop was left one was entered.
2559 // 2) The depth increased from OldL to NewL.
2560 // => One loop was entered, none was left.
2561 // 3) The depth decreased from OldL to NewL.
2562 // => Loops were left were difference of the depths defines how many.
2563 if (OldDepth == NewDepth) {
2564 assert(OldL->getParentLoop() == NewL->getParentLoop());
2565 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2566 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2567 Dom = addDomainDimId(Dom, NewDepth, NewL);
2568 } else if (OldDepth < NewDepth) {
2569 assert(OldDepth + 1 == NewDepth);
2570 auto &R = S.getRegion();
2571 (void)R;
2572 assert(NewL->getParentLoop() == OldL ||
2573 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2574 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2575 Dom = addDomainDimId(Dom, NewDepth, NewL);
2576 } else {
2577 assert(OldDepth > NewDepth);
2578 int Diff = OldDepth - NewDepth;
2579 int NumDim = isl_set_n_dim(Dom);
2580 assert(NumDim >= Diff);
2581 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2582 }
2583
2584 return Dom;
2585}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002586
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002587bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2588 LoopInfo &LI) {
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002589 ReversePostOrderTraversal<Region *> RTraversal(R);
2590 for (auto *RN : RTraversal) {
2591
2592 // Recurse for affine subregions but go on for basic blocks and non-affine
2593 // subregions.
2594 if (RN->isSubRegion()) {
2595 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002596 if (!isNonAffineSubRegion(SubRegion)) {
2597 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002598 continue;
2599 }
2600 }
2601
2602 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2603 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002604 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002605 isl_set *&Domain = DomainMap[BB];
2606 assert(Domain && "Cannot propagate a nullptr");
2607
Johannes Doerferta3519512016-04-23 13:02:23 +00002608 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002609 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002610 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002611
Johannes Doerferta3519512016-04-23 13:02:23 +00002612 if (!IsInvalidBlock) {
2613 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002614 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002615 isl_set_free(InvalidDomain);
2616 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002617 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2618 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2619 AS_RESTRICTION);
2620 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002621 }
2622
Johannes Doerferta3519512016-04-23 13:02:23 +00002623 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002624 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002625 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002626 }
2627
Johannes Doerferta3519512016-04-23 13:02:23 +00002628 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002629 auto *TI = BB->getTerminator();
2630 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2631 for (unsigned u = 0; u < NumSuccs; u++) {
2632 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002633 auto *SuccStmt = getStmtFor(SuccBB);
2634
2635 // Skip successors outside the SCoP.
2636 if (!SuccStmt)
2637 continue;
2638
Johannes Doerferte4459a22016-04-25 13:34:50 +00002639 // Skip backedges.
2640 if (DT.dominates(SuccBB, BB))
2641 continue;
2642
Michael Kruse55454072017-03-15 22:16:43 +00002643 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta3519512016-04-23 13:02:23 +00002644 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2645 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2646 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2647 SuccInvalidDomain =
2648 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2649 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2650 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2651 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002652
Michael Krusebc150122016-05-02 12:25:18 +00002653 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002654 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002655 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002656 continue;
2657
Johannes Doerferta3519512016-04-23 13:02:23 +00002658 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002659 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002660 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002661 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002662
2663 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002664 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002665
2666 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002667}
2668
Johannes Doerfert642594a2016-04-04 07:57:39 +00002669void Scop::propagateDomainConstraintsToRegionExit(
2670 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002671 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002672
2673 // Check if the block @p BB is the entry of a region. If so we propagate it's
2674 // domain to the exit block of the region. Otherwise we are done.
2675 auto *RI = R.getRegionInfo();
2676 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2677 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002678 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002679 return;
2680
Johannes Doerfert642594a2016-04-04 07:57:39 +00002681 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002682 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002683 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002684 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002685 SmallVector<BasicBlock *, 4> LatchBBs;
2686 BBLoop->getLoopLatches(LatchBBs);
2687 for (auto *LatchBB : LatchBBs)
2688 if (BB != LatchBB && BBReg->contains(LatchBB))
2689 return;
2690 L = L->getParentLoop();
2691 }
2692
2693 auto *Domain = DomainMap[BB];
2694 assert(Domain && "Cannot propagate a nullptr");
2695
Michael Kruse55454072017-03-15 22:16:43 +00002696 auto *ExitStmt = getStmtFor(ExitBB);
2697 auto *ExitBBLoop = ExitStmt->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002698
2699 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2700 // adjust the domain before we can propagate it.
2701 auto *AdjustedDomain =
2702 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2703 auto *&ExitDomain = DomainMap[ExitBB];
2704
2705 // If the exit domain is not yet created we set it otherwise we "add" the
2706 // current domain.
2707 ExitDomain =
2708 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2709
Johannes Doerferta3519512016-04-23 13:02:23 +00002710 // Initialize the invalid domain.
Johannes Doerferta3519512016-04-23 13:02:23 +00002711 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2712
Johannes Doerfert642594a2016-04-04 07:57:39 +00002713 FinishedExitBlocks.insert(ExitBB);
2714}
2715
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002716bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2717 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002718 // To create the domain for each block in R we iterate over all blocks and
2719 // subregions in R and propagate the conditions under which the current region
2720 // element is executed. To this end we iterate in reverse post order over R as
2721 // it ensures that we first visit all predecessors of a region node (either a
2722 // basic block or a subregion) before we visit the region node itself.
2723 // Initially, only the domain for the SCoP region entry block is set and from
2724 // there we propagate the current domain to all successors, however we add the
2725 // condition that the successor is actually executed next.
2726 // As we are only interested in non-loop carried constraints here we can
2727 // simply skip loop back edges.
2728
Johannes Doerfert642594a2016-04-04 07:57:39 +00002729 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002730 ReversePostOrderTraversal<Region *> RTraversal(R);
2731 for (auto *RN : RTraversal) {
2732
2733 // Recurse for affine subregions but go on for basic blocks and non-affine
2734 // subregions.
2735 if (RN->isSubRegion()) {
2736 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002737 if (!isNonAffineSubRegion(SubRegion)) {
2738 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002739 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002740 continue;
2741 }
2742 }
2743
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002744 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002745 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002746
Johannes Doerfert96425c22015-08-30 21:13:53 +00002747 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002748 TerminatorInst *TI = BB->getTerminator();
2749
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002750 if (isa<UnreachableInst>(TI))
2751 continue;
2752
Johannes Doerfertf5673802015-10-01 23:48:18 +00002753 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002754 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002755 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002756 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002757
Johannes Doerfert642594a2016-04-04 07:57:39 +00002758 auto *BBLoop = getRegionNodeLoop(RN, LI);
2759 // Propagate the domain from BB directly to blocks that have a superset
2760 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002761 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002762
2763 // If all successors of BB have been set a domain through the propagation
2764 // above we do not need to build condition sets but can just skip this
2765 // block. However, it is important to note that this is a local property
2766 // with regards to the region @p R. To this end FinishedExitBlocks is a
2767 // local variable.
2768 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2769 return FinishedExitBlocks.count(SuccBB);
2770 };
2771 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2772 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002773
2774 // Build the condition sets for the successor nodes of the current region
2775 // node. If it is a non-affine subregion we will always execute the single
2776 // exit node, hence the single entry node domain is the condition set. For
2777 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002778 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002779 if (RN->isSubRegion())
2780 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002781 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2782 ConditionSets))
2783 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002784
2785 // Now iterate over the successors and set their initial domain based on
2786 // their condition set. We skip back edges here and have to be careful when
2787 // we leave a loop not to keep constraints over a dimension that doesn't
2788 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002789 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002790 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002791 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002792 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002793
Johannes Doerfert535de032016-04-19 14:49:05 +00002794 auto *SuccStmt = getStmtFor(SuccBB);
2795 // Skip blocks outside the region.
2796 if (!SuccStmt) {
2797 isl_set_free(CondSet);
2798 continue;
2799 }
2800
Johannes Doerfert642594a2016-04-04 07:57:39 +00002801 // If we propagate the domain of some block to "SuccBB" we do not have to
2802 // adjust the domain.
2803 if (FinishedExitBlocks.count(SuccBB)) {
2804 isl_set_free(CondSet);
2805 continue;
2806 }
2807
Johannes Doerfert96425c22015-08-30 21:13:53 +00002808 // Skip back edges.
2809 if (DT.dominates(SuccBB, BB)) {
2810 isl_set_free(CondSet);
2811 continue;
2812 }
2813
Michael Kruse55454072017-03-15 22:16:43 +00002814 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002815 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002816
2817 // Set the domain for the successor or merge it with an existing domain in
2818 // case there are multiple paths (without loop back edges) to the
2819 // successor block.
2820 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002821
Johannes Doerferta3519512016-04-23 13:02:23 +00002822 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002823 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002824 } else {
2825 // Initialize the invalid domain.
2826 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2827 SuccDomain = CondSet;
2828 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002829
Michael Krusebc150122016-05-02 12:25:18 +00002830 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002831 // In case this happens we will clean up and bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002832 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002833 continue;
2834
2835 invalidate(COMPLEXITY, DebugLoc());
2836 while (++u < ConditionSets.size())
2837 isl_set_free(ConditionSets[u]);
2838 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002839 }
2840 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002841
2842 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002843}
2844
Michael Krused56b90a2016-09-01 09:03:27 +00002845__isl_give isl_set *
2846Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2847 __isl_keep isl_set *Domain,
2848 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002849 // If @p BB is the ScopEntry we are done
2850 if (R.getEntry() == BB)
2851 return isl_set_universe(isl_set_get_space(Domain));
2852
Johannes Doerfert642594a2016-04-04 07:57:39 +00002853 // The region info of this function.
2854 auto &RI = *R.getRegionInfo();
2855
Michael Kruse55454072017-03-15 22:16:43 +00002856 auto *BBLoop = getStmtFor(BB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002857
2858 // A domain to collect all predecessor domains, thus all conditions under
2859 // which the block is executed. To this end we start with the empty domain.
2860 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2861
2862 // Set of regions of which the entry block domain has been propagated to BB.
2863 // all predecessors inside any of the regions can be skipped.
2864 SmallSet<Region *, 8> PropagatedRegions;
2865
2866 for (auto *PredBB : predecessors(BB)) {
2867 // Skip backedges.
2868 if (DT.dominates(BB, PredBB))
2869 continue;
2870
2871 // If the predecessor is in a region we used for propagation we can skip it.
2872 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2873 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2874 PredBBInRegion)) {
2875 continue;
2876 }
2877
2878 // Check if there is a valid region we can use for propagation, thus look
2879 // for a region that contains the predecessor and has @p BB as exit block.
2880 auto *PredR = RI.getRegionFor(PredBB);
2881 while (PredR->getExit() != BB && !PredR->contains(BB))
2882 PredR->getParent();
2883
2884 // If a valid region for propagation was found use the entry of that region
2885 // for propagation, otherwise the PredBB directly.
2886 if (PredR->getExit() == BB) {
2887 PredBB = PredR->getEntry();
2888 PropagatedRegions.insert(PredR);
2889 }
2890
Johannes Doerfert41cda152016-04-08 10:32:26 +00002891 auto *PredBBDom = getDomainConditions(PredBB);
Michael Kruse55454072017-03-15 22:16:43 +00002892 auto *PredBBLoop = getStmtFor(PredBB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002893 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2894
2895 PredDom = isl_set_union(PredDom, PredBBDom);
2896 }
2897
2898 return PredDom;
2899}
2900
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002901bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2902 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002903 // Iterate over the region R and propagate the domain constrains from the
2904 // predecessors to the current node. In contrast to the
2905 // buildDomainsWithBranchConstraints function, this one will pull the domain
2906 // information from the predecessors instead of pushing it to the successors.
2907 // Additionally, we assume the domains to be already present in the domain
2908 // map here. However, we iterate again in reverse post order so we know all
2909 // predecessors have been visited before a block or non-affine subregion is
2910 // visited.
2911
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002912 ReversePostOrderTraversal<Region *> RTraversal(R);
2913 for (auto *RN : RTraversal) {
2914
2915 // Recurse for affine subregions but go on for basic blocks and non-affine
2916 // subregions.
2917 if (RN->isSubRegion()) {
2918 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002919 if (!isNonAffineSubRegion(SubRegion)) {
2920 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002921 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002922 continue;
2923 }
2924 }
2925
2926 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002927 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002928 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002929
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002930 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002931 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002932 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002933 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002934
Johannes Doerfert642594a2016-04-04 07:57:39 +00002935 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002936 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002937 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2938 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002939 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002940
2941 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002942}
2943
Tobias Grosserc80d6972016-09-02 06:33:33 +00002944/// Create a map to map from a given iteration to a subsequent iteration.
2945///
2946/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2947/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002948/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002949///
2950/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002951static __isl_give isl_map *
2952createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2953 auto *MapSpace = isl_space_map_from_set(SetSpace);
2954 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00002955 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002956 if (u != Dim)
2957 NextIterationMap =
2958 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2959 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2960 C = isl_constraint_set_constant_si(C, 1);
2961 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2962 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2963 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2964 return NextIterationMap;
2965}
2966
Johannes Doerfert297c7202016-05-10 13:06:42 +00002967bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002968 int LoopDepth = getRelativeLoopDepth(L);
2969 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002970
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002971 BasicBlock *HeaderBB = L->getHeader();
2972 assert(DomainMap.count(HeaderBB));
2973 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002974
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002975 isl_map *NextIterationMap =
2976 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002977
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002978 isl_set *UnionBackedgeCondition =
2979 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002980
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002981 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2982 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002983
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002984 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002985
2986 // If the latch is only reachable via error statements we skip it.
2987 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2988 if (!LatchBBDom)
2989 continue;
2990
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002991 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002992
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002993 TerminatorInst *TI = LatchBB->getTerminator();
2994 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00002995 assert(BI && "Only branch instructions allowed in loop latches");
2996
2997 if (BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002998 BackedgeCondition = isl_set_copy(LatchBBDom);
2999 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003000 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003001 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00003002 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
Michael Krusee1dc3872016-11-03 15:19:41 +00003003 ConditionSets)) {
3004 isl_map_free(NextIterationMap);
3005 isl_set_free(UnionBackedgeCondition);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003006 return false;
Michael Krusee1dc3872016-11-03 15:19:41 +00003007 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003008
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003009 // Free the non back edge condition set as we do not need it.
3010 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003011
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003012 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003013 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003014
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003015 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3016 assert(LatchLoopDepth >= LoopDepth);
3017 BackedgeCondition =
3018 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
3019 LatchLoopDepth - LoopDepth);
3020 UnionBackedgeCondition =
3021 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003022 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003023
3024 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
3025 for (int i = 0; i < LoopDepth; i++)
3026 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
3027
3028 isl_set *UnionBackedgeConditionComplement =
3029 isl_set_complement(UnionBackedgeCondition);
3030 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
3031 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
3032 UnionBackedgeConditionComplement =
3033 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
3034 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
3035 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
3036
3037 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
3038 HeaderBBDom = Parts.second;
3039
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003040 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3041 // the bounded assumptions to the context as they are already implied by the
3042 // <nsw> tag.
3043 if (Affinator.hasNSWAddRecForLoop(L)) {
3044 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003045 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003046 }
3047
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003048 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003049 recordAssumption(INFINITELOOP, UnboundedCtx,
3050 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003051 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003052}
3053
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003054MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003055 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003056
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003057 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003058 if (!PointerBaseInst)
3059 return nullptr;
3060
3061 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3062 if (!BasePtrStmt)
3063 return nullptr;
3064
3065 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3066}
3067
3068bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
3069 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003070 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
3071 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
3072 bool Hoistable = NHCtx != nullptr;
3073 isl_set_free(NHCtx);
3074 return !Hoistable;
3075 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003076
Tobias Grosserbe372d52017-02-09 10:11:58 +00003077 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003078 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003079 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003080 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003081
3082 return false;
3083}
3084
Johannes Doerfert5210da52016-06-02 11:06:54 +00003085bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003086 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003087 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003088
Johannes Doerfertcd195322016-11-17 21:41:08 +00003089 if (buildAliasGroups(AA)) {
3090 // Aliasing assumptions do not go through addAssumption but we still want to
3091 // collect statistics so we do it here explicitly.
3092 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003093 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003094 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003095 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003096
3097 // If a problem occurs while building the alias groups we need to delete
3098 // this SCoP and pretend it wasn't valid in the first place. To this end
3099 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003100 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003101
3102 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3103 << " could not be created as the number of parameters involved "
3104 "is too high. The SCoP will be "
3105 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3106 "the maximal number of parameters but be advised that the "
3107 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003108 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003109}
3110
Tobias Grosser889830b2017-02-09 23:12:22 +00003111std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003112Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003113 AliasSetTracker AST(AA);
3114
3115 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003116 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003117 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003118
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003119 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003120 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3121 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003122
3123 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003124 if (StmtDomainEmpty)
3125 continue;
3126
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003127 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003128 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003129 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003130 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003131 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003132 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003133 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003134 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003135 else
3136 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003137 AST.add(Acc);
3138 }
3139 }
3140
Tobias Grosser9edcf072017-01-16 14:07:57 +00003141 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003142 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003143 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003144 continue;
3145 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003146 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003147 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003148 if (AG.size() < 2)
3149 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003150 AliasGroups.push_back(std::move(AG));
3151 }
3152
Tobias Grosser9edcf072017-01-16 14:07:57 +00003153 return std::make_tuple(AliasGroups, HasWriteAccess);
3154}
3155
Tobias Grossere39f9122017-01-16 14:08:00 +00003156void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003157 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3158 AliasGroupTy NewAG;
3159 AliasGroupTy &AG = AliasGroups[u];
3160 AliasGroupTy::iterator AGI = AG.begin();
3161 isl_set *AGDomain = getAccessDomain(*AGI);
3162 while (AGI != AG.end()) {
3163 MemoryAccess *MA = *AGI;
3164 isl_set *MADomain = getAccessDomain(MA);
3165 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3166 NewAG.push_back(MA);
3167 AGI = AG.erase(AGI);
3168 isl_set_free(MADomain);
3169 } else {
3170 AGDomain = isl_set_union(AGDomain, MADomain);
3171 AGI++;
3172 }
3173 }
3174 if (NewAG.size() > 1)
3175 AliasGroups.push_back(std::move(NewAG));
3176 isl_set_free(AGDomain);
3177 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003178}
3179
3180bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3181 // To create sound alias checks we perform the following steps:
3182 // o) We partition each group into read only and non read only accesses.
3183 // o) For each group with more than one base pointer we then compute minimal
3184 // and maximal accesses to each array of a group in read only and non
3185 // read only partitions separately.
3186 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003187 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003188
3189 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3190
3191 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003192
Johannes Doerfert13771732014-10-01 12:40:46 +00003193 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003194 bool Valid = buildAliasGroup(AG, HasWriteAccess);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003195 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003196 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003197 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003198
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003199 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003200}
3201
Tobias Grosser77f32572017-01-16 15:49:07 +00003202bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003203 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003204 AliasGroupTy ReadOnlyAccesses;
3205 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003206 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003207 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003208
3209 auto &F = getFunction();
3210
3211 if (AliasGroup.size() < 2)
3212 return true;
3213
3214 for (MemoryAccess *Access : AliasGroup) {
3215 emitOptimizationRemarkAnalysis(
3216 F.getContext(), DEBUG_TYPE, F,
3217 Access->getAccessInstruction()->getDebugLoc(),
3218 "Possibly aliasing pointer, use restrict keyword.");
3219
Tobias Grosser889830b2017-02-09 23:12:22 +00003220 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3221 if (HasWriteAccess.count(Array)) {
3222 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003223 ReadWriteAccesses.push_back(Access);
3224 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003225 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003226 ReadOnlyAccesses.push_back(Access);
3227 }
3228 }
3229
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003230 // If there are no read-only pointers, and less than two read-write pointers,
3231 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003232 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003233 return true;
3234
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003235 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003236 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003237 return true;
3238
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003239 // For non-affine accesses, no alias check can be generated as we cannot
3240 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003241 for (MemoryAccess *MA : AliasGroup) {
3242 if (!MA->isAffine()) {
3243 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3244 return false;
3245 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003246 }
3247
3248 // Ensure that for all memory accesses for which we generate alias checks,
3249 // their base pointers are available.
3250 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003251 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3252 addRequiredInvariantLoad(
3253 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3254 }
3255
3256 MinMaxAliasGroups.emplace_back();
3257 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3258 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3259 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3260
3261 bool Valid;
3262
3263 Valid =
3264 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3265
3266 if (!Valid)
3267 return false;
3268
3269 // Bail out if the number of values we need to compare is too large.
3270 // This is important as the number of comparisons grows quadratically with
3271 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003272 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003273 RunTimeChecksMaxArraysPerGroup)
3274 return false;
3275
3276 Valid =
3277 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3278
3279 if (!Valid)
3280 return false;
3281
3282 return true;
3283}
3284
Tobias Grosserc80d6972016-09-02 06:33:33 +00003285/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003286static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003287 // Start with the smallest loop containing the entry and expand that
3288 // loop until it contains all blocks in the region. If there is a loop
3289 // containing all blocks in the region check if it is itself contained
3290 // and if so take the parent loop as it will be the smallest containing
3291 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003292 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003293 while (L) {
3294 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003295 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003296 AllContained &= L->contains(BB);
3297 if (AllContained)
3298 break;
3299 L = L->getParentLoop();
3300 }
3301
Johannes Doerfertef744432016-05-23 12:42:38 +00003302 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003303}
3304
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003305Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003306 ScopDetection::DetectionContext &DC)
Philip Pfaffe35bdcaf2017-05-15 13:43:01 +00003307 : SE(&ScalarEvolution), R(R), name(R.getNameStr()), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003308 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003309 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3310 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3311 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3312 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003313 if (IslOnErrorAbort)
3314 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003315 buildContext();
3316}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003317
Tobias Grosserbedef002016-12-02 08:10:56 +00003318void Scop::foldSizeConstantsToRight() {
3319 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3320
3321 for (auto Array : arrays()) {
3322 if (Array->getNumberOfDimensions() <= 1)
3323 continue;
3324
3325 isl_space *Space = Array->getSpace();
3326
3327 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3328
3329 if (!isl_union_set_contains(Accessed, Space)) {
3330 isl_space_free(Space);
3331 continue;
3332 }
3333
3334 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3335
3336 isl_map *Transform =
3337 isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3338
3339 std::vector<int> Int;
3340
3341 int Dims = isl_set_dim(Elements, isl_dim_set);
3342 for (int i = 0; i < Dims; i++) {
3343 isl_set *DimOnly =
3344 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3345 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3346 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3347
3348 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3349
3350 if (i == Dims - 1) {
3351 Int.push_back(1);
3352 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3353 isl_basic_set_free(DimHull);
3354 continue;
3355 }
3356
3357 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3358 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3359 isl_val *Val = isl_aff_get_denominator_val(Diff);
3360 isl_aff_free(Diff);
3361
3362 int ValInt = 1;
3363
3364 if (isl_val_is_int(Val))
3365 ValInt = isl_val_get_num_si(Val);
3366 isl_val_free(Val);
3367
3368 Int.push_back(ValInt);
3369
3370 isl_constraint *C = isl_constraint_alloc_equality(
3371 isl_local_space_from_space(isl_map_get_space(Transform)));
3372 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3373 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3374 Transform = isl_map_add_constraint(Transform, C);
3375 isl_basic_set_free(DimHull);
3376 continue;
3377 }
3378
3379 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3380 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3381
3382 int ValInt = 1;
3383 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3384 ValInt = 0;
3385 }
3386
3387 Int.push_back(ValInt);
3388 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3389 isl_basic_set_free(DimHull);
3390 isl_basic_set_free(ZeroSet);
3391 }
3392
3393 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3394
3395 if (!isl_set_is_subset(Elements, MappedElements)) {
3396 isl_set_free(Elements);
3397 isl_set_free(MappedElements);
3398 isl_map_free(Transform);
3399 continue;
3400 }
3401
3402 isl_set_free(MappedElements);
3403
3404 bool CanFold = true;
3405
3406 if (Int[0] <= 1)
3407 CanFold = false;
3408
3409 unsigned NumDims = Array->getNumberOfDimensions();
3410 for (unsigned i = 1; i < NumDims - 1; i++)
3411 if (Int[0] != Int[i] && Int[i])
3412 CanFold = false;
3413
3414 if (!CanFold) {
3415 isl_set_free(Elements);
3416 isl_map_free(Transform);
3417 continue;
3418 }
3419
Tobias Grosserbedef002016-12-02 08:10:56 +00003420 for (auto &Access : AccessFunctions)
3421 if (Access->getScopArrayInfo() == Array)
3422 Access->setAccessRelation(isl_map_apply_range(
3423 Access->getAccessRelation(), isl_map_copy(Transform)));
3424
3425 isl_map_free(Transform);
3426
3427 std::vector<const SCEV *> Sizes;
3428 for (unsigned i = 0; i < NumDims; i++) {
3429 auto Size = Array->getDimensionSize(i);
3430
3431 if (i == NumDims - 1)
3432 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3433 Sizes.push_back(Size);
3434 }
3435
3436 Array->updateSizes(Sizes, false /* CheckConsistency */);
3437
3438 isl_set_free(Elements);
3439 }
3440 isl_union_set_free(Accessed);
3441 return;
3442}
3443
Tobias Grosser491b7992016-12-02 05:21:22 +00003444void Scop::finalizeAccesses() {
3445 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003446 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003447 foldAccessRelations();
3448 assumeNoOutOfBounds();
3449}
3450
Tobias Grosser75805372011-04-29 06:27:02 +00003451Scop::~Scop() {
3452 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003453 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003454 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003455 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003456
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003457 for (auto &It : ParameterIds)
3458 isl_id_free(It.second);
3459
Johannes Doerfert96425c22015-08-30 21:13:53 +00003460 for (auto It : DomainMap)
3461 isl_set_free(It.second);
3462
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003463 for (auto &AS : RecordedAssumptions)
3464 isl_set_free(AS.Set);
3465
Johannes Doerfertb164c792014-09-18 11:17:17 +00003466 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003467 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003468 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003469 isl_pw_multi_aff_free(MMA.first);
3470 isl_pw_multi_aff_free(MMA.second);
3471 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003472 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003473 isl_pw_multi_aff_free(MMA.first);
3474 isl_pw_multi_aff_free(MMA.second);
3475 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003476 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003477
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003478 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003479 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003480
3481 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003482 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003483 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003484 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003485 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003486 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003487 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003488}
3489
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003490void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003491 // Check all array accesses for each base pointer and find a (virtual) element
3492 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003493 for (ScopStmt &Stmt : *this)
3494 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003495 if (!Access->isArrayKind())
3496 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003497 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003498 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3499
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003500 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003501 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003502 unsigned DivisibleSize = Array->getElemSizeInBytes();
3503 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003504 while (!isDivisible(Subscript, DivisibleSize, *SE))
3505 DivisibleSize /= 2;
3506 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003507 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003508 }
3509
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003510 for (auto &Stmt : *this)
3511 for (auto &Access : Stmt)
3512 Access->updateDimensionality();
3513}
3514
Tobias Grosser491b7992016-12-02 05:21:22 +00003515void Scop::foldAccessRelations() {
3516 for (auto &Stmt : *this)
3517 for (auto &Access : Stmt)
3518 Access->foldAccessRelation();
3519}
3520
3521void Scop::assumeNoOutOfBounds() {
3522 for (auto &Stmt : *this)
3523 for (auto &Access : Stmt)
3524 Access->assumeNoOutOfBound();
3525}
3526
Michael Kruse977d38b2016-07-22 17:31:17 +00003527void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003528 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3529 ScopStmt &Stmt = *StmtIt;
3530
Johannes Doerfert26404542016-05-10 12:19:47 +00003531 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003532 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003533 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003534
Johannes Doerferteca9e892015-11-03 16:54:49 +00003535 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003536 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003537 bool OnlyRead = true;
3538 for (MemoryAccess *MA : Stmt) {
3539 if (MA->isRead())
3540 continue;
3541
3542 OnlyRead = false;
3543 break;
3544 }
3545
3546 RemoveStmt = OnlyRead;
3547 }
3548
Johannes Doerfert26404542016-05-10 12:19:47 +00003549 if (!RemoveStmt) {
3550 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003551 continue;
3552 }
3553
Johannes Doerfert26404542016-05-10 12:19:47 +00003554 // Remove the statement because it is unnecessary.
3555 if (Stmt.isRegionStmt())
3556 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3557 StmtMap.erase(BB);
3558 else
3559 StmtMap.erase(Stmt.getBasicBlock());
3560
3561 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003562 }
3563}
3564
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003565InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003566 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3567 if (!LInst)
3568 return nullptr;
3569
3570 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3571 LInst = cast<LoadInst>(Rep);
3572
Johannes Doerfert96e54712016-02-07 17:30:13 +00003573 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003574 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003575 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003576 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003577 continue;
3578
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003579 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003580 for (auto *MA : MAs)
3581 if (MA->getAccessInstruction() == Val)
3582 return &IAClass;
3583 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003584
3585 return nullptr;
3586}
3587
Tobias Grosserc80d6972016-09-02 06:33:33 +00003588/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003589static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003590 bool MAInvalidCtxIsEmpty,
3591 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003592 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3593 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3594 // TODO: We can provide more information for better but more expensive
3595 // results.
3596 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3597 LInst->getAlignment(), DL))
3598 return false;
3599
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003600 // If the location might be overwritten we do not hoist it unconditionally.
3601 //
3602 // TODO: This is probably to conservative.
3603 if (!NonHoistableCtxIsEmpty)
3604 return false;
3605
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003606 // If a dereferencable load is in a statement that is modeled precisely we can
3607 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003608 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003609 return true;
3610
3611 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003612 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003613 // statement domain.
3614 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3615 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3616 return false;
3617 return true;
3618}
3619
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003620void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003621
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003622 if (InvMAs.empty())
3623 return;
3624
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003625 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003626 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003627
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003628 // Get the context under which the statement is executed but remove the error
3629 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003630 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003631 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003632
Tobias Grosser90411a92017-02-16 19:11:33 +00003633 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003634 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003635 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3636 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003637 for (auto &InvMA : InvMAs)
3638 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003639 return;
3640 }
3641
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003642 // Project out all parameters that relate to loads in the statement. Otherwise
3643 // we could have cyclic dependences on the constraints under which the
3644 // hoisted loads are executed and we could not determine an order in which to
3645 // pre-load them. This happens because not only lower bounds are part of the
3646 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003647 for (auto &InvMA : InvMAs) {
3648 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003649 Instruction *AccInst = MA->getAccessInstruction();
3650 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003651 SetVector<Value *> Values;
3652 for (const SCEV *Parameter : Parameters) {
3653 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003654 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003655 if (!Values.count(AccInst))
3656 continue;
3657
3658 if (isl_id *ParamId = getIdForParam(Parameter)) {
3659 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003660 if (Dim >= 0)
3661 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003662 isl_id_free(ParamId);
3663 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003664 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003665 }
3666 }
3667
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003668 for (auto &InvMA : InvMAs) {
3669 auto *MA = InvMA.MA;
3670 auto *NHCtx = InvMA.NonHoistableCtx;
3671
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003672 // Check for another invariant access that accesses the same location as
3673 // MA and if found consolidate them. Otherwise create a new equivalence
3674 // class at the end of InvariantEquivClasses.
3675 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003676 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003677 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3678
Johannes Doerfert85676e32016-04-23 14:32:34 +00003679 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003680 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003681 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3682
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003683 isl_set *MACtx;
3684 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003685 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3686 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003687 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003688 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003689 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003690 } else {
3691 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003692 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003693 MACtx = isl_set_gist_params(MACtx, getContext());
3694 }
3695
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003696 bool Consolidated = false;
3697 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003698 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003699 continue;
3700
Johannes Doerfertdf880232016-03-03 12:26:58 +00003701 // If the pointer and the type is equal check if the access function wrt.
3702 // to the domain is equal too. It can happen that the domain fixes
3703 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003704 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003705 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003706 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003707 if (!MAs.empty()) {
3708 auto *LastMA = MAs.front();
3709
3710 auto *AR = isl_map_range(MA->getAccessRelation());
3711 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3712 bool SameAR = isl_set_is_equal(AR, LastAR);
3713 isl_set_free(AR);
3714 isl_set_free(LastAR);
3715
3716 if (!SameAR)
3717 continue;
3718 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003719
3720 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003721 MAs.push_front(MA);
3722
Johannes Doerfertdf880232016-03-03 12:26:58 +00003723 Consolidated = true;
3724
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003725 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003726 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003727 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003728 IAClassDomainCtx =
3729 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003730 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003731 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003732 break;
3733 }
3734
3735 if (Consolidated)
3736 continue;
3737
3738 // If we did not consolidate MA, thus did not find an equivalence class
3739 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003740 InvariantEquivClasses.emplace_back(
3741 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003742 }
3743
3744 isl_set_free(DomainCtx);
3745}
3746
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003747__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3748 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003749 // TODO: Loads that are not loop carried, hence are in a statement with
3750 // zero iterators, are by construction invariant, though we
3751 // currently "hoist" them anyway. This is necessary because we allow
3752 // them to be treated as parameters (e.g., in conditions) and our code
3753 // generation would otherwise use the old value.
3754
3755 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003756 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003757
Johannes Doerfertc9765462016-11-17 22:11:56 +00003758 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3759 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003760 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003761
3762 // Skip accesses that have an invariant base pointer which is defined but
3763 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3764 // returns a pointer that is used as a base address. However, as we want
3765 // to hoist indirect pointers, we allow the base pointer to be defined in
3766 // the region if it is also a memory access. Each ScopArrayInfo object
3767 // that has a base pointer origin has a base pointer that is loaded and
3768 // that it is invariant, thus it will be hoisted too. However, if there is
3769 // no base pointer origin we check that the base pointer is defined
3770 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003771 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003772 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003773 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003774
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003775 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003776 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003777
3778 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3779 Stmt.getNumIterators())) {
3780 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003781 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003782 }
3783
3784 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003785 isl_set *SafeToLoad;
3786
3787 auto &DL = getFunction().getParent()->getDataLayout();
3788 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
3789 DL)) {
3790 SafeToLoad =
3791 isl_set_universe(isl_space_range(isl_map_get_space(AccessRelation)));
3792 isl_map_free(AccessRelation);
3793 } else if (BB != LI->getParent()) {
3794 // Skip accesses in non-affine subregions as they might not be executed
3795 // under the same condition as the entry of the non-affine subregion.
3796 isl_map_free(AccessRelation);
3797 return nullptr;
3798 } else {
3799 SafeToLoad = isl_map_range(AccessRelation);
3800 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003801
3802 isl_union_map *Written = isl_union_map_intersect_range(
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003803 isl_union_map_copy(Writes), isl_union_set_from_set(SafeToLoad));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003804 auto *WrittenCtx = isl_union_map_params(Written);
3805 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003806
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003807 if (!IsWritten)
3808 return WrittenCtx;
3809
3810 WrittenCtx = isl_set_remove_divs(WrittenCtx);
Tobias Grosser90411a92017-02-16 19:11:33 +00003811 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctsInDomain;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003812 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3813 isl_set_free(WrittenCtx);
3814 return nullptr;
3815 }
3816
3817 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3818 AS_RESTRICTION);
3819 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003820}
3821
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003822void Scop::verifyInvariantLoads() {
3823 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003824 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003825 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003826 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003827 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003828 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3829 return;
3830 }
3831 }
3832}
3833
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003834void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003835 if (!PollyInvariantLoadHoisting)
3836 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003837
Tobias Grosser0865e7752016-02-29 07:29:42 +00003838 isl_union_map *Writes = getWrites();
3839 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003840 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003841
Tobias Grosser0865e7752016-02-29 07:29:42 +00003842 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003843 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3844 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003845
3846 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003847 for (auto InvMA : InvariantAccesses)
3848 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003849 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003850 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003851 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003852}
3853
Tobias Grosserf3adab42017-05-10 10:59:58 +00003854/// Find the canonical scop array info object for a set of invariant load
3855/// hoisted loads. The canonical array is the one that corresponds to the
3856/// first load in the list of accesses which is used as base pointer of a
3857/// scop array.
3858static const ScopArrayInfo *findCanonicalArray(Scop *S,
3859 MemoryAccessList &Accesses) {
3860 for (MemoryAccess *Access : Accesses) {
3861 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
3862 Access->getAccessInstruction(), MemoryKind::Array);
3863 if (CanonicalArray)
3864 return CanonicalArray;
3865 }
3866 return nullptr;
3867}
3868
3869/// Check if @p Array severs as base array in an invariant load.
3870static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
3871 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
3872 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
3873 if (Access2->getScopArrayInfo() == Array)
3874 return true;
3875 return false;
3876}
3877
3878/// Replace the base pointer arrays in all memory accesses referencing @p Old,
3879/// with a reference to @p New.
3880static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
3881 const ScopArrayInfo *New) {
3882 for (ScopStmt &Stmt : *S)
3883 for (MemoryAccess *Access : Stmt) {
3884 if (Access->getLatestScopArrayInfo() != Old)
3885 continue;
3886
3887 isl_id *Id = New->getBasePtrId();
3888 isl_map *Map = Access->getAccessRelation();
3889 Map = isl_map_set_tuple_id(Map, isl_dim_out, Id);
3890 Access->setAccessRelation(Map);
3891 }
3892}
3893
3894void Scop::canonicalizeDynamicBasePtrs() {
3895 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
3896 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
3897
3898 const ScopArrayInfo *CanonicalBasePtrSAI =
3899 findCanonicalArray(this, BasePtrAccesses);
3900
3901 if (!CanonicalBasePtrSAI)
3902 continue;
3903
3904 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
3905 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
3906 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
3907 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
3908 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
3909 continue;
3910
3911 // we currently do not canonicalize arrays where some accesses are
3912 // hoisted as invariant loads. If we would, we need to update the access
3913 // function of the invariant loads as well. However, as this is not a
3914 // very common situation, we leave this for now to avoid further
3915 // complexity increases.
3916 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
3917 continue;
3918
3919 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
3920 }
3921 }
3922}
3923
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003924const ScopArrayInfo *
3925Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
3926 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
3927 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00003928 assert((BasePtr || BaseName) &&
3929 "BasePtr and BaseName can not be nullptr at the same time.");
3930 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3931 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3932 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003933 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003934 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003935 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003936 DL, this, BaseName));
3937 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003938 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003939 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003940 // In case of mismatching array sizes, we bail out by setting the run-time
3941 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003942 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003943 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003944 }
Tobias Grosserab671442015-05-23 05:58:27 +00003945 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003946}
3947
Roman Gareevd7754a12016-07-30 09:25:51 +00003948const ScopArrayInfo *
3949Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3950 const std::vector<unsigned> &Sizes) {
3951 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3952 std::vector<const SCEV *> SCEVSizes;
3953
3954 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003955 if (size)
3956 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3957 else
3958 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003959
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003960 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3961 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00003962 return SAI;
3963}
3964
Tobias Grosserf3adab42017-05-10 10:59:58 +00003965const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
3966 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003967 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00003968 return SAI;
3969}
3970
3971const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
3972 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003973 assert(SAI && "No ScopArrayInfo available for this base pointer");
3974 return SAI;
3975}
3976
Tobias Grosser74394f02013-01-14 22:40:23 +00003977std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003978
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003979std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003980 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003981 return stringFromIslObj(AssumedContext);
3982}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003983
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003984std::string Scop::getInvalidContextStr() const {
3985 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003986}
Tobias Grosser75805372011-04-29 06:27:02 +00003987
3988std::string Scop::getNameStr() const {
3989 std::string ExitName, EntryName;
3990 raw_string_ostream ExitStr(ExitName);
3991 raw_string_ostream EntryStr(EntryName);
3992
Tobias Grosserf240b482014-01-09 10:42:15 +00003993 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003994 EntryStr.str();
3995
3996 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003997 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003998 ExitStr.str();
3999 } else
4000 ExitName = "FunctionExit";
4001
4002 return EntryName + "---" + ExitName;
4003}
4004
Tobias Grosser74394f02013-01-14 22:40:23 +00004005__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00004006__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00004007 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00004008}
4009
Tobias Grossere86109f2013-10-29 21:05:49 +00004010__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004011 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00004012 return isl_set_copy(AssumedContext);
4013}
4014
Michael Krusef3091bf2017-03-17 13:09:52 +00004015bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004016 if (PollyProcessUnprofitable)
4017 return true;
4018
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004019 if (isEmpty())
4020 return false;
4021
4022 unsigned OptimizableStmtsOrLoops = 0;
4023 for (auto &Stmt : *this) {
4024 if (Stmt.getNumIterators() == 0)
4025 continue;
4026
4027 bool ContainsArrayAccs = false;
4028 bool ContainsScalarAccs = false;
4029 for (auto *MA : Stmt) {
4030 if (MA->isRead())
4031 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004032 ContainsArrayAccs |= MA->isLatestArrayKind();
4033 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004034 }
4035
Michael Krusef3091bf2017-03-17 13:09:52 +00004036 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004037 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4038 }
4039
4040 return OptimizableStmtsOrLoops > 1;
4041}
4042
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004043bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004044 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004045 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00004046 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4047 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4048 isl_set_is_subset(PositiveContext, NegativeContext));
4049 isl_set_free(PositiveContext);
4050 if (!IsFeasible) {
4051 isl_set_free(NegativeContext);
4052 return false;
4053 }
4054
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004055 auto *DomainContext = isl_union_set_params(getDomains());
4056 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00004057 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004058 isl_set_free(NegativeContext);
4059 isl_set_free(DomainContext);
4060
Johannes Doerfert43788c52015-08-20 05:58:56 +00004061 return IsFeasible;
4062}
4063
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004064static std::string toString(AssumptionKind Kind) {
4065 switch (Kind) {
4066 case ALIASING:
4067 return "No-aliasing";
4068 case INBOUNDS:
4069 return "Inbounds";
4070 case WRAPPING:
4071 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004072 case UNSIGNED:
4073 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004074 case COMPLEXITY:
4075 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004076 case PROFITABLE:
4077 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004078 case ERRORBLOCK:
4079 return "No-error";
4080 case INFINITELOOP:
4081 return "Finite loop";
4082 case INVARIANTLOAD:
4083 return "Invariant load";
4084 case DELINEARIZATION:
4085 return "Delinearization";
4086 }
4087 llvm_unreachable("Unknown AssumptionKind!");
4088}
4089
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004090bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4091 if (Sign == AS_ASSUMPTION) {
4092 if (isl_set_is_subset(Context, Set))
4093 return false;
4094
4095 if (isl_set_is_subset(AssumedContext, Set))
4096 return false;
4097 } else {
4098 if (isl_set_is_disjoint(Set, Context))
4099 return false;
4100
4101 if (isl_set_is_subset(Set, InvalidContext))
4102 return false;
4103 }
4104 return true;
4105}
4106
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004107bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
4108 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004109 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4110 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004111
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004112 // Do never emit trivial assumptions as they only clutter the output.
4113 if (!PollyRemarksMinimal) {
4114 isl_set *Univ = nullptr;
4115 if (Sign == AS_ASSUMPTION)
4116 Univ = isl_set_universe(isl_set_get_space(Set));
4117
4118 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4119 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4120 isl_set_free(Univ);
4121
4122 if (IsTrivial)
4123 return false;
4124 }
4125
Johannes Doerfertcd195322016-11-17 21:41:08 +00004126 switch (Kind) {
4127 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004128 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004129 break;
4130 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004131 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004132 break;
4133 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004134 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004135 break;
4136 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004137 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004138 break;
4139 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004140 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004141 break;
4142 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004143 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004144 break;
4145 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004146 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004147 break;
4148 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004149 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004150 break;
4151 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004152 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004153 break;
4154 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004155 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004156 break;
4157 }
4158
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004159 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004160 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4161 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004162 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004163 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004164}
4165
4166void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004167 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004168 // Simplify the assumptions/restrictions first.
4169 Set = isl_set_gist_params(Set, getContext());
4170
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004171 if (!trackAssumption(Kind, Set, Loc, Sign)) {
4172 isl_set_free(Set);
4173 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004174 }
4175
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004176 if (Sign == AS_ASSUMPTION) {
4177 AssumedContext = isl_set_intersect(AssumedContext, Set);
4178 AssumedContext = isl_set_coalesce(AssumedContext);
4179 } else {
4180 InvalidContext = isl_set_union(InvalidContext, Set);
4181 InvalidContext = isl_set_coalesce(InvalidContext);
4182 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004183}
4184
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004185void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004186 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004187 assert((isl_set_is_params(Set) || BB) &&
4188 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004189 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004190}
4191
4192void Scop::addRecordedAssumptions() {
4193 while (!RecordedAssumptions.empty()) {
4194 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004195
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004196 if (!AS.BB) {
4197 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
4198 continue;
4199 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004200
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004201 // If the domain was deleted the assumptions are void.
4202 isl_set *Dom = getDomainConditions(AS.BB);
4203 if (!Dom) {
4204 isl_set_free(AS.Set);
4205 continue;
4206 }
4207
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004208 // If a basic block was given use its domain to simplify the assumption.
4209 // In case of restrictions we know they only have to hold on the domain,
4210 // thus we can intersect them with the domain of the block. However, for
4211 // assumptions the domain has to imply them, thus:
4212 // _ _____
4213 // Dom => S <==> A v B <==> A - B
4214 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004215 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004216 // assumption.
4217 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004218 if (AS.Sign == AS_RESTRICTION)
4219 S = isl_set_params(isl_set_intersect(S, Dom));
4220 else /* (AS.Sign == AS_ASSUMPTION) */
4221 S = isl_set_params(isl_set_subtract(Dom, S));
4222
4223 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004224 }
4225}
4226
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004227void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004228 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004229}
4230
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004231__isl_give isl_set *Scop::getInvalidContext() const {
4232 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004233}
4234
Tobias Grosser75805372011-04-29 06:27:02 +00004235void Scop::printContext(raw_ostream &OS) const {
4236 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004237 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004238
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004239 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004240 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004241
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004242 OS.indent(4) << "Invalid Context:\n";
4243 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004244
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004245 unsigned Dim = 0;
4246 for (const SCEV *Parameter : Parameters)
4247 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004248}
4249
Johannes Doerfertb164c792014-09-18 11:17:17 +00004250void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004251 int noOfGroups = 0;
4252 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004253 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004254 noOfGroups += 1;
4255 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004256 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004257 }
4258
Tobias Grosserbb853c22015-07-25 12:31:03 +00004259 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004260 if (MinMaxAliasGroups.empty()) {
4261 OS.indent(8) << "n/a\n";
4262 return;
4263 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004264
Tobias Grosserbb853c22015-07-25 12:31:03 +00004265 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004266
4267 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004268 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004269 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004270 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004271 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4272 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004273 }
4274 OS << " ]]\n";
4275 }
4276
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004277 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004278 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004279 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004280 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004281 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4282 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004283 }
4284 OS << " ]]\n";
4285 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004286 }
4287}
4288
Tobias Grosser75805372011-04-29 06:27:02 +00004289void Scop::printStatements(raw_ostream &OS) const {
4290 OS << "Statements {\n";
4291
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004292 for (const ScopStmt &Stmt : *this)
4293 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00004294
4295 OS.indent(4) << "}\n";
4296}
4297
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004298void Scop::printArrayInfo(raw_ostream &OS) const {
4299 OS << "Arrays {\n";
4300
Tobias Grosserab671442015-05-23 05:58:27 +00004301 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004302 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004303
4304 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004305
4306 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4307
4308 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004309 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004310
4311 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004312}
4313
Tobias Grosser75805372011-04-29 06:27:02 +00004314void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004315 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004316 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004317 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004318 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004319 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004320 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004321 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004322 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004323 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004324 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004325 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4326 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004327 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004328 }
4329 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004330 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004331 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004332 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00004333 printStatements(OS.indent(4));
4334}
4335
4336void Scop::dump() const { print(dbgs()); }
4337
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004338isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004339
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004340__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4341 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004342 // First try to use the SCEVAffinator to generate a piecewise defined
4343 // affine function from @p E in the context of @p BB. If that tasks becomes to
4344 // complex the affinator might return a nullptr. In such a case we invalidate
4345 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004346 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004347 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004348 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004349 // TODO: We could use a heuristic and either use:
4350 // SCEVAffinator::takeNonNegativeAssumption
4351 // or
4352 // SCEVAffinator::interpretAsUnsigned
4353 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004354 if (NonNegative)
4355 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004356 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004357 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004358
4359 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
4360 invalidate(COMPLEXITY, DL);
4361 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004362}
4363
Tobias Grosser808cd692015-07-14 09:33:13 +00004364__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004365 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4366 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004367
Tobias Grosser808cd692015-07-14 09:33:13 +00004368 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004369 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004370
4371 return Domain;
4372}
4373
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004374__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4375 PWACtx PWAC = getPwAff(E, BB);
4376 isl_set_free(PWAC.second);
4377 return PWAC.first;
4378}
4379
Tobias Grossere5a35142015-11-12 14:07:09 +00004380__isl_give isl_union_map *
4381Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4382 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004383
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004384 for (ScopStmt &Stmt : *this) {
4385 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004386 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004387 continue;
4388
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004389 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004390 isl_map *AccessDomain = MA->getAccessRelation();
4391 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004392 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004393 }
4394 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004395 return isl_union_map_coalesce(Accesses);
4396}
4397
4398__isl_give isl_union_map *Scop::getMustWrites() {
4399 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004400}
4401
4402__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004403 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004404}
4405
Tobias Grosser37eb4222014-02-20 21:43:54 +00004406__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004407 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004408}
4409
4410__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004411 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004412}
4413
Tobias Grosser2ac23382015-11-12 14:07:13 +00004414__isl_give isl_union_map *Scop::getAccesses() {
4415 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4416}
4417
Roman Gareevb3224ad2016-09-14 06:26:09 +00004418// Check whether @p Node is an extension node.
4419//
4420// @return true if @p Node is an extension node.
4421isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4422 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4423 return isl_bool_error;
4424 else
4425 return isl_bool_true;
4426}
4427
4428bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4429 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4430 nullptr) == isl_stat_error;
4431}
4432
Tobias Grosser808cd692015-07-14 09:33:13 +00004433__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004434 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004435 if (containsExtensionNode(Tree)) {
4436 isl_schedule_free(Tree);
4437 return nullptr;
4438 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004439 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004440 isl_schedule_free(Tree);
4441 return S;
4442}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004443
Tobias Grosser808cd692015-07-14 09:33:13 +00004444__isl_give isl_schedule *Scop::getScheduleTree() const {
4445 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4446 getDomains());
4447}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004448
Tobias Grosser808cd692015-07-14 09:33:13 +00004449void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4450 auto *S = isl_schedule_from_domain(getDomains());
4451 S = isl_schedule_insert_partial_schedule(
4452 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4453 isl_schedule_free(Schedule);
4454 Schedule = S;
4455}
4456
4457void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4458 isl_schedule_free(Schedule);
4459 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004460}
4461
4462bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4463 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004464 for (ScopStmt &Stmt : *this) {
4465 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004466 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4467 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4468
4469 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4470 isl_union_set_free(StmtDomain);
4471 isl_union_set_free(NewStmtDomain);
4472 continue;
4473 }
4474
4475 Changed = true;
4476
4477 isl_union_set_free(StmtDomain);
4478 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4479
4480 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004481 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004482 isl_union_set_free(NewStmtDomain);
4483 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004484 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004485 }
4486 isl_union_set_free(Domain);
4487 return Changed;
4488}
4489
Tobias Grosser75805372011-04-29 06:27:02 +00004490ScalarEvolution *Scop::getSE() const { return SE; }
4491
Tobias Grosser808cd692015-07-14 09:33:13 +00004492struct MapToDimensionDataTy {
4493 int N;
4494 isl_union_pw_multi_aff *Res;
4495};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004496
Tobias Grosserc80d6972016-09-02 06:33:33 +00004497// Create a function that maps the elements of 'Set' to its N-th dimension and
4498// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004499//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004500// @param Set The input set.
4501// @param User->N The dimension to map to.
4502// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004503//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004504// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004505static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4506 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4507 int Dim;
4508 isl_space *Space;
4509 isl_pw_multi_aff *PMA;
4510
4511 Dim = isl_set_dim(Set, isl_dim_set);
4512 Space = isl_set_get_space(Set);
4513 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4514 Dim - Data->N);
4515 if (Data->N > 1)
4516 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4517 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4518
4519 isl_set_free(Set);
4520
4521 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004522}
4523
Tobias Grosserc80d6972016-09-02 06:33:33 +00004524// Create an isl_multi_union_aff that defines an identity mapping from the
4525// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004526//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004527// # Example:
4528//
4529// Domain: { A[i,j]; B[i,j,k] }
4530// N: 1
4531//
4532// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4533//
4534// @param USet A union set describing the elements for which to generate a
4535// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004536// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004537// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004538static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004539mapToDimension(__isl_take isl_union_set *USet, int N) {
4540 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004541 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004542 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004543
Tobias Grosser808cd692015-07-14 09:33:13 +00004544 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004545
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004546 auto *Space = isl_union_set_get_space(USet);
4547 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004548
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004549 Data = {N, PwAff};
4550
4551 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004552 (void)Res;
4553
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004554 assert(Res == isl_stat_ok);
4555
4556 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004557 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4558}
4559
Michael Kruse55454072017-03-15 22:16:43 +00004560void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004561 assert(BB && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004562 Stmts.emplace_back(*this, *BB, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004563 auto *Stmt = &Stmts.back();
4564 StmtMap[BB] = Stmt;
4565}
4566
Michael Kruse55454072017-03-15 22:16:43 +00004567void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004568 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004569 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004570 auto *Stmt = &Stmts.back();
4571 for (BasicBlock *BB : R->blocks())
Tobias Grosser808cd692015-07-14 09:33:13 +00004572 StmtMap[BB] = Stmt;
Tobias Grosser808cd692015-07-14 09:33:13 +00004573}
4574
Roman Gareevb3224ad2016-09-14 06:26:09 +00004575ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4576 __isl_take isl_map *TargetRel,
4577 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004578#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004579 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4580 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4581 assert(isl_set_is_subset(Domain, TargetDomain) &&
4582 "Target access not defined for complete statement domain");
4583 assert(isl_set_is_subset(Domain, SourceDomain) &&
4584 "Source access not defined for complete statement domain");
4585 isl_set_free(SourceDomain);
4586 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004587#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004588 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4589 CopyStmtsNum++;
4590 return &(Stmts.back());
4591}
4592
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004593void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004594 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004595 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004596 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004597 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4598 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004599}
4600
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004601/// To generate a schedule for the elements in a Region we traverse the Region
4602/// in reverse-post-order and add the contained RegionNodes in traversal order
4603/// to the schedule of the loop that is currently at the top of the LoopStack.
4604/// For loop-free codes, this results in a correct sequential ordering.
4605///
4606/// Example:
4607/// bb1(0)
4608/// / \.
4609/// bb2(1) bb3(2)
4610/// \ / \.
4611/// bb4(3) bb5(4)
4612/// \ /
4613/// bb6(5)
4614///
4615/// Including loops requires additional processing. Whenever a loop header is
4616/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4617/// from an empty schedule, we first process all RegionNodes that are within
4618/// this loop and complete the sequential schedule at this loop-level before
4619/// processing about any other nodes. To implement this
4620/// loop-nodes-first-processing, the reverse post-order traversal is
4621/// insufficient. Hence, we additionally check if the traversal yields
4622/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4623/// These region-nodes are then queue and only traverse after the all nodes
4624/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004625void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004626 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004627
4628 ReversePostOrderTraversal<Region *> RTraversal(R);
4629 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4630 std::deque<RegionNode *> DelayList;
4631 bool LastRNWaiting = false;
4632
4633 // Iterate over the region @p R in reverse post-order but queue
4634 // sub-regions/blocks iff they are not part of the last encountered but not
4635 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4636 // that we queued the last sub-region/block from the reverse post-order
4637 // iterator. If it is set we have to explore the next sub-region/block from
4638 // the iterator (if any) to guarantee progress. If it is not set we first try
4639 // the next queued sub-region/blocks.
4640 while (!WorkList.empty() || !DelayList.empty()) {
4641 RegionNode *RN;
4642
4643 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4644 RN = WorkList.front();
4645 WorkList.pop_front();
4646 LastRNWaiting = false;
4647 } else {
4648 RN = DelayList.front();
4649 DelayList.pop_front();
4650 }
4651
4652 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004653 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004654 L = OuterScopLoop;
4655
Tobias Grosser151ae322016-04-03 19:36:52 +00004656 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004657 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004658 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004659 LastRNWaiting = true;
4660 DelayList.push_back(RN);
4661 continue;
4662 }
4663 LoopStack.push_back({L, nullptr, 0});
4664 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004665 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004666 }
4667
4668 return;
4669}
4670
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004671void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004672
Tobias Grosser8362c262016-01-06 15:30:06 +00004673 if (RN->isSubRegion()) {
4674 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004675 if (!isNonAffineSubRegion(LocalRegion)) {
4676 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004677 return;
4678 }
4679 }
Michael Kruse046dde42015-08-10 13:01:57 +00004680
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004681 auto &LoopData = LoopStack.back();
4682 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004683
Michael Kruse6f7721f2016-02-24 22:08:19 +00004684 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004685 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4686 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004687 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004688 }
4689
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004690 // Check if we just processed the last node in this loop. If we did, finalize
4691 // the loop by:
4692 //
4693 // - adding new schedule dimensions
4694 // - folding the resulting schedule into the parent loop schedule
4695 // - dropping the loop schedule from the LoopStack.
4696 //
4697 // Then continue to check surrounding loops, which might also have been
4698 // completed by this node.
4699 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00004700 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004701 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004702 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004703
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004704 LoopStack.pop_back();
4705 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004706
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004707 if (Schedule) {
4708 auto *Domain = isl_schedule_get_domain(Schedule);
4709 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4710 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4711 NextLoopData.Schedule =
4712 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004713 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004714
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004715 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4716 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004717 }
Tobias Grosser75805372011-04-29 06:27:02 +00004718}
4719
Michael Kruse6f7721f2016-02-24 22:08:19 +00004720ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004721 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004722 if (StmtMapIt == StmtMap.end())
4723 return nullptr;
4724 return StmtMapIt->second;
4725}
4726
Michael Kruse6f7721f2016-02-24 22:08:19 +00004727ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4728 if (RN->isSubRegion())
4729 return getStmtFor(RN->getNodeAs<Region>());
4730 return getStmtFor(RN->getNodeAs<BasicBlock>());
4731}
4732
4733ScopStmt *Scop::getStmtFor(Region *R) const {
4734 ScopStmt *Stmt = getStmtFor(R->getEntry());
4735 assert(!Stmt || Stmt->getRegion() == R);
4736 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004737}
4738
Johannes Doerfert96425c22015-08-30 21:13:53 +00004739int Scop::getRelativeLoopDepth(const Loop *L) const {
4740 Loop *OuterLoop =
4741 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4742 if (!OuterLoop)
4743 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004744 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4745}
4746
Roman Gareevd7754a12016-07-30 09:25:51 +00004747ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4748 for (auto &SAI : arrays()) {
4749 if (SAI->getName() == BaseName)
4750 return SAI;
4751 }
4752 return nullptr;
4753}
4754
Johannes Doerfert99191c72016-05-31 09:41:04 +00004755//===----------------------------------------------------------------------===//
4756void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4757 AU.addRequired<LoopInfoWrapperPass>();
4758 AU.addRequired<RegionInfoPass>();
4759 AU.addRequired<DominatorTreeWrapperPass>();
4760 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004761 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004762 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004763 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004764 AU.setPreservesAll();
4765}
4766
Tobias Grossercd01a362017-02-17 08:12:36 +00004767void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
4768 NumLoopsInScop += Stats.NumLoops;
4769 MaxNumLoopsInScop =
4770 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
4771
Tobias Grossercd01a362017-02-17 08:12:36 +00004772 if (Stats.MaxDepth == 1)
4773 NumScopsDepthOne++;
4774 else if (Stats.MaxDepth == 2)
4775 NumScopsDepthTwo++;
4776 else if (Stats.MaxDepth == 3)
4777 NumScopsDepthThree++;
4778 else if (Stats.MaxDepth == 4)
4779 NumScopsDepthFour++;
4780 else if (Stats.MaxDepth == 5)
4781 NumScopsDepthFive++;
4782 else
4783 NumScopsDepthLarger++;
4784}
4785
Johannes Doerfert99191c72016-05-31 09:41:04 +00004786bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004787 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004788
4789 if (!SD.isMaxRegionInScop(*R))
4790 return false;
4791
4792 Function *F = R->getEntry()->getParent();
4793 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4794 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4795 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4796 auto const &DL = F->getParent()->getDataLayout();
4797 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004798 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004799
Michael Kruse89b1f942017-03-17 13:56:53 +00004800 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004801 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00004802
4803 if (S) {
4804 ScopDetection::LoopStats Stats =
4805 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
4806 updateLoopCountStatistic(Stats);
4807 }
4808
Tobias Grosser75805372011-04-29 06:27:02 +00004809 return false;
4810}
4811
Johannes Doerfert99191c72016-05-31 09:41:04 +00004812void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004813 if (S)
4814 S->print(OS);
4815 else
4816 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004817}
Tobias Grosser75805372011-04-29 06:27:02 +00004818
Johannes Doerfert99191c72016-05-31 09:41:04 +00004819char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004820
Johannes Doerfert99191c72016-05-31 09:41:04 +00004821Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4822
4823INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004824 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004825 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004826INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00004827INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004828INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004829INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004830INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004831INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004832INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004833INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004834 "Polly - Create polyhedral description of Scops", false,
4835 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004836
4837//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00004838ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
4839 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
4840 AssumptionCache &AC) {
4841 /// Create polyhedral descripton of scops for all the valid regions of a
4842 /// function.
4843 for (auto &It : SD) {
4844 Region *R = const_cast<Region *>(It);
4845 if (!SD.isMaxRegionInScop(*R))
4846 continue;
4847
4848 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4849 std::unique_ptr<Scop> S = SB.getScop();
4850 if (!S)
4851 continue;
4852 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
4853 assert(Inserted && "Building Scop for the same region twice!");
4854 (void)Inserted;
4855 }
4856}
4857
4858AnalysisKey ScopInfoAnalysis::Key;
4859
4860ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
4861 FunctionAnalysisManager &FAM) {
4862 auto &SD = FAM.getResult<ScopAnalysis>(F);
4863 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
4864 auto &LI = FAM.getResult<LoopAnalysis>(F);
4865 auto &AA = FAM.getResult<AAManager>(F);
4866 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
4867 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
4868 auto &DL = F.getParent()->getDataLayout();
4869 return {DL, SD, SE, LI, AA, DT, AC};
4870}
4871
4872PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
4873 FunctionAnalysisManager &FAM) {
4874 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
4875 for (auto &It : SI) {
4876 if (It.second)
4877 It.second->print(Stream);
4878 else
4879 Stream << "Invalid Scop!\n";
4880 }
4881 return PreservedAnalyses::all();
4882}
4883
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004884void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4885 AU.addRequired<LoopInfoWrapperPass>();
4886 AU.addRequired<RegionInfoPass>();
4887 AU.addRequired<DominatorTreeWrapperPass>();
4888 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004889 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004890 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004891 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004892 AU.setPreservesAll();
4893}
4894
4895bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004896 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004897 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4898 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4899 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4900 auto const &DL = F.getParent()->getDataLayout();
4901 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004902 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004903
Philip Pfaffe838e0882017-05-15 12:55:14 +00004904 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004905 return false;
4906}
4907
4908void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00004909 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004910 if (It.second)
4911 It.second->print(OS);
4912 else
4913 OS << "Invalid Scop!\n";
4914 }
4915}
4916
4917char ScopInfoWrapperPass::ID = 0;
4918
4919Pass *polly::createScopInfoWrapperPassPass() {
4920 return new ScopInfoWrapperPass();
4921}
4922
4923INITIALIZE_PASS_BEGIN(
4924 ScopInfoWrapperPass, "polly-function-scops",
4925 "Polly - Create polyhedral description of all Scops of a function", false,
4926 false);
4927INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00004928INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004929INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4930INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4931INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004932INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004933INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4934INITIALIZE_PASS_END(
4935 ScopInfoWrapperPass, "polly-function-scops",
4936 "Polly - Create polyhedral description of all Scops of a function", false,
4937 false)