blob: cfc229709cc25fc3151f6b2208fedbd0de89f155 [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
Johannes Doerfert2f705842016-04-12 16:09:44 +000097static cl::opt<bool> PollyRemarksMinimal(
98 "polly-remarks-minimal",
99 cl::desc("Do not emit remarks about assumptions that are known"),
100 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
101
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +0000102// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000103// operations can overflow easily. Additive reductions and bit operations
104// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +0000105static cl::opt<bool> DisableMultiplicativeReductions(
106 "polly-disable-multiplicative-reductions",
107 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
108 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000109
Johannes Doerfert9143d672014-09-27 11:02:39 +0000110static cl::opt<unsigned> RunTimeChecksMaxParameters(
111 "polly-rtc-max-parameters",
112 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
113 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
114
Tobias Grosser71500722015-03-28 15:11:14 +0000115static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
116 "polly-rtc-max-arrays-per-group",
117 cl::desc("The maximal number of arrays to compare in each alias group."),
118 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000119
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000120static cl::opt<std::string> UserContextStr(
121 "polly-context", cl::value_desc("isl parameter set"),
122 cl::desc("Provide additional constraints on the context parameters"),
123 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000124
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000125static cl::opt<bool> DetectReductions("polly-detect-reductions",
126 cl::desc("Detect and exploit reductions"),
127 cl::Hidden, cl::ZeroOrMore,
128 cl::init(true), cl::cat(PollyCategory));
129
Tobias Grosser2937b592016-04-29 11:43:20 +0000130static cl::opt<bool>
131 IslOnErrorAbort("polly-on-isl-error-abort",
132 cl::desc("Abort if an isl error is encountered"),
133 cl::init(true), cl::cat(PollyCategory));
134
Michael Kruse6ab44762016-10-04 17:33:39 +0000135static cl::opt<bool> UnprofitableScalarAccs(
136 "polly-unprofitable-scalar-accs",
137 cl::desc("Count statements with scalar accesses as not optimizable"),
Michael Kruse9b91c622017-03-17 13:10:05 +0000138 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Michael Kruse6ab44762016-10-04 17:33:39 +0000139
Tobias Grosserd7c49752017-02-28 09:45:54 +0000140static cl::opt<bool> PollyPreciseInbounds(
141 "polly-precise-inbounds",
142 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
143 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
144
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000145static cl::opt<bool>
146 PollyIgnoreInbounds("polly-ignore-inbounds",
147 cl::desc("Do not take inbounds assumptions at all"),
148 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
149
Tobias Grosser5842dee2017-03-17 13:00:53 +0000150static cl::opt<bool> PollyIgnoreParamBounds(
151 "polly-ignore-parameter-bounds",
152 cl::desc(
153 "Do not add parameter bounds and do no gist simplify sets accordingly"),
154 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
155
Tobias Grosserc2f15102017-03-01 21:11:27 +0000156static cl::opt<bool> PollyPreciseFoldAccesses(
157 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000158 cl::desc("Fold memory accesses to model more possible delinearizations "
159 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000160 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Michael Kruse7bf39442015-09-10 12:46:52 +0000161//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000162
Michael Kruse046dde42015-08-10 13:01:57 +0000163// Create a sequence of two schedules. Either argument may be null and is
164// interpreted as the empty schedule. Can also return null if both schedules are
165// empty.
166static __isl_give isl_schedule *
167combineInSequence(__isl_take isl_schedule *Prev,
168 __isl_take isl_schedule *Succ) {
169 if (!Prev)
170 return Succ;
171 if (!Succ)
172 return Prev;
173
174 return isl_schedule_sequence(Prev, Succ);
175}
176
Johannes Doerferte7044942015-02-24 11:58:30 +0000177static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
178 const ConstantRange &Range,
179 int dim,
180 enum isl_dim_type type) {
181 isl_val *V;
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000182 isl_ctx *Ctx = isl_set_get_ctx(S);
Johannes Doerferte7044942015-02-24 11:58:30 +0000183
Tobias Grosser3281f602017-02-16 18:39:14 +0000184 // The upper and lower bound for a parameter value is derived either from
185 // the data type of the parameter or from the - possibly more restrictive -
186 // range metadata.
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000187 V = isl_valFromAPInt(Ctx, Range.getSignedMin(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000188 S = isl_set_lower_bound_val(S, type, dim, V);
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000189 V = isl_valFromAPInt(Ctx, Range.getSignedMax(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000190 S = isl_set_upper_bound_val(S, type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000191
Tobias Grosser3281f602017-02-16 18:39:14 +0000192 if (Range.isFullSet())
193 return S;
194
Tobias Grosserc8a82762017-02-16 19:11:25 +0000195 if (isl_set_n_basic_set(S) > MaxDisjunctsInContext)
196 return S;
197
Tobias Grosser3281f602017-02-16 18:39:14 +0000198 // In case of signed wrapping, we can refine the set of valid values by
199 // excluding the part not covered by the wrapping range.
200 if (Range.isSignWrappedSet()) {
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000201 V = isl_valFromAPInt(Ctx, Range.getLower(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000202 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
203
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000204 V = isl_valFromAPInt(Ctx, Range.getUpper(), true);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000205 V = isl_val_sub_ui(V, 1);
Tobias Grosser3281f602017-02-16 18:39:14 +0000206 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
207 S = isl_set_union(SLB, SUB);
208 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000209
Tobias Grosser3281f602017-02-16 18:39:14 +0000210 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000211}
212
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000213static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
214 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
215 if (!BasePtrLI)
216 return nullptr;
217
Johannes Doerfert952b5302016-05-23 12:40:48 +0000218 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000219 return nullptr;
220
221 ScalarEvolution &SE = *S->getSE();
222
223 auto *OriginBaseSCEV =
224 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
225 if (!OriginBaseSCEV)
226 return nullptr;
227
228 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
229 if (!OriginBaseSCEVUnknown)
230 return nullptr;
231
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000232 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000233 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000234}
235
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000236ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000237 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000238 const DataLayout &DL, Scop *S,
239 const char *BaseName)
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000240 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000241 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000242 BaseName ? BaseName
243 : getIslCompatibleName("MemRef_", BasePtr,
244 Kind == MemoryKind::PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000245 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000246
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000247 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000248
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000249 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000250 BasePtrOriginSAI = nullptr;
251 return;
252 }
253
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000254 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
255 if (BasePtrOriginSAI)
256 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000257}
258
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000259__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000260 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000261 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
262 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
263 return Space;
264}
265
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000266bool ScopArrayInfo::isReadOnly() {
267 isl_union_set *WriteSet = isl_union_map_range(S.getWrites());
268 isl_space *Space = getSpace();
269 WriteSet = isl_union_set_intersect(
270 WriteSet, isl_union_set_from_set(isl_set_universe(Space)));
271
272 bool IsReadOnly = isl_union_set_is_empty(WriteSet);
273 isl_union_set_free(WriteSet);
274
275 return IsReadOnly;
276}
277
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000278void ScopArrayInfo::updateElementType(Type *NewElementType) {
279 if (NewElementType == ElementType)
280 return;
281
Tobias Grosserd840fc72016-02-04 13:18:42 +0000282 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
283 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
284
Johannes Doerferta7920982016-02-25 14:08:48 +0000285 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000286 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000287
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000288 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
289 ElementType = NewElementType;
290 } else {
291 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
292 ElementType = IntegerType::get(ElementType->getContext(), GCD);
293 }
294}
295
Tobias Grosserbedef002016-12-02 08:10:56 +0000296bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
297 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000298 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
299 int ExtraDimsNew = NewSizes.size() - SharedDims;
300 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000301
Tobias Grosserbedef002016-12-02 08:10:56 +0000302 if (CheckConsistency) {
303 for (int i = 0; i < SharedDims; i++) {
304 auto *NewSize = NewSizes[i + ExtraDimsNew];
305 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
306 if (NewSize && KnownSize && NewSize != KnownSize)
307 return false;
308 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000309
Tobias Grosserbedef002016-12-02 08:10:56 +0000310 if (DimensionSizes.size() >= NewSizes.size())
311 return true;
312 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000313
314 DimensionSizes.clear();
315 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
316 NewSizes.end());
317 for (isl_pw_aff *Size : DimensionSizesPw)
318 isl_pw_aff_free(Size);
319 DimensionSizesPw.clear();
320 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000321 if (!Expr) {
322 DimensionSizesPw.push_back(nullptr);
323 continue;
324 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000325 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000326 DimensionSizesPw.push_back(Size);
327 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000328 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000329}
330
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000331ScopArrayInfo::~ScopArrayInfo() {
332 isl_id_free(Id);
333 for (isl_pw_aff *Size : DimensionSizesPw)
334 isl_pw_aff_free(Size);
335}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000336
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000337std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
338
339int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000340 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000341}
342
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000343__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
344 return isl_id_copy(Id);
345}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000346
347void ScopArrayInfo::dump() const { print(errs()); }
348
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000349void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000350 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000351 unsigned u = 0;
352 if (getNumberOfDimensions() > 0 && !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000353 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000354 u++;
355 }
356 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000357 OS << "[";
358
Tobias Grosser26253842015-11-10 14:24:21 +0000359 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000360 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000361 OS << " " << Size << " ";
362 isl_pw_aff_free(Size);
363 } else {
364 OS << *getDimensionSize(u);
365 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000366
367 OS << "]";
368 }
369
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000370 OS << ";";
371
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000372 if (BasePtrOriginSAI)
373 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
374
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000375 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000376}
377
378const ScopArrayInfo *
379ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
380 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
381 assert(Id && "Output dimension didn't have an ID");
382 return getFromId(Id);
383}
384
Michael Krused56b90a2016-09-01 09:03:27 +0000385const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000386 void *User = isl_id_get_user(Id);
387 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
388 isl_id_free(Id);
389 return SAI;
390}
391
Michael Kruse3b425ff2016-04-11 14:34:08 +0000392void MemoryAccess::wrapConstantDimensions() {
393 auto *SAI = getScopArrayInfo();
394 auto *ArraySpace = SAI->getSpace();
395 auto *Ctx = isl_space_get_ctx(ArraySpace);
396 unsigned DimsArray = SAI->getNumberOfDimensions();
397
398 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
399 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
400 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
401
402 // Begin with last dimension, to iteratively carry into higher dimensions.
403 for (int i = DimsArray - 1; i > 0; i--) {
404 auto *DimSize = SAI->getDimensionSize(i);
405 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
406
407 // This transformation is not applicable to dimensions with dynamic size.
408 if (!DimSizeCst)
409 continue;
410
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000411 // This transformation is not applicable to dimensions of size zero.
412 if (DimSize->isZero())
413 continue;
414
Michael Kruse3b425ff2016-04-11 14:34:08 +0000415 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
416 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
417 isl_dim_set, i);
418 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
419 isl_dim_set, i - 1);
420
421 // Compute: index % size
422 // Modulo must apply in the divide of the previous iteration, if any.
423 auto *Modulo = isl_aff_copy(Var);
424 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
425 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
426
427 // Compute: floor(index / size)
428 auto *Divide = Var;
429 Divide = isl_aff_div(
430 Divide,
431 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
432 Divide = isl_aff_floor(Divide);
433 Divide = isl_aff_add(Divide, PrevVar);
434 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
435
436 // Apply Modulo and Divide.
437 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
438 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
439 }
440
441 // Apply all modulo/divides on the accesses.
442 AccessRelation =
443 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
444 AccessRelation = isl_map_detect_equalities(AccessRelation);
445 isl_local_space_free(LArraySpace);
446}
447
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000448void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000449 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000450 auto *ArraySpace = SAI->getSpace();
451 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000452 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000453
454 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
455 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
456 auto DimsMissing = DimsArray - DimsAccess;
457
Michael Kruse375cb5f2016-02-24 22:08:24 +0000458 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000459 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000460 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000461 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000462
Johannes Doerferta90943d2016-02-21 16:37:25 +0000463 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000464 isl_set_universe(AccessSpace),
465 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000466
467 for (unsigned i = 0; i < DimsMissing; i++)
468 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
469
470 for (unsigned i = DimsMissing; i < DimsArray; i++)
471 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
472
473 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000474
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000475 // For the non delinearized arrays, divide the access function of the last
476 // subscript by the size of the elements in the array.
477 //
478 // A stride one array access in C expressed as A[i] is expressed in
479 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
480 // two subsequent values of 'i' index two values that are stored next to
481 // each other in memory. By this division we make this characteristic
482 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000483 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000484 // that divides the offsets of all accesses to this base pointer.
485 if (DimsAccess == 1) {
486 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
487 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
488 }
489
Michael Kruse3b425ff2016-04-11 14:34:08 +0000490 // We currently do this only if we added at least one dimension, which means
491 // some dimension's indices have not been specified, an indicator that some
492 // index values have been added together.
493 // TODO: Investigate general usefulness; Effect on unit tests is to make index
494 // expressions more complicated.
495 if (DimsMissing)
496 wrapConstantDimensions();
497
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000498 if (!isAffine())
499 computeBoundsOnAccessRelation(ArrayElemSize);
500
Tobias Grosserd840fc72016-02-04 13:18:42 +0000501 // Introduce multi-element accesses in case the type loaded by this memory
502 // access is larger than the canonical element type of the array.
503 //
504 // An access ((float *)A)[i] to an array char *A is modeled as
505 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000506 if (ElemBytes > ArrayElemSize) {
507 assert(ElemBytes % ArrayElemSize == 0 &&
508 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000509 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000510 isl_set_universe(isl_space_copy(ArraySpace)),
511 isl_set_universe(isl_space_copy(ArraySpace)));
512 for (unsigned i = 0; i < DimsArray - 1; i++)
513 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
514
Tobias Grosserd840fc72016-02-04 13:18:42 +0000515 isl_constraint *C;
516 isl_local_space *LS;
517
518 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000519 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
520
521 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
522 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000523 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000524 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
525 Map = isl_map_add_constraint(Map, C);
526
527 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000528 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000529 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
530 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
531 Map = isl_map_add_constraint(Map, C);
532 AccessRelation = isl_map_apply_range(AccessRelation, Map);
533 }
534
535 isl_space_free(ArraySpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000536}
537
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000538const std::string
539MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
540 switch (RT) {
541 case MemoryAccess::RT_NONE:
542 llvm_unreachable("Requested a reduction operator string for a memory "
543 "access which isn't a reduction");
544 case MemoryAccess::RT_ADD:
545 return "+";
546 case MemoryAccess::RT_MUL:
547 return "*";
548 case MemoryAccess::RT_BOR:
549 return "|";
550 case MemoryAccess::RT_BXOR:
551 return "^";
552 case MemoryAccess::RT_BAND:
553 return "&";
554 }
555 llvm_unreachable("Unknown reduction type");
556 return "";
557}
558
Tobias Grosserc80d6972016-09-02 06:33:33 +0000559/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000560static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
561 const Instruction *Load) {
562 if (!BinOp)
563 return MemoryAccess::RT_NONE;
564 switch (BinOp->getOpcode()) {
565 case Instruction::FAdd:
566 if (!BinOp->hasUnsafeAlgebra())
567 return MemoryAccess::RT_NONE;
568 // Fall through
569 case Instruction::Add:
570 return MemoryAccess::RT_ADD;
571 case Instruction::Or:
572 return MemoryAccess::RT_BOR;
573 case Instruction::Xor:
574 return MemoryAccess::RT_BXOR;
575 case Instruction::And:
576 return MemoryAccess::RT_BAND;
577 case Instruction::FMul:
578 if (!BinOp->hasUnsafeAlgebra())
579 return MemoryAccess::RT_NONE;
580 // Fall through
581 case Instruction::Mul:
582 if (DisableMultiplicativeReductions)
583 return MemoryAccess::RT_NONE;
584 return MemoryAccess::RT_MUL;
585 default:
586 return MemoryAccess::RT_NONE;
587 }
588}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000589
Tobias Grosser75805372011-04-29 06:27:02 +0000590MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000591 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000592 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000593 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000594 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000595}
596
Michael Kruse2fa35192016-09-01 19:53:31 +0000597const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000598 isl_id *ArrayId = getArrayId();
599 void *User = isl_id_get_user(ArrayId);
600 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
601 isl_id_free(ArrayId);
602 return SAI;
603}
604
Michael Kruse2fa35192016-09-01 19:53:31 +0000605const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
606 isl_id *ArrayId = getLatestArrayId();
607 void *User = isl_id_get_user(ArrayId);
608 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
609 isl_id_free(ArrayId);
610 return SAI;
611}
612
613__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000614 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
615}
616
Michael Kruse2fa35192016-09-01 19:53:31 +0000617__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
618 if (!hasNewAccessRelation())
619 return getOriginalArrayId();
620 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
621}
622
Tobias Grosserd840fc72016-02-04 13:18:42 +0000623__isl_give isl_map *MemoryAccess::getAddressFunction() const {
624 return isl_map_lexmin(getAccessRelation());
625}
626
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000627__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
628 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000629 isl_map *Schedule, *ScheduledAccRel;
630 isl_union_set *UDomain;
631
632 UDomain = isl_union_set_from_set(getStatement()->getDomain());
633 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
634 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000635 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000636 return isl_pw_multi_aff_from_map(ScheduledAccRel);
637}
638
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000639__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000640 return isl_map_copy(AccessRelation);
641}
642
Johannes Doerferta99130f2014-10-13 12:58:03 +0000643std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000644 return stringFromIslObj(AccessRelation);
645}
646
Johannes Doerferta99130f2014-10-13 12:58:03 +0000647__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000648 return isl_map_get_space(AccessRelation);
649}
650
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000651__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000652 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000653}
654
Tobias Grosser6f730082015-09-05 07:46:47 +0000655std::string MemoryAccess::getNewAccessRelationStr() const {
656 return stringFromIslObj(NewAccessRelation);
657}
658
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000659__isl_give isl_basic_map *
660MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000661 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000662 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000663
Tobias Grosser084d8f72012-05-29 09:29:44 +0000664 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000665 isl_basic_set_universe(Statement->getDomainSpace()),
666 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000667}
668
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000669// Formalize no out-of-bound access assumption
670//
671// When delinearizing array accesses we optimistically assume that the
672// delinearized accesses do not access out of bound locations (the subscript
673// expression of each array evaluates for each statement instance that is
674// executed to a value that is larger than zero and strictly smaller than the
675// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000676// dimension for which we do not need to assume any upper bound. At this point
677// we formalize this assumption to ensure that at code generation time the
678// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000679//
680// To find the set of constraints necessary to avoid out of bound accesses, we
681// first build the set of data locations that are not within array bounds. We
682// then apply the reverse access relation to obtain the set of iterations that
683// may contain invalid accesses and reduce this set of iterations to the ones
684// that are actually executed by intersecting them with the domain of the
685// statement. If we now project out all loop dimensions, we obtain a set of
686// parameters that may cause statement instances to be executed that may
687// possibly yield out of bound memory accesses. The complement of these
688// constraints is the set of constraints that needs to be assumed to ensure such
689// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000690void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000691 if (PollyIgnoreInbounds)
692 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000693 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000694 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000695 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000696 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000697 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
698 isl_pw_aff *Var =
699 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
700 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
701
702 isl_set *DimOutside;
703
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000704 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000705 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000706 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
707 isl_space_dim(Space, isl_dim_set));
708 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
709 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000710
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000711 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000712
713 Outside = isl_set_union(Outside, DimOutside);
714 }
715
716 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
717 Outside = isl_set_intersect(Outside, Statement->getDomain());
718 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000719
720 // Remove divs to avoid the construction of overly complicated assumptions.
721 // Doing so increases the set of parameter combinations that are assumed to
722 // not appear. This is always save, but may make the resulting run-time check
723 // bail out more often than strictly necessary.
724 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000725 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000726 const auto &Loc = getAccessInstruction()
727 ? getAccessInstruction()->getDebugLoc()
728 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000729 if (!PollyPreciseInbounds)
730 Outside = isl_set_gist(Outside, isl_set_params(Statement->getDomain()));
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000731 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
732 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000733 isl_space_free(Space);
734}
735
Johannes Doerfertcea61932016-02-21 19:13:19 +0000736void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000737 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000738 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000739
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000740 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000741 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000742
743 isl_map *LengthMap;
744 if (Subscripts[1] == nullptr) {
745 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
746 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000747 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000748 LengthMap = isl_map_from_pw_aff(LengthPWA);
749 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
750 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
751 }
752 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
753 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000754 SubscriptMap =
755 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000756 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
757 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
758 getStatement()->getDomainId());
759}
760
Johannes Doerferte7044942015-02-24 11:58:30 +0000761void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
762 ScalarEvolution *SE = Statement->getParent()->getSE();
763
Johannes Doerfertcea61932016-02-21 19:13:19 +0000764 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000765 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000766 return;
767
768 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000769 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
770 return;
771
772 auto *PtrSCEV = SE->getSCEV(Ptr);
773 if (isa<SCEVCouldNotCompute>(PtrSCEV))
774 return;
775
776 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
777 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
778 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
779
780 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
781 if (Range.isFullSet())
782 return;
783
Tobias Grosserb3a85882017-02-12 08:11:12 +0000784 if (Range.isWrappedSet())
785 return;
786
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000787 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000788
Johannes Doerferte7044942015-02-24 11:58:30 +0000789 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000790 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000791 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000792 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000793
794 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000795 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000796
Tobias Grosserb3a85882017-02-12 08:11:12 +0000797 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
798
Johannes Doerferte7044942015-02-24 11:58:30 +0000799 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
800 AccessRange =
801 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
802 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
803}
804
Tobias Grosser491b7992016-12-02 05:21:22 +0000805void MemoryAccess::foldAccessRelation() {
806 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
807 return;
808
Michael Krusee2bccbb2015-09-18 19:59:43 +0000809 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000810
Tobias Grosserc2f15102017-03-01 21:11:27 +0000811 isl_map *OldAccessRelation = isl_map_copy(AccessRelation);
812
Tobias Grosser619190d2015-03-30 17:22:28 +0000813 for (int i = Size - 2; i >= 0; --i) {
814 isl_space *Space;
815 isl_map *MapOne, *MapTwo;
Roman Gareevf5aff702016-09-12 17:08:31 +0000816 isl_pw_aff *DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000817
818 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
819 isl_pw_aff_free(DimSize);
820 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
821
822 Space = isl_map_get_space(AccessRelation);
823 Space = isl_space_map_from_set(isl_space_range(Space));
824 Space = isl_space_align_params(Space, SpaceSize);
825
826 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
827 isl_id_free(ParamId);
828
829 MapOne = isl_map_universe(isl_space_copy(Space));
830 for (int j = 0; j < Size; ++j)
831 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
832 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
833
834 MapTwo = isl_map_universe(isl_space_copy(Space));
835 for (int j = 0; j < Size; ++j)
836 if (j < i || j > i + 1)
837 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
838
839 isl_local_space *LS = isl_local_space_from_space(Space);
840 isl_constraint *C;
841 C = isl_equality_alloc(isl_local_space_copy(LS));
842 C = isl_constraint_set_constant_si(C, -1);
843 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
844 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
845 MapTwo = isl_map_add_constraint(MapTwo, C);
846 C = isl_equality_alloc(LS);
847 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
848 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
849 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
850 MapTwo = isl_map_add_constraint(MapTwo, C);
851 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
852
853 MapOne = isl_map_union(MapOne, MapTwo);
854 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
855 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000856
857 isl_id *BaseAddrId = getScopArrayInfo()->getBasePtrId();
858 auto Space = Statement->getDomainSpace();
859 AccessRelation = isl_map_set_tuple_id(
860 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
861 AccessRelation =
862 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
863 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Tobias Grosserc2f15102017-03-01 21:11:27 +0000864
865 // Access dimension folding might in certain cases increase the number of
866 // disjuncts in the memory access, which can possibly complicate the generated
867 // run-time checks and can lead to costly compilation.
868 if (!PollyPreciseFoldAccesses && isl_map_n_basic_map(AccessRelation) >
869 isl_map_n_basic_map(OldAccessRelation)) {
870 isl_map_free(AccessRelation);
871 AccessRelation = OldAccessRelation;
872 } else {
873 isl_map_free(OldAccessRelation);
874 }
875
Tobias Grosser491b7992016-12-02 05:21:22 +0000876 isl_space_free(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000877}
878
Tobias Grosserc80d6972016-09-02 06:33:33 +0000879/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000880static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000881 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000882 if (Size == 1)
883 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000884
885 // Only one factor needs to be divisible.
886 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
887 for (auto *FactorExpr : MulExpr->operands())
888 if (isDivisible(FactorExpr, Size, SE))
889 return true;
890 return false;
891 }
892
893 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
894 // to be divisble.
895 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
896 for (auto *OpExpr : NAryExpr->operands())
897 if (!isDivisible(OpExpr, Size, SE))
898 return false;
899 return true;
900 }
901
902 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
903 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
904 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
905 return MulSCEV == Expr;
906}
907
Michael Krusee2bccbb2015-09-18 19:59:43 +0000908void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
909 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000910
Johannes Doerfert85676e32016-04-23 14:32:34 +0000911 // Initialize the invalid domain which describes all iterations for which the
912 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000913 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
914 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
915 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000916
Michael Krusee2bccbb2015-09-18 19:59:43 +0000917 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000918 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000919
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000920 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
921 buildMemIntrinsicAccessRelation();
922 AccessRelation =
923 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
924 return;
925 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000926
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000927 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000928 // We overapproximate non-affine accesses with a possible access to the
929 // whole array. For read accesses it does not make a difference, if an
930 // access must or may happen. However, for write accesses it is important to
931 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000932 if (!AccessRelation)
933 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
934
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000935 AccessRelation =
936 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000937 return;
938 }
939
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000940 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000941 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000942
Michael Krusee2bccbb2015-09-18 19:59:43 +0000943 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000944 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000945 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000946 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000947 }
948
Tobias Grosser79baa212014-04-10 08:38:02 +0000949 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000950 AccessRelation = isl_map_set_tuple_id(
951 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000952 AccessRelation =
953 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
954
Tobias Grosseraa660a92015-03-30 00:07:50 +0000955 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000956 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000957}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000958
Michael Krusecac948e2015-10-02 13:53:07 +0000959MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000960 AccessType AccType, Value *BaseAddress,
961 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000962 ArrayRef<const SCEV *> Subscripts,
963 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000964 MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000965 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Johannes Doerfert85676e32016-04-23 14:32:34 +0000966 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
967 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()),
968 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000969 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000970 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000971 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000972 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000973
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000974 std::string IdName =
975 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000976 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
977}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000978
Roman Gareevb3224ad2016-09-14 06:26:09 +0000979MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
980 __isl_take isl_map *AccRel)
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000981 : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
982 Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
983 IsAffine(true), AccessRelation(nullptr), NewAccessRelation(AccRel) {
Roman Gareevb3224ad2016-09-14 06:26:09 +0000984 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
985 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
986 Sizes.push_back(nullptr);
987 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
988 Sizes.push_back(SAI->getDimensionSize(i));
989 ElementType = SAI->getElementType();
990 BaseAddr = SAI->getBasePtr();
991 BaseName = SAI->getName();
992 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
993 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
994
995 std::string IdName =
996 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
997 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
998}
999
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001000void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +00001001 auto *Ctx = Statement->getParent()->getContext();
1002 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1003 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001004}
1005
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001006const std::string MemoryAccess::getReductionOperatorStr() const {
1007 return MemoryAccess::getReductionOperatorStr(getReductionType());
1008}
1009
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001010__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
1011
Johannes Doerfertf6183392014-07-01 20:52:51 +00001012raw_ostream &polly::operator<<(raw_ostream &OS,
1013 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001014 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001015 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001016 else
1017 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001018 return OS;
1019}
1020
Tobias Grosser75805372011-04-29 06:27:02 +00001021void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001022 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001023 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001024 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001025 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001026 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001027 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001028 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001029 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001030 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001031 break;
1032 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001033 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +00001034 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001035 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001036 if (hasNewAccessRelation())
1037 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001038}
1039
Tobias Grosser74394f02013-01-14 22:40:23 +00001040void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +00001041
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001042__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
1043 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001044 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +00001045 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
1046 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
1047 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +00001048 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001049}
1050
Tobias Grosser75805372011-04-29 06:27:02 +00001051// Create a map in the size of the provided set domain, that maps from the
1052// one element of the provided set domain to another element of the provided
1053// set domain.
1054// The mapping is limited to all points that are equal in all but the last
1055// dimension and for which the last dimension of the input is strict smaller
1056// than the last dimension of the output.
1057//
1058// getEqualAndLarger(set[i0, i1, ..., iX]):
1059//
1060// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1061// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1062//
Tobias Grosser2a526fe2016-09-08 11:18:56 +00001063static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +00001064 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001065 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +00001066 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001067
1068 // Set all but the last dimension to be equal for the input and output
1069 //
1070 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1071 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001072 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +00001073 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001074
1075 // Set the last dimension of the input to be strict smaller than the
1076 // last dimension of the output.
1077 //
1078 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001079 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1080 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001081 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001082}
1083
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001084__isl_give isl_set *
1085MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001086 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +00001087 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +00001088 isl_space *Space = isl_space_range(isl_map_get_space(S));
1089 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001090
Sebastian Popa00a0292012-12-18 07:46:06 +00001091 S = isl_map_reverse(S);
1092 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001093
Sebastian Popa00a0292012-12-18 07:46:06 +00001094 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1095 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1096 NextScatt = isl_map_apply_domain(NextScatt, S);
1097 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001098
Sebastian Popa00a0292012-12-18 07:46:06 +00001099 isl_set *Deltas = isl_map_deltas(NextScatt);
1100 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001101}
1102
Sebastian Popa00a0292012-12-18 07:46:06 +00001103bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001104 int StrideWidth) const {
1105 isl_set *Stride, *StrideX;
1106 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001107
Sebastian Popa00a0292012-12-18 07:46:06 +00001108 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001109 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001110 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1111 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1112 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1113 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001114 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001115
Tobias Grosser28dd4862012-01-24 16:42:16 +00001116 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001117 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001118
Tobias Grosser28dd4862012-01-24 16:42:16 +00001119 return IsStrideX;
1120}
1121
Michael Krused56b90a2016-09-01 09:03:27 +00001122bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001123 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001124}
1125
Michael Krused56b90a2016-09-01 09:03:27 +00001126bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001127 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001128}
1129
Tobias Grosserbedef002016-12-02 08:10:56 +00001130void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
1131 isl_map_free(AccessRelation);
1132 AccessRelation = NewAccess;
1133}
1134
Michael Krused56b90a2016-09-01 09:03:27 +00001135void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001136 assert(NewAccess);
1137
1138#ifndef NDEBUG
1139 // Check domain space compatibility.
1140 auto *NewSpace = isl_map_get_space(NewAccess);
1141 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1142 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1143 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1144 isl_space_free(NewDomainSpace);
1145 isl_space_free(OriginalDomainSpace);
1146
1147 // Check whether there is an access for every statement instance.
1148 auto *StmtDomain = getStatement()->getDomain();
1149 StmtDomain = isl_set_intersect_params(
1150 StmtDomain, getStatement()->getParent()->getContext());
1151 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1152 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1153 "Partial accesses not supported");
1154 isl_set_free(NewDomain);
1155 isl_set_free(StmtDomain);
1156
Michael Kruse772ce722016-09-01 19:16:58 +00001157 auto *NewAccessSpace = isl_space_range(NewSpace);
1158 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1159 "Must specify the array that is accessed");
1160 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1161 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1162 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001163
1164 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1165 InvariantEquivClassTy *EqClass =
1166 getStatement()->getParent()->lookupInvariantEquivClass(
1167 SAI->getBasePtr());
1168 assert(EqClass &&
1169 "Access functions to indirect arrays must have an invariant and "
1170 "hoisted base pointer");
1171 }
1172
1173 // Check whether access dimensions correspond to number of dimensions of the
1174 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001175 auto Dims = SAI->getNumberOfDimensions();
1176 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1177 "Access dims must match array dims");
1178 isl_space_free(NewAccessSpace);
1179 isl_id_free(NewArrayId);
1180#endif
1181
Tobias Grosser166c4222015-09-05 07:46:40 +00001182 isl_map_free(NewAccessRelation);
1183 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001184}
Tobias Grosser75805372011-04-29 06:27:02 +00001185
1186//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001187
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001188__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001189 isl_set *Domain = getDomain();
1190 if (isl_set_is_empty(Domain)) {
1191 isl_set_free(Domain);
1192 return isl_map_from_aff(
1193 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1194 }
1195 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001196 if (!Schedule) {
1197 isl_set_free(Domain);
1198 return nullptr;
1199 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001200 Schedule = isl_union_map_intersect_domain(
1201 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1202 if (isl_union_map_is_empty(Schedule)) {
1203 isl_set_free(Domain);
1204 isl_union_map_free(Schedule);
1205 return isl_map_from_aff(
1206 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1207 }
1208 auto *M = isl_map_from_union_map(Schedule);
1209 M = isl_map_coalesce(M);
1210 M = isl_map_gist_domain(M, Domain);
1211 M = isl_map_coalesce(M);
1212 return M;
1213}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001214
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001215__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1216 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001217 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1218 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001219}
1220
Tobias Grosser37eb4222014-02-20 21:43:54 +00001221void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1222 assert(isl_set_is_subset(NewDomain, Domain) &&
1223 "New domain is not a subset of old domain!");
1224 isl_set_free(Domain);
1225 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001226}
1227
Michael Krusecac948e2015-10-02 13:53:07 +00001228void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001229 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001230 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001231 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001232
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001233 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001234 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001235 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001236 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001237 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001238 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001239 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001240 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001241 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001242
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001243 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1244 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001245 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001246 }
1247}
1248
Michael Krusecac948e2015-10-02 13:53:07 +00001249void ScopStmt::addAccess(MemoryAccess *Access) {
1250 Instruction *AccessInst = Access->getAccessInstruction();
1251
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001252 if (Access->isArrayKind()) {
1253 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1254 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001255 } else if (Access->isValueKind() && Access->isWrite()) {
1256 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001257 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001258 assert(!ValueWrites.lookup(AccessVal));
1259
1260 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001261 } else if (Access->isValueKind() && Access->isRead()) {
1262 Value *AccessVal = Access->getAccessValue();
1263 assert(!ValueReads.lookup(AccessVal));
1264
1265 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001266 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001267 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001268 assert(!PHIWrites.lookup(PHI));
1269
1270 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001271 }
1272
1273 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001274}
1275
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001276void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001277 for (MemoryAccess *MA : *this)
1278 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001279
Johannes Doerferta60ad842016-05-10 12:18:22 +00001280 auto *Ctx = Parent.getContext();
1281 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1282 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001283}
1284
Tobias Grosserc80d6972016-09-02 06:33:33 +00001285/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001286static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1287 void *User) {
1288 isl_set **BoundedParts = static_cast<isl_set **>(User);
1289 if (isl_basic_set_is_bounded(BSet))
1290 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1291 else
1292 isl_basic_set_free(BSet);
1293 return isl_stat_ok;
1294}
1295
Tobias Grosserc80d6972016-09-02 06:33:33 +00001296/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001297static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1298 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1299 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1300 isl_set_free(S);
1301 return BoundedParts;
1302}
1303
Tobias Grosserc80d6972016-09-02 06:33:33 +00001304/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001305///
1306/// @returns A separation of @p S into first an unbounded then a bounded subset,
1307/// both with regards to the dimension @p Dim.
1308static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1309partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1310
1311 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001312 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001313
1314 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001315 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001316
1317 // Remove dimensions that are greater than Dim as they are not interesting.
1318 assert(NumDimsS >= Dim + 1);
1319 OnlyDimS =
1320 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1321
1322 // Create artificial parametric upper bounds for dimensions smaller than Dim
1323 // as we are not interested in them.
1324 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1325 for (unsigned u = 0; u < Dim; u++) {
1326 isl_constraint *C = isl_inequality_alloc(
1327 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1328 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1329 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1330 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1331 }
1332
1333 // Collect all bounded parts of OnlyDimS.
1334 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1335
1336 // Create the dimensions greater than Dim again.
1337 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1338 NumDimsS - Dim - 1);
1339
1340 // Remove the artificial upper bound parameters again.
1341 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1342
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001343 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001344 return std::make_pair(UnboundedParts, BoundedParts);
1345}
1346
Tobias Grosserc80d6972016-09-02 06:33:33 +00001347/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001348static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1349 __isl_take isl_set *To) {
1350 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1351 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1352 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1353 }
1354 return To;
1355}
1356
Tobias Grosserc80d6972016-09-02 06:33:33 +00001357/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001358static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001359 __isl_take isl_pw_aff *L,
1360 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001361 switch (Pred) {
1362 case ICmpInst::ICMP_EQ:
1363 return isl_pw_aff_eq_set(L, R);
1364 case ICmpInst::ICMP_NE:
1365 return isl_pw_aff_ne_set(L, R);
1366 case ICmpInst::ICMP_SLT:
1367 return isl_pw_aff_lt_set(L, R);
1368 case ICmpInst::ICMP_SLE:
1369 return isl_pw_aff_le_set(L, R);
1370 case ICmpInst::ICMP_SGT:
1371 return isl_pw_aff_gt_set(L, R);
1372 case ICmpInst::ICMP_SGE:
1373 return isl_pw_aff_ge_set(L, R);
1374 case ICmpInst::ICMP_ULT:
1375 return isl_pw_aff_lt_set(L, R);
1376 case ICmpInst::ICMP_UGT:
1377 return isl_pw_aff_gt_set(L, R);
1378 case ICmpInst::ICMP_ULE:
1379 return isl_pw_aff_le_set(L, R);
1380 case ICmpInst::ICMP_UGE:
1381 return isl_pw_aff_ge_set(L, R);
1382 default:
1383 llvm_unreachable("Non integer predicate not supported");
1384 }
1385}
1386
Tobias Grosserc80d6972016-09-02 06:33:33 +00001387/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001388///
1389/// Helper function that will make sure the dimensions of the result have the
1390/// same isl_id's as the @p Domain.
1391static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1392 __isl_take isl_pw_aff *L,
1393 __isl_take isl_pw_aff *R,
1394 __isl_keep isl_set *Domain) {
1395 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1396 return setDimensionIds(Domain, ConsequenceCondSet);
1397}
1398
Tobias Grosserc80d6972016-09-02 06:33:33 +00001399/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001400///
1401/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001402/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1403/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001404static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001405buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1406 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001407 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1408
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001409 Value *Condition = getConditionFromTerminator(SI);
1410 assert(Condition && "No condition for switch");
1411
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001412 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001413 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001414 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001415 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001416
1417 unsigned NumSuccessors = SI->getNumSuccessors();
1418 ConditionSets.resize(NumSuccessors);
1419 for (auto &Case : SI->cases()) {
1420 unsigned Idx = Case.getSuccessorIndex();
1421 ConstantInt *CaseValue = Case.getCaseValue();
1422
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001423 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001424 isl_set *CaseConditionSet =
1425 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1426 ConditionSets[Idx] = isl_set_coalesce(
1427 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1428 }
1429
1430 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1431 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1432 for (unsigned u = 2; u < NumSuccessors; u++)
1433 ConditionSetUnion =
1434 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1435 ConditionSets[0] = setDimensionIds(
1436 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1437
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001438 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001439
1440 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001441}
1442
Tobias Grosserc80d6972016-09-02 06:33:33 +00001443/// Build the conditions sets for the branch condition @p Condition in
1444/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001445///
1446/// This will fill @p ConditionSets with the conditions under which control
1447/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001448/// have as many elements as @p TI has successors. If @p TI is nullptr the
1449/// context under which @p Condition is true/false will be returned as the
1450/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001451static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001452buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1453 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001454 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1455
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001456 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001457 isl_set *ConsequenceCondSet = nullptr;
1458 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1459 if (CCond->isZero())
1460 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1461 else
1462 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1463 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1464 auto Opcode = BinOp->getOpcode();
1465 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1466
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001467 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1468 ConditionSets) &&
1469 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1470 ConditionSets);
1471 if (!Valid) {
1472 while (!ConditionSets.empty())
1473 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001474 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001475 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001476
1477 isl_set_free(ConditionSets.pop_back_val());
1478 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1479 isl_set_free(ConditionSets.pop_back_val());
1480 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1481
1482 if (Opcode == Instruction::And)
1483 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1484 else
1485 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1486 } else {
1487 auto *ICond = dyn_cast<ICmpInst>(Condition);
1488 assert(ICond &&
1489 "Condition of exiting branch was neither constant nor ICmp!");
1490
1491 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001492 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001493 // For unsigned comparisons we assumed the signed bit of neither operand
1494 // to be set. The comparison is equal to a signed comparison under this
1495 // assumption.
1496 bool NonNeg = ICond->isUnsigned();
1497 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1498 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001499 ConsequenceCondSet =
1500 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1501 }
1502
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001503 // If no terminator was given we are only looking for parameter constraints
1504 // under which @p Condition is true/false.
1505 if (!TI)
1506 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001507 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001508 ConsequenceCondSet = isl_set_coalesce(
1509 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001510
Johannes Doerfertb2885792016-04-26 09:20:41 +00001511 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001512 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001513 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001514
Michael Krusef7a4a942016-05-02 12:25:36 +00001515 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001516 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1517 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001518 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001519 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001520 }
1521
Michael Krusef7a4a942016-05-02 12:25:36 +00001522 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001523 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001524 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001525 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001526 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001527 }
1528
1529 ConditionSets.push_back(ConsequenceCondSet);
1530 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001531
1532 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001533}
1534
Tobias Grosserc80d6972016-09-02 06:33:33 +00001535/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001536///
1537/// This will fill @p ConditionSets with the conditions under which control
1538/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1539/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001540static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001541buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001542 __isl_keep isl_set *Domain,
1543 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1544
1545 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001546 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001547
1548 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1549
1550 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001551 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001552 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001553 }
1554
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001555 Value *Condition = getConditionFromTerminator(TI);
1556 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001557
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001558 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001559}
1560
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001561void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001562 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001563
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001564 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001565 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001566}
1567
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001568void ScopStmt::collectSurroundingLoops() {
1569 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1570 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1571 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1572 isl_id_free(DimId);
1573 }
1574}
1575
Michael Kruse55454072017-03-15 22:16:43 +00001576ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001577 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
Michael Kruse55454072017-03-15 22:16:43 +00001578 R(&R), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001579
Tobias Grosser16c44032015-07-09 07:31:45 +00001580 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001581}
1582
Michael Kruse55454072017-03-15 22:16:43 +00001583ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001584 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Michael Kruse55454072017-03-15 22:16:43 +00001585 R(nullptr), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Tobias Grosser75805372011-04-29 06:27:02 +00001586
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001587 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001588}
1589
Roman Gareevb3224ad2016-09-14 06:26:09 +00001590ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1591 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1592 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1593 R(nullptr), Build(nullptr) {
1594 BaseName = getIslCompatibleName("CopyStmt_", "",
1595 std::to_string(parent.getCopyStmtsNum()));
1596 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1597 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1598 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1599 auto *Access =
1600 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1601 parent.addAccessFunction(Access);
1602 addAccess(Access);
1603 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1604 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1605 parent.addAccessFunction(Access);
1606 addAccess(Access);
1607}
1608
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001609void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001610 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001611
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001612 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001613 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001614 buildAccessRelations();
1615
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001616 if (DetectReductions)
1617 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001618}
1619
Tobias Grosserc80d6972016-09-02 06:33:33 +00001620/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001621///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001622/// Check if the stored value for @p StoreMA is a binary operator with one or
1623/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001624/// used only once (by @p StoreMA) and its load operands are also used only
1625/// once, we have found a possible reduction chain. It starts at an operand
1626/// load and includes the binary operator and @p StoreMA.
1627///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001628/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001629/// escape this block or into any other store except @p StoreMA.
1630void ScopStmt::collectCandiateReductionLoads(
1631 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1632 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1633 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001634 return;
1635
1636 // Skip if there is not one binary operator between the load and the store
1637 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001638 if (!BinOp)
1639 return;
1640
1641 // Skip if the binary operators has multiple uses
1642 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001643 return;
1644
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001645 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001646 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1647 return;
1648
Johannes Doerfert9890a052014-07-01 00:32:29 +00001649 // Skip if the binary operator is outside the current SCoP
1650 if (BinOp->getParent() != Store->getParent())
1651 return;
1652
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001653 // Skip if it is a multiplicative reduction and we disabled them
1654 if (DisableMultiplicativeReductions &&
1655 (BinOp->getOpcode() == Instruction::Mul ||
1656 BinOp->getOpcode() == Instruction::FMul))
1657 return;
1658
Johannes Doerferte58a0122014-06-27 20:31:28 +00001659 // Check the binary operator operands for a candidate load
1660 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1661 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1662 if (!PossibleLoad0 && !PossibleLoad1)
1663 return;
1664
1665 // A load is only a candidate if it cannot escape (thus has only this use)
1666 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001667 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001668 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001669 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001670 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001671 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001672}
1673
Tobias Grosserc80d6972016-09-02 06:33:33 +00001674/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001675///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001676/// Iterate over all store memory accesses and check for valid binary reduction
1677/// like chains. For all candidates we check if they have the same base address
1678/// and there are no other accesses which overlap with them. The base address
1679/// check rules out impossible reductions candidates early. The overlap check,
1680/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001681/// guarantees that none of the intermediate results will escape during
1682/// execution of the loop nest. We basically check here that no other memory
1683/// access can access the same memory as the potential reduction.
1684void ScopStmt::checkForReductions() {
1685 SmallVector<MemoryAccess *, 2> Loads;
1686 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1687
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001688 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001689 // stores and collecting possible reduction loads.
1690 for (MemoryAccess *StoreMA : MemAccs) {
1691 if (StoreMA->isRead())
1692 continue;
1693
1694 Loads.clear();
1695 collectCandiateReductionLoads(StoreMA, Loads);
1696 for (MemoryAccess *LoadMA : Loads)
1697 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1698 }
1699
1700 // Then check each possible candidate pair.
1701 for (const auto &CandidatePair : Candidates) {
1702 bool Valid = true;
1703 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1704 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1705
1706 // Skip those with obviously unequal base addresses.
1707 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1708 isl_map_free(LoadAccs);
1709 isl_map_free(StoreAccs);
1710 continue;
1711 }
1712
1713 // And check if the remaining for overlap with other memory accesses.
1714 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1715 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1716 isl_set *AllAccs = isl_map_range(AllAccsRel);
1717
1718 for (MemoryAccess *MA : MemAccs) {
1719 if (MA == CandidatePair.first || MA == CandidatePair.second)
1720 continue;
1721
1722 isl_map *AccRel =
1723 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1724 isl_set *Accs = isl_map_range(AccRel);
1725
Tobias Grosser55a7af72016-09-08 14:08:07 +00001726 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001727 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1728 Valid = Valid && isl_set_is_empty(OverlapAccs);
1729 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001730 } else {
1731 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001732 }
1733 }
1734
1735 isl_set_free(AllAccs);
1736 if (!Valid)
1737 continue;
1738
Johannes Doerfertf6183392014-07-01 20:52:51 +00001739 const LoadInst *Load =
1740 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1741 MemoryAccess::ReductionType RT =
1742 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1743
Johannes Doerferte58a0122014-06-27 20:31:28 +00001744 // If no overlapping access was found we mark the load and store as
1745 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001746 CandidatePair.first->markAsReductionLike(RT);
1747 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001748 }
Tobias Grosser75805372011-04-29 06:27:02 +00001749}
1750
Tobias Grosser74394f02013-01-14 22:40:23 +00001751std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001752
Tobias Grosser54839312015-04-21 11:37:25 +00001753std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001754 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001755 if (!S)
1756 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001757 auto Str = stringFromIslObj(S);
1758 isl_map_free(S);
1759 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001760}
1761
Johannes Doerferta3519512016-04-23 13:02:23 +00001762void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1763 isl_set_free(InvalidDomain);
1764 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001765}
1766
Michael Kruse375cb5f2016-02-24 22:08:24 +00001767BasicBlock *ScopStmt::getEntryBlock() const {
1768 if (isBlockStmt())
1769 return getBasicBlock();
1770 return getRegion()->getEntry();
1771}
1772
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001773unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001774
Tobias Grosser75805372011-04-29 06:27:02 +00001775const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1776
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001777Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001778 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001779}
1780
Tobias Grosser74394f02013-01-14 22:40:23 +00001781isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001782
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001783__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001784
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001785__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001786 return isl_set_get_space(Domain);
1787}
1788
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001789__isl_give isl_id *ScopStmt::getDomainId() const {
1790 return isl_set_get_tuple_id(Domain);
1791}
Tobias Grossercd95b772012-08-30 11:49:38 +00001792
Johannes Doerfert7c013572016-04-12 09:57:34 +00001793ScopStmt::~ScopStmt() {
1794 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001795 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001796}
Tobias Grosser75805372011-04-29 06:27:02 +00001797
1798void ScopStmt::print(raw_ostream &OS) const {
1799 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001800 OS.indent(12) << "Domain :=\n";
1801
1802 if (Domain) {
1803 OS.indent(16) << getDomainStr() << ";\n";
1804 } else
1805 OS.indent(16) << "n/a\n";
1806
Tobias Grosser54839312015-04-21 11:37:25 +00001807 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001808
1809 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001810 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001811 } else
1812 OS.indent(16) << "n/a\n";
1813
Tobias Grosser083d3d32014-06-28 08:59:45 +00001814 for (MemoryAccess *Access : MemAccs)
1815 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001816}
1817
1818void ScopStmt::dump() const { print(dbgs()); }
1819
Michael Kruse10071822016-05-23 14:45:58 +00001820void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001821 // Remove the memory accesses from this statement together with all scalar
1822 // accesses that were caused by it. MemoryKind::Value READs have no access
1823 // instruction, hence would not be removed by this function. However, it is
1824 // only used for invariant LoadInst accesses, its arguments are always affine,
1825 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1826 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001827 auto Predicate = [&](MemoryAccess *Acc) {
1828 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1829 };
1830 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1831 MemAccs.end());
1832 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001833}
1834
Michael Kruse0446d812017-03-10 16:05:24 +00001835void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
1836 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1837 assert(MAIt != MemAccs.end());
1838 MemAccs.erase(MAIt);
1839
1840 auto It = InstructionToAccess.find(MA->getAccessInstruction());
1841 if (It != InstructionToAccess.end()) {
1842 It->second.remove(MA);
1843 if (It->second.empty())
1844 InstructionToAccess.erase(MA->getAccessInstruction());
1845 }
1846}
1847
Tobias Grosser75805372011-04-29 06:27:02 +00001848//===----------------------------------------------------------------------===//
1849/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001850
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001851void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001852 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1853 isl_set_free(Context);
1854 Context = NewContext;
1855}
1856
Tobias Grosserc80d6972016-09-02 06:33:33 +00001857/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001858struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001859 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001860 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001861
1862public:
1863 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001864 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001865
1866 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1867 ValueToValueMap &VMap) {
1868 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1869 return SSPR.visit(E);
1870 }
1871
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001872 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1873 auto *Start = visit(E->getStart());
1874 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1875 visit(E->getStepRecurrence(SE)),
1876 E->getLoop(), SCEV::FlagAnyWrap);
1877 return SE.getAddExpr(Start, AddRec);
1878 }
1879
1880 const SCEV *visitUnknown(const SCEVUnknown *E) {
1881 if (auto *NewValue = VMap.lookup(E->getValue()))
1882 return SE.getUnknown(NewValue);
1883 return E;
1884 }
1885};
1886
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001887const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001888 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001889}
1890
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001891void Scop::createParameterId(const SCEV *Parameter) {
1892 assert(Parameters.count(Parameter));
1893 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001894
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001895 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001896
Tobias Grosser8f99c162011-11-15 11:38:55 +00001897 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1898 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001899
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001900 // If this parameter references a specific Value and this value has a name
1901 // we use this name as it is likely to be unique and more useful than just
1902 // a number.
1903 if (Val->hasName())
1904 ParameterName = Val->getName();
1905 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001906 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001907 if (LoadOrigin->hasName()) {
1908 ParameterName += "_loaded_from_";
1909 ParameterName +=
1910 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1911 }
1912 }
1913 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001914
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001915 ParameterName = getIslCompatibleName("", ParameterName, "");
1916
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001917 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1918 const_cast<void *>((const void *)Parameter));
1919 ParameterIds[Parameter] = Id;
1920}
1921
1922void Scop::addParams(const ParameterSetTy &NewParameters) {
1923 for (const SCEV *Parameter : NewParameters) {
1924 // Normalize the SCEV to get the representing element for an invariant load.
1925 Parameter = extractConstantFactor(Parameter, *SE).second;
1926 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1927
1928 if (Parameters.insert(Parameter))
1929 createParameterId(Parameter);
1930 }
1931}
1932
1933__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1934 // Normalize the SCEV to get the representing element for an invariant load.
1935 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1936 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001937}
Tobias Grosser75805372011-04-29 06:27:02 +00001938
Michael Krused56b90a2016-09-01 09:03:27 +00001939__isl_give isl_set *
1940Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001941 isl_set *DomainContext = isl_union_set_params(getDomains());
1942 return isl_set_intersect_params(C, DomainContext);
1943}
1944
Johannes Doerferte0b08072016-05-23 12:43:44 +00001945bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1946 return DT.dominates(BB, getEntry());
1947}
1948
Michael Kruse89b1f942017-03-17 13:56:53 +00001949void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1950 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001951 auto &F = getFunction();
Michael Kruse89b1f942017-03-17 13:56:53 +00001952 for (auto &Assumption : AC.assumptions()) {
1953 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1954 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001955 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001956
Michael Kruse89b1f942017-03-17 13:56:53 +00001957 bool InScop = contains(CI);
1958 if (!InScop && !isDominatedBy(DT, CI->getParent()))
1959 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001960
Michael Kruse89b1f942017-03-17 13:56:53 +00001961 auto *L = LI.getLoopFor(CI->getParent());
1962 auto *Val = CI->getArgOperand(0);
1963 ParameterSetTy DetectedParams;
1964 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
1965 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1966 CI->getDebugLoc(),
1967 "Non-affine user assumption ignored.");
1968 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00001969 }
Michael Kruse89b1f942017-03-17 13:56:53 +00001970
1971 // Collect all newly introduced parameters.
1972 ParameterSetTy NewParams;
1973 for (auto *Param : DetectedParams) {
1974 Param = extractConstantFactor(Param, *SE).second;
1975 Param = getRepresentingInvariantLoadSCEV(Param);
1976 if (Parameters.count(Param))
1977 continue;
1978 NewParams.insert(Param);
1979 }
1980
1981 SmallVector<isl_set *, 2> ConditionSets;
1982 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
1983 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
1984 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
1985 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
1986 isl_set_free(Dom);
1987
1988 if (!Valid)
1989 continue;
1990
1991 isl_set *AssumptionCtx = nullptr;
1992 if (InScop) {
1993 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
1994 isl_set_free(ConditionSets[0]);
1995 } else {
1996 AssumptionCtx = isl_set_complement(ConditionSets[1]);
1997 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
1998 }
1999
2000 // Project out newly introduced parameters as they are not otherwise useful.
2001 if (!NewParams.empty()) {
2002 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2003 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2004 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2005 isl_id_free(Id);
2006
2007 if (!NewParams.count(Param))
2008 continue;
2009
2010 AssumptionCtx =
2011 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2012 }
2013 }
2014
2015 emitOptimizationRemarkAnalysis(
2016 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
2017 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
2018 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002019 }
2020}
2021
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002022void Scop::addUserContext() {
2023 if (UserContextStr.empty())
2024 return;
2025
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002026 isl_set *UserContext =
2027 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002028 isl_space *Space = getParamSpace();
2029 if (isl_space_dim(Space, isl_dim_param) !=
2030 isl_set_dim(UserContext, isl_dim_param)) {
2031 auto SpaceStr = isl_space_to_str(Space);
2032 errs() << "Error: the context provided in -polly-context has not the same "
2033 << "number of dimensions than the computed context. Due to this "
2034 << "mismatch, the -polly-context option is ignored. Please provide "
2035 << "the context in the parameter space: " << SpaceStr << ".\n";
2036 free(SpaceStr);
2037 isl_set_free(UserContext);
2038 isl_space_free(Space);
2039 return;
2040 }
2041
2042 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002043 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2044 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002045
2046 if (strcmp(NameContext, NameUserContext) != 0) {
2047 auto SpaceStr = isl_space_to_str(Space);
2048 errs() << "Error: the name of dimension " << i
2049 << " provided in -polly-context "
2050 << "is '" << NameUserContext << "', but the name in the computed "
2051 << "context is '" << NameContext
2052 << "'. Due to this name mismatch, "
2053 << "the -polly-context option is ignored. Please provide "
2054 << "the context in the parameter space: " << SpaceStr << ".\n";
2055 free(SpaceStr);
2056 isl_set_free(UserContext);
2057 isl_space_free(Space);
2058 return;
2059 }
2060
2061 UserContext =
2062 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2063 isl_space_get_dim_id(Space, isl_dim_param, i));
2064 }
2065
2066 Context = isl_set_intersect(Context, UserContext);
2067 isl_space_free(Space);
2068}
2069
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002070void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002071 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002072
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002073 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002074 for (LoadInst *LInst : RIL) {
2075 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2076
Johannes Doerfert96e54712016-02-07 17:30:13 +00002077 Type *Ty = LInst->getType();
2078 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002079 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002080 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002081 continue;
2082 }
2083
2084 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002085 InvariantEquivClasses.emplace_back(
2086 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002087 }
2088}
2089
Tobias Grosser6be480c2011-11-08 15:41:13 +00002090void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002091 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002092 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002093 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002094 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002095}
2096
Tobias Grosser18daaca2012-05-22 10:47:27 +00002097void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002098 unsigned PDim = 0;
2099 for (auto *Parameter : Parameters) {
2100 ConstantRange SRange = SE->getSignedRange(Parameter);
2101 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002102 }
2103}
2104
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002105void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002106 if (PollyIgnoreParamBounds)
2107 return;
2108
Tobias Grosser6be480c2011-11-08 15:41:13 +00002109 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002110 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002111
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002112 unsigned PDim = 0;
2113 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002114 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002115 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002116 }
2117
2118 // Align the parameters of all data structures to the model.
2119 Context = isl_set_align_params(Context, Space);
2120
Johannes Doerferta60ad842016-05-10 12:18:22 +00002121 // As all parameters are known add bounds to them.
2122 addParameterBounds();
2123
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002124 for (ScopStmt &Stmt : *this)
2125 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002126
2127 // Simplify the schedule according to the context too.
2128 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002129}
2130
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002131static __isl_give isl_set *
2132simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2133 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002134 // If we have modeled all blocks in the SCoP that have side effects we can
2135 // simplify the context with the constraints that are needed for anything to
2136 // be executed at all. However, if we have error blocks in the SCoP we already
2137 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002138 // domains, thus we cannot use the remaining domain to simplify the
2139 // assumptions.
2140 if (!S.hasErrorBlock()) {
2141 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2142 AssumptionContext =
2143 isl_set_gist_params(AssumptionContext, DomainParameters);
2144 }
2145
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002146 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2147 return AssumptionContext;
2148}
2149
2150void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002151 // The parameter constraints of the iteration domains give us a set of
2152 // constraints that need to hold for all cases where at least a single
2153 // statement iteration is executed in the whole scop. We now simplify the
2154 // assumed context under the assumption that such constraints hold and at
2155 // least a single statement iteration is executed. For cases where no
2156 // statement instances are executed, the assumptions we have taken about
2157 // the executed code do not matter and can be changed.
2158 //
2159 // WARNING: This only holds if the assumptions we have taken do not reduce
2160 // the set of statement instances that are executed. Otherwise we
2161 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002162 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002163 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002164 // performed. In such a case, modifying the run-time conditions and
2165 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002166 // to not be executed.
2167 //
2168 // Example:
2169 //
2170 // When delinearizing the following code:
2171 //
2172 // for (long i = 0; i < 100; i++)
2173 // for (long j = 0; j < m; j++)
2174 // A[i+p][j] = 1.0;
2175 //
2176 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002177 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002178 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002179 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002180 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002181}
2182
Tobias Grosserc80d6972016-09-02 06:33:33 +00002183/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002184static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002185 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2186 isl_pw_multi_aff *MinPMA, *MaxPMA;
2187 isl_pw_aff *LastDimAff;
2188 isl_aff *OneAff;
2189 unsigned Pos;
2190
Johannes Doerfert6296d952016-04-22 11:38:19 +00002191 Set = isl_set_remove_divs(Set);
2192
Tobias Grosser90411a92017-02-16 19:11:33 +00002193 if (isl_set_n_basic_set(Set) >= MaxDisjunctsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002194 isl_set_free(Set);
2195 return isl_stat_error;
2196 }
2197
Johannes Doerfert9143d672014-09-27 11:02:39 +00002198 // Restrict the number of parameters involved in the access as the lexmin/
2199 // lexmax computation will take too long if this number is high.
2200 //
2201 // Experiments with a simple test case using an i7 4800MQ:
2202 //
2203 // #Parameters involved | Time (in sec)
2204 // 6 | 0.01
2205 // 7 | 0.04
2206 // 8 | 0.12
2207 // 9 | 0.40
2208 // 10 | 1.54
2209 // 11 | 6.78
2210 // 12 | 30.38
2211 //
2212 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2213 unsigned InvolvedParams = 0;
2214 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2215 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2216 InvolvedParams++;
2217
2218 if (InvolvedParams > RunTimeChecksMaxParameters) {
2219 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002220 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002221 }
2222 }
2223
Johannes Doerfertb164c792014-09-18 11:17:17 +00002224 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2225 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2226
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002227 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2228 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2229
Johannes Doerfertb164c792014-09-18 11:17:17 +00002230 // Adjust the last dimension of the maximal access by one as we want to
2231 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2232 // we test during code generation might now point after the end of the
2233 // allocated array but we will never dereference it anyway.
2234 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2235 "Assumed at least one output dimension");
2236 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2237 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2238 OneAff = isl_aff_zero_on_domain(
2239 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2240 OneAff = isl_aff_add_constant_si(OneAff, 1);
2241 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2242 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2243
2244 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2245
2246 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002247 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002248}
2249
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002250static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2251 isl_set *Domain = MA->getStatement()->getDomain();
2252 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2253 return isl_set_reset_tuple_id(Domain);
2254}
2255
Tobias Grosserc80d6972016-09-02 06:33:33 +00002256/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002257static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002258 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002259
Tobias Grossere9522232017-01-16 15:49:04 +00002260 MinMaxAccesses.reserve(AliasGroup.size());
2261
2262 isl_union_set *Domains = S.getDomains();
2263 isl_union_map *Accesses = isl_union_map_empty(S.getParamSpace());
2264
2265 for (MemoryAccess *MA : AliasGroup)
2266 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2267
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002268 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2269 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002270 Locations = isl_union_set_coalesce(Locations);
2271 Locations = isl_union_set_detect_equalities(Locations);
Tobias Grosserff400872017-02-01 10:12:09 +00002272 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
2273 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002274 isl_union_set_free(Locations);
2275 return Valid;
2276}
2277
Tobias Grosserc80d6972016-09-02 06:33:33 +00002278/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002279///
2280///{
2281
Tobias Grosserc80d6972016-09-02 06:33:33 +00002282/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002283static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2284 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2285 : RN->getNodeAs<BasicBlock>();
2286}
2287
Tobias Grosserc80d6972016-09-02 06:33:33 +00002288/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002289static inline BasicBlock *
2290getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002291 if (RN->isSubRegion()) {
2292 assert(idx == 0);
2293 return RN->getNodeAs<Region>()->getExit();
2294 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002295 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002296}
2297
Tobias Grosserc80d6972016-09-02 06:33:33 +00002298/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002299static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002300 if (!RN->isSubRegion()) {
2301 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2302 Loop *L = LI.getLoopFor(BB);
2303
2304 // Unreachable statements are not considered to belong to a LLVM loop, as
2305 // they are not part of an actual loop in the control flow graph.
2306 // Nevertheless, we handle certain unreachable statements that are common
2307 // when modeling run-time bounds checks as being part of the loop to be
2308 // able to model them and to later eliminate the run-time bounds checks.
2309 //
2310 // Specifically, for basic blocks that terminate in an unreachable and
2311 // where the immeditate predecessor is part of a loop, we assume these
2312 // basic blocks belong to the loop the predecessor belongs to. This
2313 // allows us to model the following code.
2314 //
2315 // for (i = 0; i < N; i++) {
2316 // if (i > 1024)
2317 // abort(); <- this abort might be translated to an
2318 // unreachable
2319 //
2320 // A[i] = ...
2321 // }
2322 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2323 L = LI.getLoopFor(BB->getPrevNode());
2324 return L;
2325 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002326
2327 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2328 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2329 while (L && NonAffineSubRegion->contains(L))
2330 L = L->getParentLoop();
2331 return L;
2332}
2333
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002334/// Get the number of blocks in @p L.
2335///
2336/// The number of blocks in a loop are the number of basic blocks actually
2337/// belonging to the loop, as well as all single basic blocks that the loop
2338/// exits to and which terminate in an unreachable instruction. We do not
2339/// allow such basic blocks in the exit of a scop, hence they belong to the
2340/// scop and represent run-time conditions which we want to model and
2341/// subsequently speculate away.
2342///
2343/// @see getRegionNodeLoop for additional details.
2344long getNumBlocksInLoop(Loop *L) {
2345 long NumBlocks = L->getNumBlocks();
2346 SmallVector<llvm::BasicBlock *, 4> ExitBlocks;
2347 L->getExitBlocks(ExitBlocks);
2348
2349 for (auto ExitBlock : ExitBlocks) {
2350 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2351 NumBlocks++;
2352 }
2353 return NumBlocks;
2354}
2355
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002356static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2357 if (!RN->isSubRegion())
2358 return 1;
2359
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002360 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002361 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002362}
2363
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002364static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2365 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002366 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002367 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002368 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002369 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002370 return true;
2371 return false;
2372}
2373
Johannes Doerfert96425c22015-08-30 21:13:53 +00002374///}
2375
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002376static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2377 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002378 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002379 isl_id *DimId =
2380 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2381 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2382}
2383
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002384__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002385 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002386}
2387
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002388__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002389 auto DIt = DomainMap.find(BB);
2390 if (DIt != DomainMap.end())
2391 return isl_set_copy(DIt->getSecond());
2392
2393 auto &RI = *R.getRegionInfo();
2394 auto *BBR = RI.getRegionFor(BB);
2395 while (BBR->getEntry() == BB)
2396 BBR = BBR->getParent();
2397 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002398}
2399
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002400bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002401
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002402 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002403 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002404 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2405 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002406 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002407
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002408 while (LD-- >= 0) {
2409 S = addDomainDimId(S, LD + 1, L);
2410 L = L->getParentLoop();
2411 }
2412
Johannes Doerferta3519512016-04-23 13:02:23 +00002413 // Initialize the invalid domain.
2414 auto *EntryStmt = getStmtFor(EntryBB);
2415 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2416
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002417 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002418
Johannes Doerfert432658d2016-01-26 11:01:41 +00002419 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002420 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002421
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002422 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002423 return false;
2424
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002425 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002426 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002427
2428 // Error blocks and blocks dominated by them have been assumed to never be
2429 // executed. Representing them in the Scop does not add any value. In fact,
2430 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002431 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002432 // will cause problems when building up a ScopStmt for them.
2433 // Furthermore, basic blocks dominated by error blocks may reference
2434 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002435 // can themselves not be constructed properly. To this end we will replace
2436 // the domains of error blocks and those only reachable via error blocks
2437 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002438 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002439 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002440 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002441 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002442
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002443 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002444}
2445
Tobias Grosserc80d6972016-09-02 06:33:33 +00002446/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002447/// to be compatible to domains constructed for loop @p NewL.
2448///
2449/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2450/// edge from @p OldL to @p NewL.
2451static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2452 __isl_take isl_set *Dom,
2453 Loop *OldL, Loop *NewL) {
2454
2455 // If the loops are the same there is nothing to do.
2456 if (NewL == OldL)
2457 return Dom;
2458
2459 int OldDepth = S.getRelativeLoopDepth(OldL);
2460 int NewDepth = S.getRelativeLoopDepth(NewL);
2461 // If both loops are non-affine loops there is nothing to do.
2462 if (OldDepth == -1 && NewDepth == -1)
2463 return Dom;
2464
2465 // Distinguish three cases:
2466 // 1) The depth is the same but the loops are not.
2467 // => One loop was left one was entered.
2468 // 2) The depth increased from OldL to NewL.
2469 // => One loop was entered, none was left.
2470 // 3) The depth decreased from OldL to NewL.
2471 // => Loops were left were difference of the depths defines how many.
2472 if (OldDepth == NewDepth) {
2473 assert(OldL->getParentLoop() == NewL->getParentLoop());
2474 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2475 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2476 Dom = addDomainDimId(Dom, NewDepth, NewL);
2477 } else if (OldDepth < NewDepth) {
2478 assert(OldDepth + 1 == NewDepth);
2479 auto &R = S.getRegion();
2480 (void)R;
2481 assert(NewL->getParentLoop() == OldL ||
2482 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2483 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2484 Dom = addDomainDimId(Dom, NewDepth, NewL);
2485 } else {
2486 assert(OldDepth > NewDepth);
2487 int Diff = OldDepth - NewDepth;
2488 int NumDim = isl_set_n_dim(Dom);
2489 assert(NumDim >= Diff);
2490 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2491 }
2492
2493 return Dom;
2494}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002495
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002496bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2497 LoopInfo &LI) {
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002498 ReversePostOrderTraversal<Region *> RTraversal(R);
2499 for (auto *RN : RTraversal) {
2500
2501 // Recurse for affine subregions but go on for basic blocks and non-affine
2502 // subregions.
2503 if (RN->isSubRegion()) {
2504 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002505 if (!isNonAffineSubRegion(SubRegion)) {
2506 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002507 continue;
2508 }
2509 }
2510
2511 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2512 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002513 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002514 isl_set *&Domain = DomainMap[BB];
2515 assert(Domain && "Cannot propagate a nullptr");
2516
Johannes Doerferta3519512016-04-23 13:02:23 +00002517 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002518 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002519 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002520
Johannes Doerferta3519512016-04-23 13:02:23 +00002521 if (!IsInvalidBlock) {
2522 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002523 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002524 isl_set_free(InvalidDomain);
2525 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002526 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2527 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2528 AS_RESTRICTION);
2529 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002530 }
2531
Johannes Doerferta3519512016-04-23 13:02:23 +00002532 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002533 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002534 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002535 }
2536
Johannes Doerferta3519512016-04-23 13:02:23 +00002537 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002538 auto *TI = BB->getTerminator();
2539 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2540 for (unsigned u = 0; u < NumSuccs; u++) {
2541 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002542 auto *SuccStmt = getStmtFor(SuccBB);
2543
2544 // Skip successors outside the SCoP.
2545 if (!SuccStmt)
2546 continue;
2547
Johannes Doerferte4459a22016-04-25 13:34:50 +00002548 // Skip backedges.
2549 if (DT.dominates(SuccBB, BB))
2550 continue;
2551
Michael Kruse55454072017-03-15 22:16:43 +00002552 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta3519512016-04-23 13:02:23 +00002553 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2554 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2555 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2556 SuccInvalidDomain =
2557 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2558 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2559 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2560 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002561
Michael Krusebc150122016-05-02 12:25:18 +00002562 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002563 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002564 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002565 continue;
2566
Johannes Doerferta3519512016-04-23 13:02:23 +00002567 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002568 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002569 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002570 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002571
2572 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002573 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002574
2575 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002576}
2577
Johannes Doerfert642594a2016-04-04 07:57:39 +00002578void Scop::propagateDomainConstraintsToRegionExit(
2579 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002580 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002581
2582 // Check if the block @p BB is the entry of a region. If so we propagate it's
2583 // domain to the exit block of the region. Otherwise we are done.
2584 auto *RI = R.getRegionInfo();
2585 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2586 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002587 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002588 return;
2589
Johannes Doerfert642594a2016-04-04 07:57:39 +00002590 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002591 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002592 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002593 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002594 SmallVector<BasicBlock *, 4> LatchBBs;
2595 BBLoop->getLoopLatches(LatchBBs);
2596 for (auto *LatchBB : LatchBBs)
2597 if (BB != LatchBB && BBReg->contains(LatchBB))
2598 return;
2599 L = L->getParentLoop();
2600 }
2601
2602 auto *Domain = DomainMap[BB];
2603 assert(Domain && "Cannot propagate a nullptr");
2604
Michael Kruse55454072017-03-15 22:16:43 +00002605 auto *ExitStmt = getStmtFor(ExitBB);
2606 auto *ExitBBLoop = ExitStmt->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002607
2608 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2609 // adjust the domain before we can propagate it.
2610 auto *AdjustedDomain =
2611 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2612 auto *&ExitDomain = DomainMap[ExitBB];
2613
2614 // If the exit domain is not yet created we set it otherwise we "add" the
2615 // current domain.
2616 ExitDomain =
2617 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2618
Johannes Doerferta3519512016-04-23 13:02:23 +00002619 // Initialize the invalid domain.
Johannes Doerferta3519512016-04-23 13:02:23 +00002620 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2621
Johannes Doerfert642594a2016-04-04 07:57:39 +00002622 FinishedExitBlocks.insert(ExitBB);
2623}
2624
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002625bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2626 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002627 // To create the domain for each block in R we iterate over all blocks and
2628 // subregions in R and propagate the conditions under which the current region
2629 // element is executed. To this end we iterate in reverse post order over R as
2630 // it ensures that we first visit all predecessors of a region node (either a
2631 // basic block or a subregion) before we visit the region node itself.
2632 // Initially, only the domain for the SCoP region entry block is set and from
2633 // there we propagate the current domain to all successors, however we add the
2634 // condition that the successor is actually executed next.
2635 // As we are only interested in non-loop carried constraints here we can
2636 // simply skip loop back edges.
2637
Johannes Doerfert642594a2016-04-04 07:57:39 +00002638 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002639 ReversePostOrderTraversal<Region *> RTraversal(R);
2640 for (auto *RN : RTraversal) {
2641
2642 // Recurse for affine subregions but go on for basic blocks and non-affine
2643 // subregions.
2644 if (RN->isSubRegion()) {
2645 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002646 if (!isNonAffineSubRegion(SubRegion)) {
2647 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002648 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002649 continue;
2650 }
2651 }
2652
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002653 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002654 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002655
Johannes Doerfert96425c22015-08-30 21:13:53 +00002656 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002657 TerminatorInst *TI = BB->getTerminator();
2658
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002659 if (isa<UnreachableInst>(TI))
2660 continue;
2661
Johannes Doerfertf5673802015-10-01 23:48:18 +00002662 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002663 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002664 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002665 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002666
Johannes Doerfert642594a2016-04-04 07:57:39 +00002667 auto *BBLoop = getRegionNodeLoop(RN, LI);
2668 // Propagate the domain from BB directly to blocks that have a superset
2669 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002670 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002671
2672 // If all successors of BB have been set a domain through the propagation
2673 // above we do not need to build condition sets but can just skip this
2674 // block. However, it is important to note that this is a local property
2675 // with regards to the region @p R. To this end FinishedExitBlocks is a
2676 // local variable.
2677 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2678 return FinishedExitBlocks.count(SuccBB);
2679 };
2680 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2681 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002682
2683 // Build the condition sets for the successor nodes of the current region
2684 // node. If it is a non-affine subregion we will always execute the single
2685 // exit node, hence the single entry node domain is the condition set. For
2686 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002687 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002688 if (RN->isSubRegion())
2689 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002690 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2691 ConditionSets))
2692 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002693
2694 // Now iterate over the successors and set their initial domain based on
2695 // their condition set. We skip back edges here and have to be careful when
2696 // we leave a loop not to keep constraints over a dimension that doesn't
2697 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002698 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002699 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002700 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002701 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002702
Johannes Doerfert535de032016-04-19 14:49:05 +00002703 auto *SuccStmt = getStmtFor(SuccBB);
2704 // Skip blocks outside the region.
2705 if (!SuccStmt) {
2706 isl_set_free(CondSet);
2707 continue;
2708 }
2709
Johannes Doerfert642594a2016-04-04 07:57:39 +00002710 // If we propagate the domain of some block to "SuccBB" we do not have to
2711 // adjust the domain.
2712 if (FinishedExitBlocks.count(SuccBB)) {
2713 isl_set_free(CondSet);
2714 continue;
2715 }
2716
Johannes Doerfert96425c22015-08-30 21:13:53 +00002717 // Skip back edges.
2718 if (DT.dominates(SuccBB, BB)) {
2719 isl_set_free(CondSet);
2720 continue;
2721 }
2722
Michael Kruse55454072017-03-15 22:16:43 +00002723 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002724 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002725
2726 // Set the domain for the successor or merge it with an existing domain in
2727 // case there are multiple paths (without loop back edges) to the
2728 // successor block.
2729 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002730
Johannes Doerferta3519512016-04-23 13:02:23 +00002731 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002732 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002733 } else {
2734 // Initialize the invalid domain.
2735 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2736 SuccDomain = CondSet;
2737 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002738
Michael Krusebc150122016-05-02 12:25:18 +00002739 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002740 // In case this happens we will clean up and bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002741 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002742 continue;
2743
2744 invalidate(COMPLEXITY, DebugLoc());
2745 while (++u < ConditionSets.size())
2746 isl_set_free(ConditionSets[u]);
2747 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002748 }
2749 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002750
2751 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002752}
2753
Michael Krused56b90a2016-09-01 09:03:27 +00002754__isl_give isl_set *
2755Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2756 __isl_keep isl_set *Domain,
2757 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002758 // If @p BB is the ScopEntry we are done
2759 if (R.getEntry() == BB)
2760 return isl_set_universe(isl_set_get_space(Domain));
2761
Johannes Doerfert642594a2016-04-04 07:57:39 +00002762 // The region info of this function.
2763 auto &RI = *R.getRegionInfo();
2764
Michael Kruse55454072017-03-15 22:16:43 +00002765 auto *BBLoop = getStmtFor(BB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002766
2767 // A domain to collect all predecessor domains, thus all conditions under
2768 // which the block is executed. To this end we start with the empty domain.
2769 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2770
2771 // Set of regions of which the entry block domain has been propagated to BB.
2772 // all predecessors inside any of the regions can be skipped.
2773 SmallSet<Region *, 8> PropagatedRegions;
2774
2775 for (auto *PredBB : predecessors(BB)) {
2776 // Skip backedges.
2777 if (DT.dominates(BB, PredBB))
2778 continue;
2779
2780 // If the predecessor is in a region we used for propagation we can skip it.
2781 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2782 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2783 PredBBInRegion)) {
2784 continue;
2785 }
2786
2787 // Check if there is a valid region we can use for propagation, thus look
2788 // for a region that contains the predecessor and has @p BB as exit block.
2789 auto *PredR = RI.getRegionFor(PredBB);
2790 while (PredR->getExit() != BB && !PredR->contains(BB))
2791 PredR->getParent();
2792
2793 // If a valid region for propagation was found use the entry of that region
2794 // for propagation, otherwise the PredBB directly.
2795 if (PredR->getExit() == BB) {
2796 PredBB = PredR->getEntry();
2797 PropagatedRegions.insert(PredR);
2798 }
2799
Johannes Doerfert41cda152016-04-08 10:32:26 +00002800 auto *PredBBDom = getDomainConditions(PredBB);
Michael Kruse55454072017-03-15 22:16:43 +00002801 auto *PredBBLoop = getStmtFor(PredBB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002802 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2803
2804 PredDom = isl_set_union(PredDom, PredBBDom);
2805 }
2806
2807 return PredDom;
2808}
2809
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002810bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2811 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002812 // Iterate over the region R and propagate the domain constrains from the
2813 // predecessors to the current node. In contrast to the
2814 // buildDomainsWithBranchConstraints function, this one will pull the domain
2815 // information from the predecessors instead of pushing it to the successors.
2816 // Additionally, we assume the domains to be already present in the domain
2817 // map here. However, we iterate again in reverse post order so we know all
2818 // predecessors have been visited before a block or non-affine subregion is
2819 // visited.
2820
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002821 ReversePostOrderTraversal<Region *> RTraversal(R);
2822 for (auto *RN : RTraversal) {
2823
2824 // Recurse for affine subregions but go on for basic blocks and non-affine
2825 // subregions.
2826 if (RN->isSubRegion()) {
2827 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002828 if (!isNonAffineSubRegion(SubRegion)) {
2829 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002830 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002831 continue;
2832 }
2833 }
2834
2835 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002836 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002837 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002838
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002839 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002840 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002841 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002842 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002843
Johannes Doerfert642594a2016-04-04 07:57:39 +00002844 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002845 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002846 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2847 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002848 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002849
2850 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002851}
2852
Tobias Grosserc80d6972016-09-02 06:33:33 +00002853/// Create a map to map from a given iteration to a subsequent iteration.
2854///
2855/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2856/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002857/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002858///
2859/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002860static __isl_give isl_map *
2861createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2862 auto *MapSpace = isl_space_map_from_set(SetSpace);
2863 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00002864 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002865 if (u != Dim)
2866 NextIterationMap =
2867 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2868 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2869 C = isl_constraint_set_constant_si(C, 1);
2870 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2871 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2872 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2873 return NextIterationMap;
2874}
2875
Johannes Doerfert297c7202016-05-10 13:06:42 +00002876bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002877 int LoopDepth = getRelativeLoopDepth(L);
2878 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002879
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002880 BasicBlock *HeaderBB = L->getHeader();
2881 assert(DomainMap.count(HeaderBB));
2882 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002883
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002884 isl_map *NextIterationMap =
2885 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002886
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002887 isl_set *UnionBackedgeCondition =
2888 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002889
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002890 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2891 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002892
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002893 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002894
2895 // If the latch is only reachable via error statements we skip it.
2896 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2897 if (!LatchBBDom)
2898 continue;
2899
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002900 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002901
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002902 TerminatorInst *TI = LatchBB->getTerminator();
2903 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00002904 assert(BI && "Only branch instructions allowed in loop latches");
2905
2906 if (BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002907 BackedgeCondition = isl_set_copy(LatchBBDom);
2908 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002909 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002910 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002911 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
Michael Krusee1dc3872016-11-03 15:19:41 +00002912 ConditionSets)) {
2913 isl_map_free(NextIterationMap);
2914 isl_set_free(UnionBackedgeCondition);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002915 return false;
Michael Krusee1dc3872016-11-03 15:19:41 +00002916 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002917
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002918 // Free the non back edge condition set as we do not need it.
2919 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002920
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002921 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002922 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002923
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002924 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2925 assert(LatchLoopDepth >= LoopDepth);
2926 BackedgeCondition =
2927 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2928 LatchLoopDepth - LoopDepth);
2929 UnionBackedgeCondition =
2930 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002931 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002932
2933 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2934 for (int i = 0; i < LoopDepth; i++)
2935 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2936
2937 isl_set *UnionBackedgeConditionComplement =
2938 isl_set_complement(UnionBackedgeCondition);
2939 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2940 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2941 UnionBackedgeConditionComplement =
2942 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2943 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2944 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2945
2946 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2947 HeaderBBDom = Parts.second;
2948
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002949 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2950 // the bounded assumptions to the context as they are already implied by the
2951 // <nsw> tag.
2952 if (Affinator.hasNSWAddRecForLoop(L)) {
2953 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002954 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002955 }
2956
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002957 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002958 recordAssumption(INFINITELOOP, UnboundedCtx,
2959 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002960 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002961}
2962
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002963MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00002964 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002965
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00002966 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002967 if (!PointerBaseInst)
2968 return nullptr;
2969
2970 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2971 if (!BasePtrStmt)
2972 return nullptr;
2973
2974 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2975}
2976
2977bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2978 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00002979 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
2980 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
2981 bool Hoistable = NHCtx != nullptr;
2982 isl_set_free(NHCtx);
2983 return !Hoistable;
2984 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002985
Tobias Grosserbe372d52017-02-09 10:11:58 +00002986 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00002987 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002988 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00002989 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002990
2991 return false;
2992}
2993
Johannes Doerfert5210da52016-06-02 11:06:54 +00002994bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002995 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00002996 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002997
Johannes Doerfertcd195322016-11-17 21:41:08 +00002998 if (buildAliasGroups(AA)) {
2999 // Aliasing assumptions do not go through addAssumption but we still want to
3000 // collect statistics so we do it here explicitly.
3001 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003002 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003003 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003004 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003005
3006 // If a problem occurs while building the alias groups we need to delete
3007 // this SCoP and pretend it wasn't valid in the first place. To this end
3008 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003009 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003010
3011 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3012 << " could not be created as the number of parameters involved "
3013 "is too high. The SCoP will be "
3014 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3015 "the maximal number of parameters but be advised that the "
3016 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003017 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003018}
3019
Tobias Grosser889830b2017-02-09 23:12:22 +00003020std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003021Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003022 AliasSetTracker AST(AA);
3023
3024 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003025 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003026 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003027
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003028 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003029 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3030 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003031
3032 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003033 if (StmtDomainEmpty)
3034 continue;
3035
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003036 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003037 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003038 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003039 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003040 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003041 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003042 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003043 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003044 else
3045 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003046 AST.add(Acc);
3047 }
3048 }
3049
Tobias Grosser9edcf072017-01-16 14:07:57 +00003050 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003051 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003052 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003053 continue;
3054 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003055 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003056 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003057 if (AG.size() < 2)
3058 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003059 AliasGroups.push_back(std::move(AG));
3060 }
3061
Tobias Grosser9edcf072017-01-16 14:07:57 +00003062 return std::make_tuple(AliasGroups, HasWriteAccess);
3063}
3064
Tobias Grossere39f9122017-01-16 14:08:00 +00003065void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003066 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3067 AliasGroupTy NewAG;
3068 AliasGroupTy &AG = AliasGroups[u];
3069 AliasGroupTy::iterator AGI = AG.begin();
3070 isl_set *AGDomain = getAccessDomain(*AGI);
3071 while (AGI != AG.end()) {
3072 MemoryAccess *MA = *AGI;
3073 isl_set *MADomain = getAccessDomain(MA);
3074 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3075 NewAG.push_back(MA);
3076 AGI = AG.erase(AGI);
3077 isl_set_free(MADomain);
3078 } else {
3079 AGDomain = isl_set_union(AGDomain, MADomain);
3080 AGI++;
3081 }
3082 }
3083 if (NewAG.size() > 1)
3084 AliasGroups.push_back(std::move(NewAG));
3085 isl_set_free(AGDomain);
3086 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003087}
3088
3089bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3090 // To create sound alias checks we perform the following steps:
3091 // o) We partition each group into read only and non read only accesses.
3092 // o) For each group with more than one base pointer we then compute minimal
3093 // and maximal accesses to each array of a group in read only and non
3094 // read only partitions separately.
3095 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003096 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003097
3098 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3099
3100 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003101
Johannes Doerfert13771732014-10-01 12:40:46 +00003102 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003103 bool Valid = buildAliasGroup(AG, HasWriteAccess);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003104 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003105 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003106 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003107
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003108 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003109}
3110
Tobias Grosser77f32572017-01-16 15:49:07 +00003111bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003112 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003113 AliasGroupTy ReadOnlyAccesses;
3114 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003115 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003116 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003117
3118 auto &F = getFunction();
3119
3120 if (AliasGroup.size() < 2)
3121 return true;
3122
3123 for (MemoryAccess *Access : AliasGroup) {
3124 emitOptimizationRemarkAnalysis(
3125 F.getContext(), DEBUG_TYPE, F,
3126 Access->getAccessInstruction()->getDebugLoc(),
3127 "Possibly aliasing pointer, use restrict keyword.");
3128
Tobias Grosser889830b2017-02-09 23:12:22 +00003129 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3130 if (HasWriteAccess.count(Array)) {
3131 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003132 ReadWriteAccesses.push_back(Access);
3133 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003134 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003135 ReadOnlyAccesses.push_back(Access);
3136 }
3137 }
3138
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003139 // If there are no read-only pointers, and less than two read-write pointers,
3140 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003141 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003142 return true;
3143
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003144 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003145 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003146 return true;
3147
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003148 // For non-affine accesses, no alias check can be generated as we cannot
3149 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003150 for (MemoryAccess *MA : AliasGroup) {
3151 if (!MA->isAffine()) {
3152 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3153 return false;
3154 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003155 }
3156
3157 // Ensure that for all memory accesses for which we generate alias checks,
3158 // their base pointers are available.
3159 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003160 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3161 addRequiredInvariantLoad(
3162 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3163 }
3164
3165 MinMaxAliasGroups.emplace_back();
3166 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3167 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3168 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3169
3170 bool Valid;
3171
3172 Valid =
3173 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3174
3175 if (!Valid)
3176 return false;
3177
3178 // Bail out if the number of values we need to compare is too large.
3179 // This is important as the number of comparisons grows quadratically with
3180 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003181 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003182 RunTimeChecksMaxArraysPerGroup)
3183 return false;
3184
3185 Valid =
3186 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3187
3188 if (!Valid)
3189 return false;
3190
3191 return true;
3192}
3193
Tobias Grosserc80d6972016-09-02 06:33:33 +00003194/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003195static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003196 // Start with the smallest loop containing the entry and expand that
3197 // loop until it contains all blocks in the region. If there is a loop
3198 // containing all blocks in the region check if it is itself contained
3199 // and if so take the parent loop as it will be the smallest containing
3200 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003201 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003202 while (L) {
3203 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003204 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003205 AllContained &= L->contains(BB);
3206 if (AllContained)
3207 break;
3208 L = L->getParentLoop();
3209 }
3210
Johannes Doerfertef744432016-05-23 12:42:38 +00003211 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003212}
3213
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003214Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003215 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003216 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003217 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003218 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3219 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3220 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3221 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003222 if (IslOnErrorAbort)
3223 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003224 buildContext();
3225}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003226
Tobias Grosserbedef002016-12-02 08:10:56 +00003227void Scop::foldSizeConstantsToRight() {
3228 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3229
3230 for (auto Array : arrays()) {
3231 if (Array->getNumberOfDimensions() <= 1)
3232 continue;
3233
3234 isl_space *Space = Array->getSpace();
3235
3236 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3237
3238 if (!isl_union_set_contains(Accessed, Space)) {
3239 isl_space_free(Space);
3240 continue;
3241 }
3242
3243 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3244
3245 isl_map *Transform =
3246 isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3247
3248 std::vector<int> Int;
3249
3250 int Dims = isl_set_dim(Elements, isl_dim_set);
3251 for (int i = 0; i < Dims; i++) {
3252 isl_set *DimOnly =
3253 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3254 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3255 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3256
3257 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3258
3259 if (i == Dims - 1) {
3260 Int.push_back(1);
3261 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3262 isl_basic_set_free(DimHull);
3263 continue;
3264 }
3265
3266 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3267 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3268 isl_val *Val = isl_aff_get_denominator_val(Diff);
3269 isl_aff_free(Diff);
3270
3271 int ValInt = 1;
3272
3273 if (isl_val_is_int(Val))
3274 ValInt = isl_val_get_num_si(Val);
3275 isl_val_free(Val);
3276
3277 Int.push_back(ValInt);
3278
3279 isl_constraint *C = isl_constraint_alloc_equality(
3280 isl_local_space_from_space(isl_map_get_space(Transform)));
3281 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3282 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3283 Transform = isl_map_add_constraint(Transform, C);
3284 isl_basic_set_free(DimHull);
3285 continue;
3286 }
3287
3288 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3289 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3290
3291 int ValInt = 1;
3292 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3293 ValInt = 0;
3294 }
3295
3296 Int.push_back(ValInt);
3297 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3298 isl_basic_set_free(DimHull);
3299 isl_basic_set_free(ZeroSet);
3300 }
3301
3302 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3303
3304 if (!isl_set_is_subset(Elements, MappedElements)) {
3305 isl_set_free(Elements);
3306 isl_set_free(MappedElements);
3307 isl_map_free(Transform);
3308 continue;
3309 }
3310
3311 isl_set_free(MappedElements);
3312
3313 bool CanFold = true;
3314
3315 if (Int[0] <= 1)
3316 CanFold = false;
3317
3318 unsigned NumDims = Array->getNumberOfDimensions();
3319 for (unsigned i = 1; i < NumDims - 1; i++)
3320 if (Int[0] != Int[i] && Int[i])
3321 CanFold = false;
3322
3323 if (!CanFold) {
3324 isl_set_free(Elements);
3325 isl_map_free(Transform);
3326 continue;
3327 }
3328
Tobias Grosserbedef002016-12-02 08:10:56 +00003329 for (auto &Access : AccessFunctions)
3330 if (Access->getScopArrayInfo() == Array)
3331 Access->setAccessRelation(isl_map_apply_range(
3332 Access->getAccessRelation(), isl_map_copy(Transform)));
3333
3334 isl_map_free(Transform);
3335
3336 std::vector<const SCEV *> Sizes;
3337 for (unsigned i = 0; i < NumDims; i++) {
3338 auto Size = Array->getDimensionSize(i);
3339
3340 if (i == NumDims - 1)
3341 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3342 Sizes.push_back(Size);
3343 }
3344
3345 Array->updateSizes(Sizes, false /* CheckConsistency */);
3346
3347 isl_set_free(Elements);
3348 }
3349 isl_union_set_free(Accessed);
3350 return;
3351}
3352
Tobias Grosser491b7992016-12-02 05:21:22 +00003353void Scop::finalizeAccesses() {
3354 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003355 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003356 foldAccessRelations();
3357 assumeNoOutOfBounds();
3358}
3359
Michael Kruse89b1f942017-03-17 13:56:53 +00003360void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT,
3361 LoopInfo &LI) {
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003362 buildInvariantEquivalenceClasses();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003363
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003364 if (!buildDomains(&R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003365 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003366
Michael Kruse89b1f942017-03-17 13:56:53 +00003367 addUserAssumptions(AC, DT, LI);
Johannes Doerfertff68f462016-04-19 14:49:42 +00003368
Johannes Doerfert26404542016-05-10 12:19:47 +00003369 // Remove empty statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003370 // Exit early in case there are no executable statements left in this scop.
Michael Kruse977d38b2016-07-22 17:31:17 +00003371 simplifySCoP(false);
Michael Kruseafe06702015-10-02 16:33:27 +00003372 if (Stmts.empty())
3373 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003374
Michael Krusecac948e2015-10-02 13:53:07 +00003375 // The ScopStmts now have enough information to initialize themselves.
3376 for (ScopStmt &Stmt : Stmts)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003377 Stmt.init(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00003378
Johannes Doerfertb1d66082016-12-01 11:12:14 +00003379 // Check early for a feasible runtime context.
3380 if (!hasFeasibleRuntimeContext())
3381 return;
3382
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003383 // Check early for profitability. Afterwards it cannot change anymore,
3384 // only the runtime context could become infeasible.
Michael Krusef3091bf2017-03-17 13:09:52 +00003385 if (!isProfitable(UnprofitableScalarAccs)) {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003386 invalidate(PROFITABLE, DebugLoc());
Tobias Grosser8286b832015-11-02 11:29:32 +00003387 return;
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003388 }
3389
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003390 buildSchedule(LI);
Tobias Grosser8286b832015-11-02 11:29:32 +00003391
Tobias Grosser491b7992016-12-02 05:21:22 +00003392 finalizeAccesses();
3393
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003394 realignParams();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003395 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003396
3397 // After the context was fully constructed, thus all our knowledge about
3398 // the parameters is in there, we add all recorded assumptions to the
3399 // assumed/invalid context.
3400 addRecordedAssumptions();
3401
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003402 simplifyContexts();
Johannes Doerfert5210da52016-06-02 11:06:54 +00003403 if (!buildAliasChecks(AA))
3404 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003405
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003406 hoistInvariantLoads();
3407 verifyInvariantLoads();
Michael Kruse977d38b2016-07-22 17:31:17 +00003408 simplifySCoP(true);
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003409
3410 // Check late for a feasible runtime context because profitability did not
3411 // change.
Johannes Doerfertb1d66082016-12-01 11:12:14 +00003412 if (!hasFeasibleRuntimeContext())
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003413 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003414}
3415
3416Scop::~Scop() {
3417 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003418 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003419 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003420 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003421
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003422 for (auto &It : ParameterIds)
3423 isl_id_free(It.second);
3424
Johannes Doerfert96425c22015-08-30 21:13:53 +00003425 for (auto It : DomainMap)
3426 isl_set_free(It.second);
3427
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003428 for (auto &AS : RecordedAssumptions)
3429 isl_set_free(AS.Set);
3430
Johannes Doerfertb164c792014-09-18 11:17:17 +00003431 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003432 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003433 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003434 isl_pw_multi_aff_free(MMA.first);
3435 isl_pw_multi_aff_free(MMA.second);
3436 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003437 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003438 isl_pw_multi_aff_free(MMA.first);
3439 isl_pw_multi_aff_free(MMA.second);
3440 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003441 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003442
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003443 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003444 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003445
3446 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003447 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003448 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003449 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003450 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003451 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003452 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003453}
3454
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003455void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003456 // Check all array accesses for each base pointer and find a (virtual) element
3457 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003458 for (ScopStmt &Stmt : *this)
3459 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003460 if (!Access->isArrayKind())
3461 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003462 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003463 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3464
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003465 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003466 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003467 unsigned DivisibleSize = Array->getElemSizeInBytes();
3468 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003469 while (!isDivisible(Subscript, DivisibleSize, *SE))
3470 DivisibleSize /= 2;
3471 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003472 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003473 }
3474
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003475 for (auto &Stmt : *this)
3476 for (auto &Access : Stmt)
3477 Access->updateDimensionality();
3478}
3479
Tobias Grosser491b7992016-12-02 05:21:22 +00003480void Scop::foldAccessRelations() {
3481 for (auto &Stmt : *this)
3482 for (auto &Access : Stmt)
3483 Access->foldAccessRelation();
3484}
3485
3486void Scop::assumeNoOutOfBounds() {
3487 for (auto &Stmt : *this)
3488 for (auto &Access : Stmt)
3489 Access->assumeNoOutOfBound();
3490}
3491
Michael Kruse977d38b2016-07-22 17:31:17 +00003492void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003493 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3494 ScopStmt &Stmt = *StmtIt;
3495
Johannes Doerfert26404542016-05-10 12:19:47 +00003496 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003497 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003498 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003499
Johannes Doerferteca9e892015-11-03 16:54:49 +00003500 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003501 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003502 bool OnlyRead = true;
3503 for (MemoryAccess *MA : Stmt) {
3504 if (MA->isRead())
3505 continue;
3506
3507 OnlyRead = false;
3508 break;
3509 }
3510
3511 RemoveStmt = OnlyRead;
3512 }
3513
Johannes Doerfert26404542016-05-10 12:19:47 +00003514 if (!RemoveStmt) {
3515 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003516 continue;
3517 }
3518
Johannes Doerfert26404542016-05-10 12:19:47 +00003519 // Remove the statement because it is unnecessary.
3520 if (Stmt.isRegionStmt())
3521 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3522 StmtMap.erase(BB);
3523 else
3524 StmtMap.erase(Stmt.getBasicBlock());
3525
3526 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003527 }
3528}
3529
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003530InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003531 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3532 if (!LInst)
3533 return nullptr;
3534
3535 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3536 LInst = cast<LoadInst>(Rep);
3537
Johannes Doerfert96e54712016-02-07 17:30:13 +00003538 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003539 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003540 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003541 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003542 continue;
3543
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003544 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003545 for (auto *MA : MAs)
3546 if (MA->getAccessInstruction() == Val)
3547 return &IAClass;
3548 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003549
3550 return nullptr;
3551}
3552
Tobias Grosserc80d6972016-09-02 06:33:33 +00003553/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003554static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003555 bool MAInvalidCtxIsEmpty,
3556 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003557 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3558 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3559 // TODO: We can provide more information for better but more expensive
3560 // results.
3561 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3562 LInst->getAlignment(), DL))
3563 return false;
3564
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003565 // If the location might be overwritten we do not hoist it unconditionally.
3566 //
3567 // TODO: This is probably to conservative.
3568 if (!NonHoistableCtxIsEmpty)
3569 return false;
3570
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003571 // If a dereferencable load is in a statement that is modeled precisely we can
3572 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003573 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003574 return true;
3575
3576 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003577 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003578 // statement domain.
3579 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3580 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3581 return false;
3582 return true;
3583}
3584
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003585void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003586
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003587 if (InvMAs.empty())
3588 return;
3589
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003590 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003591 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003592
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003593 // Get the context under which the statement is executed but remove the error
3594 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003595 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003596 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003597
Tobias Grosser90411a92017-02-16 19:11:33 +00003598 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003599 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003600 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3601 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003602 for (auto &InvMA : InvMAs)
3603 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003604 return;
3605 }
3606
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003607 // Project out all parameters that relate to loads in the statement. Otherwise
3608 // we could have cyclic dependences on the constraints under which the
3609 // hoisted loads are executed and we could not determine an order in which to
3610 // pre-load them. This happens because not only lower bounds are part of the
3611 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003612 for (auto &InvMA : InvMAs) {
3613 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003614 Instruction *AccInst = MA->getAccessInstruction();
3615 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003616 SetVector<Value *> Values;
3617 for (const SCEV *Parameter : Parameters) {
3618 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003619 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003620 if (!Values.count(AccInst))
3621 continue;
3622
3623 if (isl_id *ParamId = getIdForParam(Parameter)) {
3624 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003625 if (Dim >= 0)
3626 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003627 isl_id_free(ParamId);
3628 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003629 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003630 }
3631 }
3632
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003633 for (auto &InvMA : InvMAs) {
3634 auto *MA = InvMA.MA;
3635 auto *NHCtx = InvMA.NonHoistableCtx;
3636
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003637 // Check for another invariant access that accesses the same location as
3638 // MA and if found consolidate them. Otherwise create a new equivalence
3639 // class at the end of InvariantEquivClasses.
3640 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003641 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003642 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3643
Johannes Doerfert85676e32016-04-23 14:32:34 +00003644 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003645 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003646 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3647
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003648 isl_set *MACtx;
3649 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003650 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3651 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003652 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003653 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003654 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003655 } else {
3656 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003657 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003658 MACtx = isl_set_gist_params(MACtx, getContext());
3659 }
3660
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003661 bool Consolidated = false;
3662 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003663 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003664 continue;
3665
Johannes Doerfertdf880232016-03-03 12:26:58 +00003666 // If the pointer and the type is equal check if the access function wrt.
3667 // to the domain is equal too. It can happen that the domain fixes
3668 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003669 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003670 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003671 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003672 if (!MAs.empty()) {
3673 auto *LastMA = MAs.front();
3674
3675 auto *AR = isl_map_range(MA->getAccessRelation());
3676 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3677 bool SameAR = isl_set_is_equal(AR, LastAR);
3678 isl_set_free(AR);
3679 isl_set_free(LastAR);
3680
3681 if (!SameAR)
3682 continue;
3683 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003684
3685 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003686 MAs.push_front(MA);
3687
Johannes Doerfertdf880232016-03-03 12:26:58 +00003688 Consolidated = true;
3689
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003690 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003691 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003692 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003693 IAClassDomainCtx =
3694 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003695 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003696 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003697 break;
3698 }
3699
3700 if (Consolidated)
3701 continue;
3702
3703 // If we did not consolidate MA, thus did not find an equivalence class
3704 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003705 InvariantEquivClasses.emplace_back(
3706 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003707 }
3708
3709 isl_set_free(DomainCtx);
3710}
3711
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003712__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3713 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003714 // TODO: Loads that are not loop carried, hence are in a statement with
3715 // zero iterators, are by construction invariant, though we
3716 // currently "hoist" them anyway. This is necessary because we allow
3717 // them to be treated as parameters (e.g., in conditions) and our code
3718 // generation would otherwise use the old value.
3719
3720 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003721 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003722
Johannes Doerfertc9765462016-11-17 22:11:56 +00003723 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3724 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003725 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003726
3727 // Skip accesses that have an invariant base pointer which is defined but
3728 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3729 // returns a pointer that is used as a base address. However, as we want
3730 // to hoist indirect pointers, we allow the base pointer to be defined in
3731 // the region if it is also a memory access. Each ScopArrayInfo object
3732 // that has a base pointer origin has a base pointer that is loaded and
3733 // that it is invariant, thus it will be hoisted too. However, if there is
3734 // no base pointer origin we check that the base pointer is defined
3735 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003736 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003737 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003738 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003739
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +00003740 auto &DL = getFunction().getParent()->getDataLayout();
3741 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
3742 DL))
3743 return isl_set_empty(getParamSpace());
3744
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003745 // Skip accesses in non-affine subregions as they might not be executed
3746 // under the same condition as the entry of the non-affine subregion.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003747 if (BB != LI->getParent())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003748 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003749
3750 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003751 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003752
3753 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3754 Stmt.getNumIterators())) {
3755 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003756 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003757 }
3758
3759 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3760 isl_set *AccessRange = isl_map_range(AccessRelation);
3761
3762 isl_union_map *Written = isl_union_map_intersect_range(
3763 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003764 auto *WrittenCtx = isl_union_map_params(Written);
3765 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003766
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003767 if (!IsWritten)
3768 return WrittenCtx;
3769
3770 WrittenCtx = isl_set_remove_divs(WrittenCtx);
Tobias Grosser90411a92017-02-16 19:11:33 +00003771 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctsInDomain;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003772 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3773 isl_set_free(WrittenCtx);
3774 return nullptr;
3775 }
3776
3777 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3778 AS_RESTRICTION);
3779 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003780}
3781
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003782void Scop::verifyInvariantLoads() {
3783 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003784 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003785 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003786 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003787 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003788 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3789 return;
3790 }
3791 }
3792}
3793
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003794void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003795 if (!PollyInvariantLoadHoisting)
3796 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003797
Tobias Grosser0865e7752016-02-29 07:29:42 +00003798 isl_union_map *Writes = getWrites();
3799 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003800 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003801
Tobias Grosser0865e7752016-02-29 07:29:42 +00003802 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003803 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3804 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003805
3806 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003807 for (auto InvMA : InvariantAccesses)
3808 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003809 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003810 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003811 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003812}
3813
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003814const ScopArrayInfo *
3815Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
3816 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
3817 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00003818 assert((BasePtr || BaseName) &&
3819 "BasePtr and BaseName can not be nullptr at the same time.");
3820 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3821 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3822 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003823 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003824 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003825 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003826 DL, this, BaseName));
3827 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003828 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003829 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003830 // In case of mismatching array sizes, we bail out by setting the run-time
3831 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003832 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003833 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003834 }
Tobias Grosserab671442015-05-23 05:58:27 +00003835 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003836}
3837
Roman Gareevd7754a12016-07-30 09:25:51 +00003838const ScopArrayInfo *
3839Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3840 const std::vector<unsigned> &Sizes) {
3841 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3842 std::vector<const SCEV *> SCEVSizes;
3843
3844 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003845 if (size)
3846 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3847 else
3848 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003849
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003850 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3851 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00003852 return SAI;
3853}
3854
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003855const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003856 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003857 assert(SAI && "No ScopArrayInfo available for this base pointer");
3858 return SAI;
3859}
3860
Tobias Grosser74394f02013-01-14 22:40:23 +00003861std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003862
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003863std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003864 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003865 return stringFromIslObj(AssumedContext);
3866}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003867
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003868std::string Scop::getInvalidContextStr() const {
3869 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003870}
Tobias Grosser75805372011-04-29 06:27:02 +00003871
3872std::string Scop::getNameStr() const {
3873 std::string ExitName, EntryName;
3874 raw_string_ostream ExitStr(ExitName);
3875 raw_string_ostream EntryStr(EntryName);
3876
Tobias Grosserf240b482014-01-09 10:42:15 +00003877 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003878 EntryStr.str();
3879
3880 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003881 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003882 ExitStr.str();
3883 } else
3884 ExitName = "FunctionExit";
3885
3886 return EntryName + "---" + ExitName;
3887}
3888
Tobias Grosser74394f02013-01-14 22:40:23 +00003889__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003890__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003891 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003892}
3893
Tobias Grossere86109f2013-10-29 21:05:49 +00003894__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003895 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003896 return isl_set_copy(AssumedContext);
3897}
3898
Michael Krusef3091bf2017-03-17 13:09:52 +00003899bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003900 if (PollyProcessUnprofitable)
3901 return true;
3902
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003903 if (isEmpty())
3904 return false;
3905
3906 unsigned OptimizableStmtsOrLoops = 0;
3907 for (auto &Stmt : *this) {
3908 if (Stmt.getNumIterators() == 0)
3909 continue;
3910
3911 bool ContainsArrayAccs = false;
3912 bool ContainsScalarAccs = false;
3913 for (auto *MA : Stmt) {
3914 if (MA->isRead())
3915 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00003916 ContainsArrayAccs |= MA->isLatestArrayKind();
3917 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003918 }
3919
Michael Krusef3091bf2017-03-17 13:09:52 +00003920 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003921 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3922 }
3923
3924 return OptimizableStmtsOrLoops > 1;
3925}
3926
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003927bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003928 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003929 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003930 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3931 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3932 isl_set_is_subset(PositiveContext, NegativeContext));
3933 isl_set_free(PositiveContext);
3934 if (!IsFeasible) {
3935 isl_set_free(NegativeContext);
3936 return false;
3937 }
3938
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003939 auto *DomainContext = isl_union_set_params(getDomains());
3940 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003941 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003942 isl_set_free(NegativeContext);
3943 isl_set_free(DomainContext);
3944
Johannes Doerfert43788c52015-08-20 05:58:56 +00003945 return IsFeasible;
3946}
3947
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003948static std::string toString(AssumptionKind Kind) {
3949 switch (Kind) {
3950 case ALIASING:
3951 return "No-aliasing";
3952 case INBOUNDS:
3953 return "Inbounds";
3954 case WRAPPING:
3955 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00003956 case UNSIGNED:
3957 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003958 case COMPLEXITY:
3959 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003960 case PROFITABLE:
3961 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003962 case ERRORBLOCK:
3963 return "No-error";
3964 case INFINITELOOP:
3965 return "Finite loop";
3966 case INVARIANTLOAD:
3967 return "Invariant load";
3968 case DELINEARIZATION:
3969 return "Delinearization";
3970 }
3971 llvm_unreachable("Unknown AssumptionKind!");
3972}
3973
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003974bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
3975 if (Sign == AS_ASSUMPTION) {
3976 if (isl_set_is_subset(Context, Set))
3977 return false;
3978
3979 if (isl_set_is_subset(AssumedContext, Set))
3980 return false;
3981 } else {
3982 if (isl_set_is_disjoint(Set, Context))
3983 return false;
3984
3985 if (isl_set_is_subset(Set, InvalidContext))
3986 return false;
3987 }
3988 return true;
3989}
3990
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003991bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3992 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003993 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
3994 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003995
Johannes Doerfertb3265a32016-11-17 22:08:40 +00003996 // Do never emit trivial assumptions as they only clutter the output.
3997 if (!PollyRemarksMinimal) {
3998 isl_set *Univ = nullptr;
3999 if (Sign == AS_ASSUMPTION)
4000 Univ = isl_set_universe(isl_set_get_space(Set));
4001
4002 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4003 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4004 isl_set_free(Univ);
4005
4006 if (IsTrivial)
4007 return false;
4008 }
4009
Johannes Doerfertcd195322016-11-17 21:41:08 +00004010 switch (Kind) {
4011 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004012 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004013 break;
4014 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004015 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004016 break;
4017 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004018 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004019 break;
4020 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004021 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004022 break;
4023 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004024 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004025 break;
4026 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004027 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004028 break;
4029 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004030 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004031 break;
4032 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004033 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004034 break;
4035 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004036 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004037 break;
4038 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004039 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004040 break;
4041 }
4042
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004043 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004044 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4045 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004046 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004047 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004048}
4049
4050void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004051 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004052 // Simplify the assumptions/restrictions first.
4053 Set = isl_set_gist_params(Set, getContext());
4054
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004055 if (!trackAssumption(Kind, Set, Loc, Sign)) {
4056 isl_set_free(Set);
4057 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004058 }
4059
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004060 if (Sign == AS_ASSUMPTION) {
4061 AssumedContext = isl_set_intersect(AssumedContext, Set);
4062 AssumedContext = isl_set_coalesce(AssumedContext);
4063 } else {
4064 InvalidContext = isl_set_union(InvalidContext, Set);
4065 InvalidContext = isl_set_coalesce(InvalidContext);
4066 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004067}
4068
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004069void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004070 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004071 assert((isl_set_is_params(Set) || BB) &&
4072 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004073 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004074}
4075
4076void Scop::addRecordedAssumptions() {
4077 while (!RecordedAssumptions.empty()) {
4078 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004079
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004080 if (!AS.BB) {
4081 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
4082 continue;
4083 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004084
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004085 // If the domain was deleted the assumptions are void.
4086 isl_set *Dom = getDomainConditions(AS.BB);
4087 if (!Dom) {
4088 isl_set_free(AS.Set);
4089 continue;
4090 }
4091
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004092 // If a basic block was given use its domain to simplify the assumption.
4093 // In case of restrictions we know they only have to hold on the domain,
4094 // thus we can intersect them with the domain of the block. However, for
4095 // assumptions the domain has to imply them, thus:
4096 // _ _____
4097 // Dom => S <==> A v B <==> A - B
4098 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004099 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004100 // assumption.
4101 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004102 if (AS.Sign == AS_RESTRICTION)
4103 S = isl_set_params(isl_set_intersect(S, Dom));
4104 else /* (AS.Sign == AS_ASSUMPTION) */
4105 S = isl_set_params(isl_set_subtract(Dom, S));
4106
4107 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004108 }
4109}
4110
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004111void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004112 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004113}
4114
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004115__isl_give isl_set *Scop::getInvalidContext() const {
4116 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004117}
4118
Tobias Grosser75805372011-04-29 06:27:02 +00004119void Scop::printContext(raw_ostream &OS) const {
4120 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004121 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004122
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004123 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004124 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004125
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004126 OS.indent(4) << "Invalid Context:\n";
4127 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004128
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004129 unsigned Dim = 0;
4130 for (const SCEV *Parameter : Parameters)
4131 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004132}
4133
Johannes Doerfertb164c792014-09-18 11:17:17 +00004134void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004135 int noOfGroups = 0;
4136 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004137 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004138 noOfGroups += 1;
4139 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004140 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004141 }
4142
Tobias Grosserbb853c22015-07-25 12:31:03 +00004143 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004144 if (MinMaxAliasGroups.empty()) {
4145 OS.indent(8) << "n/a\n";
4146 return;
4147 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004148
Tobias Grosserbb853c22015-07-25 12:31:03 +00004149 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004150
4151 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004152 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004153 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004154 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004155 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4156 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004157 }
4158 OS << " ]]\n";
4159 }
4160
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004161 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004162 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004163 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004164 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004165 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4166 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004167 }
4168 OS << " ]]\n";
4169 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004170 }
4171}
4172
Tobias Grosser75805372011-04-29 06:27:02 +00004173void Scop::printStatements(raw_ostream &OS) const {
4174 OS << "Statements {\n";
4175
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004176 for (const ScopStmt &Stmt : *this)
4177 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00004178
4179 OS.indent(4) << "}\n";
4180}
4181
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004182void Scop::printArrayInfo(raw_ostream &OS) const {
4183 OS << "Arrays {\n";
4184
Tobias Grosserab671442015-05-23 05:58:27 +00004185 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004186 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004187
4188 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004189
4190 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4191
4192 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004193 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004194
4195 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004196}
4197
Tobias Grosser75805372011-04-29 06:27:02 +00004198void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004199 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004200 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004201 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004202 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004203 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004204 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004205 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004206 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004207 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004208 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004209 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4210 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004211 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004212 }
4213 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004214 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004215 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004216 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00004217 printStatements(OS.indent(4));
4218}
4219
4220void Scop::dump() const { print(dbgs()); }
4221
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004222isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004223
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004224__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4225 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004226 // First try to use the SCEVAffinator to generate a piecewise defined
4227 // affine function from @p E in the context of @p BB. If that tasks becomes to
4228 // complex the affinator might return a nullptr. In such a case we invalidate
4229 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004230 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004231 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004232 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004233 // TODO: We could use a heuristic and either use:
4234 // SCEVAffinator::takeNonNegativeAssumption
4235 // or
4236 // SCEVAffinator::interpretAsUnsigned
4237 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004238 if (NonNegative)
4239 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004240 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004241 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004242
4243 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
4244 invalidate(COMPLEXITY, DL);
4245 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004246}
4247
Tobias Grosser808cd692015-07-14 09:33:13 +00004248__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004249 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4250 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004251
Tobias Grosser808cd692015-07-14 09:33:13 +00004252 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004253 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004254
4255 return Domain;
4256}
4257
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004258__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4259 PWACtx PWAC = getPwAff(E, BB);
4260 isl_set_free(PWAC.second);
4261 return PWAC.first;
4262}
4263
Tobias Grossere5a35142015-11-12 14:07:09 +00004264__isl_give isl_union_map *
4265Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4266 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004267
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004268 for (ScopStmt &Stmt : *this) {
4269 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004270 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004271 continue;
4272
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004273 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004274 isl_map *AccessDomain = MA->getAccessRelation();
4275 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004276 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004277 }
4278 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004279 return isl_union_map_coalesce(Accesses);
4280}
4281
4282__isl_give isl_union_map *Scop::getMustWrites() {
4283 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004284}
4285
4286__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004287 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004288}
4289
Tobias Grosser37eb4222014-02-20 21:43:54 +00004290__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004291 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004292}
4293
4294__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004295 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004296}
4297
Tobias Grosser2ac23382015-11-12 14:07:13 +00004298__isl_give isl_union_map *Scop::getAccesses() {
4299 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4300}
4301
Roman Gareevb3224ad2016-09-14 06:26:09 +00004302// Check whether @p Node is an extension node.
4303//
4304// @return true if @p Node is an extension node.
4305isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4306 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4307 return isl_bool_error;
4308 else
4309 return isl_bool_true;
4310}
4311
4312bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4313 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4314 nullptr) == isl_stat_error;
4315}
4316
Tobias Grosser808cd692015-07-14 09:33:13 +00004317__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004318 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004319 if (containsExtensionNode(Tree)) {
4320 isl_schedule_free(Tree);
4321 return nullptr;
4322 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004323 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004324 isl_schedule_free(Tree);
4325 return S;
4326}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004327
Tobias Grosser808cd692015-07-14 09:33:13 +00004328__isl_give isl_schedule *Scop::getScheduleTree() const {
4329 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4330 getDomains());
4331}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004332
Tobias Grosser808cd692015-07-14 09:33:13 +00004333void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4334 auto *S = isl_schedule_from_domain(getDomains());
4335 S = isl_schedule_insert_partial_schedule(
4336 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4337 isl_schedule_free(Schedule);
4338 Schedule = S;
4339}
4340
4341void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4342 isl_schedule_free(Schedule);
4343 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004344}
4345
4346bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4347 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004348 for (ScopStmt &Stmt : *this) {
4349 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004350 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4351 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4352
4353 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4354 isl_union_set_free(StmtDomain);
4355 isl_union_set_free(NewStmtDomain);
4356 continue;
4357 }
4358
4359 Changed = true;
4360
4361 isl_union_set_free(StmtDomain);
4362 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4363
4364 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004365 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004366 isl_union_set_free(NewStmtDomain);
4367 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004368 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004369 }
4370 isl_union_set_free(Domain);
4371 return Changed;
4372}
4373
Tobias Grosser75805372011-04-29 06:27:02 +00004374ScalarEvolution *Scop::getSE() const { return SE; }
4375
Tobias Grosser808cd692015-07-14 09:33:13 +00004376struct MapToDimensionDataTy {
4377 int N;
4378 isl_union_pw_multi_aff *Res;
4379};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004380
Tobias Grosserc80d6972016-09-02 06:33:33 +00004381// Create a function that maps the elements of 'Set' to its N-th dimension and
4382// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004383//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004384// @param Set The input set.
4385// @param User->N The dimension to map to.
4386// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004387//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004388// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004389static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4390 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4391 int Dim;
4392 isl_space *Space;
4393 isl_pw_multi_aff *PMA;
4394
4395 Dim = isl_set_dim(Set, isl_dim_set);
4396 Space = isl_set_get_space(Set);
4397 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4398 Dim - Data->N);
4399 if (Data->N > 1)
4400 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4401 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4402
4403 isl_set_free(Set);
4404
4405 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004406}
4407
Tobias Grosserc80d6972016-09-02 06:33:33 +00004408// Create an isl_multi_union_aff that defines an identity mapping from the
4409// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004410//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004411// # Example:
4412//
4413// Domain: { A[i,j]; B[i,j,k] }
4414// N: 1
4415//
4416// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4417//
4418// @param USet A union set describing the elements for which to generate a
4419// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004420// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004421// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004422static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004423mapToDimension(__isl_take isl_union_set *USet, int N) {
4424 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004425 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004426 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004427
Tobias Grosser808cd692015-07-14 09:33:13 +00004428 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004429
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004430 auto *Space = isl_union_set_get_space(USet);
4431 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004432
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004433 Data = {N, PwAff};
4434
4435 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004436 (void)Res;
4437
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004438 assert(Res == isl_stat_ok);
4439
4440 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004441 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4442}
4443
Michael Kruse55454072017-03-15 22:16:43 +00004444void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004445 assert(BB && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004446 Stmts.emplace_back(*this, *BB, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004447 auto *Stmt = &Stmts.back();
4448 StmtMap[BB] = Stmt;
4449}
4450
Michael Kruse55454072017-03-15 22:16:43 +00004451void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004452 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004453 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004454 auto *Stmt = &Stmts.back();
4455 for (BasicBlock *BB : R->blocks())
Tobias Grosser808cd692015-07-14 09:33:13 +00004456 StmtMap[BB] = Stmt;
Tobias Grosser808cd692015-07-14 09:33:13 +00004457}
4458
Roman Gareevb3224ad2016-09-14 06:26:09 +00004459ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4460 __isl_take isl_map *TargetRel,
4461 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004462#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004463 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4464 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4465 assert(isl_set_is_subset(Domain, TargetDomain) &&
4466 "Target access not defined for complete statement domain");
4467 assert(isl_set_is_subset(Domain, SourceDomain) &&
4468 "Source access not defined for complete statement domain");
4469 isl_set_free(SourceDomain);
4470 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004471#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004472 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4473 CopyStmtsNum++;
4474 return &(Stmts.back());
4475}
4476
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004477void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004478 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004479 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004480 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004481 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4482 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004483}
4484
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004485/// To generate a schedule for the elements in a Region we traverse the Region
4486/// in reverse-post-order and add the contained RegionNodes in traversal order
4487/// to the schedule of the loop that is currently at the top of the LoopStack.
4488/// For loop-free codes, this results in a correct sequential ordering.
4489///
4490/// Example:
4491/// bb1(0)
4492/// / \.
4493/// bb2(1) bb3(2)
4494/// \ / \.
4495/// bb4(3) bb5(4)
4496/// \ /
4497/// bb6(5)
4498///
4499/// Including loops requires additional processing. Whenever a loop header is
4500/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4501/// from an empty schedule, we first process all RegionNodes that are within
4502/// this loop and complete the sequential schedule at this loop-level before
4503/// processing about any other nodes. To implement this
4504/// loop-nodes-first-processing, the reverse post-order traversal is
4505/// insufficient. Hence, we additionally check if the traversal yields
4506/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4507/// These region-nodes are then queue and only traverse after the all nodes
4508/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004509void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004510 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004511
4512 ReversePostOrderTraversal<Region *> RTraversal(R);
4513 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4514 std::deque<RegionNode *> DelayList;
4515 bool LastRNWaiting = false;
4516
4517 // Iterate over the region @p R in reverse post-order but queue
4518 // sub-regions/blocks iff they are not part of the last encountered but not
4519 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4520 // that we queued the last sub-region/block from the reverse post-order
4521 // iterator. If it is set we have to explore the next sub-region/block from
4522 // the iterator (if any) to guarantee progress. If it is not set we first try
4523 // the next queued sub-region/blocks.
4524 while (!WorkList.empty() || !DelayList.empty()) {
4525 RegionNode *RN;
4526
4527 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4528 RN = WorkList.front();
4529 WorkList.pop_front();
4530 LastRNWaiting = false;
4531 } else {
4532 RN = DelayList.front();
4533 DelayList.pop_front();
4534 }
4535
4536 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004537 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004538 L = OuterScopLoop;
4539
Tobias Grosser151ae322016-04-03 19:36:52 +00004540 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004541 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004542 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004543 LastRNWaiting = true;
4544 DelayList.push_back(RN);
4545 continue;
4546 }
4547 LoopStack.push_back({L, nullptr, 0});
4548 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004549 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004550 }
4551
4552 return;
4553}
4554
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004555void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004556
Tobias Grosser8362c262016-01-06 15:30:06 +00004557 if (RN->isSubRegion()) {
4558 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004559 if (!isNonAffineSubRegion(LocalRegion)) {
4560 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004561 return;
4562 }
4563 }
Michael Kruse046dde42015-08-10 13:01:57 +00004564
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004565 auto &LoopData = LoopStack.back();
4566 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004567
Michael Kruse6f7721f2016-02-24 22:08:19 +00004568 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004569 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4570 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004571 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004572 }
4573
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004574 // Check if we just processed the last node in this loop. If we did, finalize
4575 // the loop by:
4576 //
4577 // - adding new schedule dimensions
4578 // - folding the resulting schedule into the parent loop schedule
4579 // - dropping the loop schedule from the LoopStack.
4580 //
4581 // Then continue to check surrounding loops, which might also have been
4582 // completed by this node.
4583 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00004584 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004585 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004586 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004587
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004588 LoopStack.pop_back();
4589 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004590
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004591 if (Schedule) {
4592 auto *Domain = isl_schedule_get_domain(Schedule);
4593 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4594 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4595 NextLoopData.Schedule =
4596 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004597 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004598
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004599 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4600 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004601 }
Tobias Grosser75805372011-04-29 06:27:02 +00004602}
4603
Michael Kruse6f7721f2016-02-24 22:08:19 +00004604ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004605 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004606 if (StmtMapIt == StmtMap.end())
4607 return nullptr;
4608 return StmtMapIt->second;
4609}
4610
Michael Kruse6f7721f2016-02-24 22:08:19 +00004611ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4612 if (RN->isSubRegion())
4613 return getStmtFor(RN->getNodeAs<Region>());
4614 return getStmtFor(RN->getNodeAs<BasicBlock>());
4615}
4616
4617ScopStmt *Scop::getStmtFor(Region *R) const {
4618 ScopStmt *Stmt = getStmtFor(R->getEntry());
4619 assert(!Stmt || Stmt->getRegion() == R);
4620 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004621}
4622
Johannes Doerfert96425c22015-08-30 21:13:53 +00004623int Scop::getRelativeLoopDepth(const Loop *L) const {
4624 Loop *OuterLoop =
4625 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4626 if (!OuterLoop)
4627 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004628 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4629}
4630
Roman Gareevd7754a12016-07-30 09:25:51 +00004631ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4632 for (auto &SAI : arrays()) {
4633 if (SAI->getName() == BaseName)
4634 return SAI;
4635 }
4636 return nullptr;
4637}
4638
Johannes Doerfert99191c72016-05-31 09:41:04 +00004639//===----------------------------------------------------------------------===//
4640void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4641 AU.addRequired<LoopInfoWrapperPass>();
4642 AU.addRequired<RegionInfoPass>();
4643 AU.addRequired<DominatorTreeWrapperPass>();
4644 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4645 AU.addRequiredTransitive<ScopDetection>();
4646 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004647 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004648 AU.setPreservesAll();
4649}
4650
Tobias Grossercd01a362017-02-17 08:12:36 +00004651void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
4652 NumLoopsInScop += Stats.NumLoops;
4653 MaxNumLoopsInScop =
4654 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
4655
Tobias Grossercd01a362017-02-17 08:12:36 +00004656 if (Stats.MaxDepth == 1)
4657 NumScopsDepthOne++;
4658 else if (Stats.MaxDepth == 2)
4659 NumScopsDepthTwo++;
4660 else if (Stats.MaxDepth == 3)
4661 NumScopsDepthThree++;
4662 else if (Stats.MaxDepth == 4)
4663 NumScopsDepthFour++;
4664 else if (Stats.MaxDepth == 5)
4665 NumScopsDepthFive++;
4666 else
4667 NumScopsDepthLarger++;
4668}
4669
Johannes Doerfert99191c72016-05-31 09:41:04 +00004670bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4671 auto &SD = getAnalysis<ScopDetection>();
4672
4673 if (!SD.isMaxRegionInScop(*R))
4674 return false;
4675
4676 Function *F = R->getEntry()->getParent();
4677 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4678 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4679 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4680 auto const &DL = F->getParent()->getDataLayout();
4681 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004682 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004683
Michael Kruse89b1f942017-03-17 13:56:53 +00004684 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004685 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00004686
4687 if (S) {
4688 ScopDetection::LoopStats Stats =
4689 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
4690 updateLoopCountStatistic(Stats);
4691 }
4692
Tobias Grosser75805372011-04-29 06:27:02 +00004693 return false;
4694}
4695
Johannes Doerfert99191c72016-05-31 09:41:04 +00004696void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004697 if (S)
4698 S->print(OS);
4699 else
4700 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004701}
Tobias Grosser75805372011-04-29 06:27:02 +00004702
Johannes Doerfert99191c72016-05-31 09:41:04 +00004703char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004704
Johannes Doerfert99191c72016-05-31 09:41:04 +00004705Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4706
4707INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004708 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004709 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004710INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00004711INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004712INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004713INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004714INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004715INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004716INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004717INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004718 "Polly - Create polyhedral description of Scops", false,
4719 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004720
4721//===----------------------------------------------------------------------===//
4722void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4723 AU.addRequired<LoopInfoWrapperPass>();
4724 AU.addRequired<RegionInfoPass>();
4725 AU.addRequired<DominatorTreeWrapperPass>();
4726 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4727 AU.addRequiredTransitive<ScopDetection>();
4728 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004729 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004730 AU.setPreservesAll();
4731}
4732
4733bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4734 auto &SD = getAnalysis<ScopDetection>();
4735
4736 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4737 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4738 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4739 auto const &DL = F.getParent()->getDataLayout();
4740 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004741 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004742
4743 /// Create polyhedral descripton of scops for all the valid regions of a
4744 /// function.
4745 for (auto &It : SD) {
4746 Region *R = const_cast<Region *>(It);
4747 if (!SD.isMaxRegionInScop(*R))
4748 continue;
4749
Michael Kruse89b1f942017-03-17 13:56:53 +00004750 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004751 std::unique_ptr<Scop> S = SB.getScop();
4752 if (!S)
4753 continue;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004754 bool Inserted =
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004755 RegionToScopMap.insert(std::make_pair(R, std::move(S))).second;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004756 assert(Inserted && "Building Scop for the same region twice!");
4757 (void)Inserted;
4758 }
4759 return false;
4760}
4761
4762void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4763 for (auto &It : RegionToScopMap) {
4764 if (It.second)
4765 It.second->print(OS);
4766 else
4767 OS << "Invalid Scop!\n";
4768 }
4769}
4770
4771char ScopInfoWrapperPass::ID = 0;
4772
4773Pass *polly::createScopInfoWrapperPassPass() {
4774 return new ScopInfoWrapperPass();
4775}
4776
4777INITIALIZE_PASS_BEGIN(
4778 ScopInfoWrapperPass, "polly-function-scops",
4779 "Polly - Create polyhedral description of all Scops of a function", false,
4780 false);
4781INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00004782INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004783INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4784INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4785INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4786INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4787INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4788INITIALIZE_PASS_END(
4789 ScopInfoWrapperPass, "polly-function-scops",
4790 "Polly - Create polyhedral description of all Scops of a function", false,
4791 false)