blob: 12bd1eada37c2992ae643731fcaf4d98c14f3317 [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"
Michael Kruse7037fde2016-12-15 09:25:14 +000032#include "llvm/ADT/SmallSet.h"
Tobias Grosser83628182013-05-07 08:11:54 +000033#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000034#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000035#include "llvm/Analysis/AliasAnalysis.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 Grosser75dc40c2015-12-20 13:31:48 +000077// The maximal number of basic sets we allow during domain construction to
78// be created. More complex scops will result in very high compile time and
79// are also unlikely to result in good code
Tobias Grosser90411a92017-02-16 19:11:33 +000080static int const MaxDisjunctsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +000081
Tobias Grosserc8a82762017-02-16 19:11:25 +000082// The number of disjunct in the context after which we stop to add more
83// disjuncts. This parameter is there to avoid exponential growth in the
84// number of disjunct when adding non-convex sets to the context.
85static int const MaxDisjunctsInContext = 4;
86
Johannes Doerfert2f705842016-04-12 16:09:44 +000087static cl::opt<bool> PollyRemarksMinimal(
88 "polly-remarks-minimal",
89 cl::desc("Do not emit remarks about assumptions that are known"),
90 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
91
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000092// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000093// operations can overflow easily. Additive reductions and bit operations
94// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000095static cl::opt<bool> DisableMultiplicativeReductions(
96 "polly-disable-multiplicative-reductions",
97 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
98 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000099
Johannes Doerfert9143d672014-09-27 11:02:39 +0000100static cl::opt<unsigned> RunTimeChecksMaxParameters(
101 "polly-rtc-max-parameters",
102 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
103 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
104
Tobias Grosser71500722015-03-28 15:11:14 +0000105static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
106 "polly-rtc-max-arrays-per-group",
107 cl::desc("The maximal number of arrays to compare in each alias group."),
108 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000109
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000110static cl::opt<std::string> UserContextStr(
111 "polly-context", cl::value_desc("isl parameter set"),
112 cl::desc("Provide additional constraints on the context parameters"),
113 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000114
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000115static cl::opt<bool> DetectReductions("polly-detect-reductions",
116 cl::desc("Detect and exploit reductions"),
117 cl::Hidden, cl::ZeroOrMore,
118 cl::init(true), cl::cat(PollyCategory));
119
Tobias Grosser2937b592016-04-29 11:43:20 +0000120static cl::opt<bool>
121 IslOnErrorAbort("polly-on-isl-error-abort",
122 cl::desc("Abort if an isl error is encountered"),
123 cl::init(true), cl::cat(PollyCategory));
124
Michael Kruse6ab44762016-10-04 17:33:39 +0000125static cl::opt<bool> UnprofitableScalarAccs(
126 "polly-unprofitable-scalar-accs",
127 cl::desc("Count statements with scalar accesses as not optimizable"),
128 cl::Hidden, cl::init(true), cl::cat(PollyCategory));
129
Michael Kruse7bf39442015-09-10 12:46:52 +0000130//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000131
Michael Kruse046dde42015-08-10 13:01:57 +0000132// Create a sequence of two schedules. Either argument may be null and is
133// interpreted as the empty schedule. Can also return null if both schedules are
134// empty.
135static __isl_give isl_schedule *
136combineInSequence(__isl_take isl_schedule *Prev,
137 __isl_take isl_schedule *Succ) {
138 if (!Prev)
139 return Succ;
140 if (!Succ)
141 return Prev;
142
143 return isl_schedule_sequence(Prev, Succ);
144}
145
Johannes Doerferte7044942015-02-24 11:58:30 +0000146static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
147 const ConstantRange &Range,
148 int dim,
149 enum isl_dim_type type) {
150 isl_val *V;
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000151 isl_ctx *Ctx = isl_set_get_ctx(S);
Johannes Doerferte7044942015-02-24 11:58:30 +0000152
Tobias Grosser3281f602017-02-16 18:39:14 +0000153 // The upper and lower bound for a parameter value is derived either from
154 // the data type of the parameter or from the - possibly more restrictive -
155 // range metadata.
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000156 V = isl_valFromAPInt(Ctx, Range.getSignedMin(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000157 S = isl_set_lower_bound_val(S, type, dim, V);
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000158 V = isl_valFromAPInt(Ctx, Range.getSignedMax(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000159 S = isl_set_upper_bound_val(S, type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000160
Tobias Grosser3281f602017-02-16 18:39:14 +0000161 if (Range.isFullSet())
162 return S;
163
Tobias Grosserc8a82762017-02-16 19:11:25 +0000164 if (isl_set_n_basic_set(S) > MaxDisjunctsInContext)
165 return S;
166
Tobias Grosser3281f602017-02-16 18:39:14 +0000167 // In case of signed wrapping, we can refine the set of valid values by
168 // excluding the part not covered by the wrapping range.
169 if (Range.isSignWrappedSet()) {
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000170 V = isl_valFromAPInt(Ctx, Range.getLower(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000171 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
172
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000173 V = isl_valFromAPInt(Ctx, Range.getUpper(), true);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000174 V = isl_val_sub_ui(V, 1);
Tobias Grosser3281f602017-02-16 18:39:14 +0000175 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
176 S = isl_set_union(SLB, SUB);
177 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000178
Tobias Grosser3281f602017-02-16 18:39:14 +0000179 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000180}
181
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000182static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
183 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
184 if (!BasePtrLI)
185 return nullptr;
186
Johannes Doerfert952b5302016-05-23 12:40:48 +0000187 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000188 return nullptr;
189
190 ScalarEvolution &SE = *S->getSE();
191
192 auto *OriginBaseSCEV =
193 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
194 if (!OriginBaseSCEV)
195 return nullptr;
196
197 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
198 if (!OriginBaseSCEVUnknown)
199 return nullptr;
200
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000201 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000202 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000203}
204
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000205ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000206 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000207 const DataLayout &DL, Scop *S,
208 const char *BaseName)
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000209 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000210 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000211 BaseName ? BaseName
212 : getIslCompatibleName("MemRef_", BasePtr,
213 Kind == MemoryKind::PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000214 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000215
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000216 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000217
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000218 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000219 BasePtrOriginSAI = nullptr;
220 return;
221 }
222
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000223 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
224 if (BasePtrOriginSAI)
225 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000226}
227
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000228__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000229 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000230 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
231 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
232 return Space;
233}
234
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000235bool ScopArrayInfo::isReadOnly() {
236 isl_union_set *WriteSet = isl_union_map_range(S.getWrites());
237 isl_space *Space = getSpace();
238 WriteSet = isl_union_set_intersect(
239 WriteSet, isl_union_set_from_set(isl_set_universe(Space)));
240
241 bool IsReadOnly = isl_union_set_is_empty(WriteSet);
242 isl_union_set_free(WriteSet);
243
244 return IsReadOnly;
245}
246
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000247void ScopArrayInfo::updateElementType(Type *NewElementType) {
248 if (NewElementType == ElementType)
249 return;
250
Tobias Grosserd840fc72016-02-04 13:18:42 +0000251 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
252 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
253
Johannes Doerferta7920982016-02-25 14:08:48 +0000254 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000255 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000256
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000257 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
258 ElementType = NewElementType;
259 } else {
260 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
261 ElementType = IntegerType::get(ElementType->getContext(), GCD);
262 }
263}
264
Tobias Grosserbedef002016-12-02 08:10:56 +0000265bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
266 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000267 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
268 int ExtraDimsNew = NewSizes.size() - SharedDims;
269 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000270
Tobias Grosserbedef002016-12-02 08:10:56 +0000271 if (CheckConsistency) {
272 for (int i = 0; i < SharedDims; i++) {
273 auto *NewSize = NewSizes[i + ExtraDimsNew];
274 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
275 if (NewSize && KnownSize && NewSize != KnownSize)
276 return false;
277 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000278
Tobias Grosserbedef002016-12-02 08:10:56 +0000279 if (DimensionSizes.size() >= NewSizes.size())
280 return true;
281 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000282
283 DimensionSizes.clear();
284 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
285 NewSizes.end());
286 for (isl_pw_aff *Size : DimensionSizesPw)
287 isl_pw_aff_free(Size);
288 DimensionSizesPw.clear();
289 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000290 if (!Expr) {
291 DimensionSizesPw.push_back(nullptr);
292 continue;
293 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000294 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000295 DimensionSizesPw.push_back(Size);
296 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000297 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000298}
299
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000300ScopArrayInfo::~ScopArrayInfo() {
301 isl_id_free(Id);
302 for (isl_pw_aff *Size : DimensionSizesPw)
303 isl_pw_aff_free(Size);
304}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000305
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000306std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
307
308int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000309 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000310}
311
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000312__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
313 return isl_id_copy(Id);
314}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000315
316void ScopArrayInfo::dump() const { print(errs()); }
317
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000318void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000319 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000320 unsigned u = 0;
321 if (getNumberOfDimensions() > 0 && !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000322 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000323 u++;
324 }
325 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000326 OS << "[";
327
Tobias Grosser26253842015-11-10 14:24:21 +0000328 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000329 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000330 OS << " " << Size << " ";
331 isl_pw_aff_free(Size);
332 } else {
333 OS << *getDimensionSize(u);
334 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000335
336 OS << "]";
337 }
338
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000339 OS << ";";
340
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000341 if (BasePtrOriginSAI)
342 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
343
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000344 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000345}
346
347const ScopArrayInfo *
348ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
349 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
350 assert(Id && "Output dimension didn't have an ID");
351 return getFromId(Id);
352}
353
Michael Krused56b90a2016-09-01 09:03:27 +0000354const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000355 void *User = isl_id_get_user(Id);
356 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
357 isl_id_free(Id);
358 return SAI;
359}
360
Michael Kruse3b425ff2016-04-11 14:34:08 +0000361void MemoryAccess::wrapConstantDimensions() {
362 auto *SAI = getScopArrayInfo();
363 auto *ArraySpace = SAI->getSpace();
364 auto *Ctx = isl_space_get_ctx(ArraySpace);
365 unsigned DimsArray = SAI->getNumberOfDimensions();
366
367 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
368 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
369 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
370
371 // Begin with last dimension, to iteratively carry into higher dimensions.
372 for (int i = DimsArray - 1; i > 0; i--) {
373 auto *DimSize = SAI->getDimensionSize(i);
374 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
375
376 // This transformation is not applicable to dimensions with dynamic size.
377 if (!DimSizeCst)
378 continue;
379
380 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
381 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
382 isl_dim_set, i);
383 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
384 isl_dim_set, i - 1);
385
386 // Compute: index % size
387 // Modulo must apply in the divide of the previous iteration, if any.
388 auto *Modulo = isl_aff_copy(Var);
389 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
390 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
391
392 // Compute: floor(index / size)
393 auto *Divide = Var;
394 Divide = isl_aff_div(
395 Divide,
396 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
397 Divide = isl_aff_floor(Divide);
398 Divide = isl_aff_add(Divide, PrevVar);
399 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
400
401 // Apply Modulo and Divide.
402 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
403 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
404 }
405
406 // Apply all modulo/divides on the accesses.
407 AccessRelation =
408 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
409 AccessRelation = isl_map_detect_equalities(AccessRelation);
410 isl_local_space_free(LArraySpace);
411}
412
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000413void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000414 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000415 auto *ArraySpace = SAI->getSpace();
416 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000417 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000418
419 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
420 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
421 auto DimsMissing = DimsArray - DimsAccess;
422
Michael Kruse375cb5f2016-02-24 22:08:24 +0000423 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000424 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000425 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000426 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000427
Johannes Doerferta90943d2016-02-21 16:37:25 +0000428 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000429 isl_set_universe(AccessSpace),
430 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000431
432 for (unsigned i = 0; i < DimsMissing; i++)
433 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
434
435 for (unsigned i = DimsMissing; i < DimsArray; i++)
436 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
437
438 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000439
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000440 // For the non delinearized arrays, divide the access function of the last
441 // subscript by the size of the elements in the array.
442 //
443 // A stride one array access in C expressed as A[i] is expressed in
444 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
445 // two subsequent values of 'i' index two values that are stored next to
446 // each other in memory. By this division we make this characteristic
447 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000448 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000449 // that divides the offsets of all accesses to this base pointer.
450 if (DimsAccess == 1) {
451 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
452 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
453 }
454
Michael Kruse3b425ff2016-04-11 14:34:08 +0000455 // We currently do this only if we added at least one dimension, which means
456 // some dimension's indices have not been specified, an indicator that some
457 // index values have been added together.
458 // TODO: Investigate general usefulness; Effect on unit tests is to make index
459 // expressions more complicated.
460 if (DimsMissing)
461 wrapConstantDimensions();
462
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000463 if (!isAffine())
464 computeBoundsOnAccessRelation(ArrayElemSize);
465
Tobias Grosserd840fc72016-02-04 13:18:42 +0000466 // Introduce multi-element accesses in case the type loaded by this memory
467 // access is larger than the canonical element type of the array.
468 //
469 // An access ((float *)A)[i] to an array char *A is modeled as
470 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000471 if (ElemBytes > ArrayElemSize) {
472 assert(ElemBytes % ArrayElemSize == 0 &&
473 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000474 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000475 isl_set_universe(isl_space_copy(ArraySpace)),
476 isl_set_universe(isl_space_copy(ArraySpace)));
477 for (unsigned i = 0; i < DimsArray - 1; i++)
478 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
479
Tobias Grosserd840fc72016-02-04 13:18:42 +0000480 isl_constraint *C;
481 isl_local_space *LS;
482
483 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000484 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
485
486 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
487 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000488 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000489 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
490 Map = isl_map_add_constraint(Map, C);
491
492 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000493 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000494 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
495 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
496 Map = isl_map_add_constraint(Map, C);
497 AccessRelation = isl_map_apply_range(AccessRelation, Map);
498 }
499
500 isl_space_free(ArraySpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000501}
502
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000503const std::string
504MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
505 switch (RT) {
506 case MemoryAccess::RT_NONE:
507 llvm_unreachable("Requested a reduction operator string for a memory "
508 "access which isn't a reduction");
509 case MemoryAccess::RT_ADD:
510 return "+";
511 case MemoryAccess::RT_MUL:
512 return "*";
513 case MemoryAccess::RT_BOR:
514 return "|";
515 case MemoryAccess::RT_BXOR:
516 return "^";
517 case MemoryAccess::RT_BAND:
518 return "&";
519 }
520 llvm_unreachable("Unknown reduction type");
521 return "";
522}
523
Tobias Grosserc80d6972016-09-02 06:33:33 +0000524/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000525static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
526 const Instruction *Load) {
527 if (!BinOp)
528 return MemoryAccess::RT_NONE;
529 switch (BinOp->getOpcode()) {
530 case Instruction::FAdd:
531 if (!BinOp->hasUnsafeAlgebra())
532 return MemoryAccess::RT_NONE;
533 // Fall through
534 case Instruction::Add:
535 return MemoryAccess::RT_ADD;
536 case Instruction::Or:
537 return MemoryAccess::RT_BOR;
538 case Instruction::Xor:
539 return MemoryAccess::RT_BXOR;
540 case Instruction::And:
541 return MemoryAccess::RT_BAND;
542 case Instruction::FMul:
543 if (!BinOp->hasUnsafeAlgebra())
544 return MemoryAccess::RT_NONE;
545 // Fall through
546 case Instruction::Mul:
547 if (DisableMultiplicativeReductions)
548 return MemoryAccess::RT_NONE;
549 return MemoryAccess::RT_MUL;
550 default:
551 return MemoryAccess::RT_NONE;
552 }
553}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000554
Tobias Grosser75805372011-04-29 06:27:02 +0000555MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000556 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000557 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000558 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000559 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000560}
561
Michael Kruse2fa35192016-09-01 19:53:31 +0000562const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000563 isl_id *ArrayId = getArrayId();
564 void *User = isl_id_get_user(ArrayId);
565 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
566 isl_id_free(ArrayId);
567 return SAI;
568}
569
Michael Kruse2fa35192016-09-01 19:53:31 +0000570const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
571 isl_id *ArrayId = getLatestArrayId();
572 void *User = isl_id_get_user(ArrayId);
573 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
574 isl_id_free(ArrayId);
575 return SAI;
576}
577
578__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000579 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
580}
581
Michael Kruse2fa35192016-09-01 19:53:31 +0000582__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
583 if (!hasNewAccessRelation())
584 return getOriginalArrayId();
585 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
586}
587
Tobias Grosserd840fc72016-02-04 13:18:42 +0000588__isl_give isl_map *MemoryAccess::getAddressFunction() const {
589 return isl_map_lexmin(getAccessRelation());
590}
591
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000592__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
593 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000594 isl_map *Schedule, *ScheduledAccRel;
595 isl_union_set *UDomain;
596
597 UDomain = isl_union_set_from_set(getStatement()->getDomain());
598 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
599 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000600 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000601 return isl_pw_multi_aff_from_map(ScheduledAccRel);
602}
603
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000604__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000605 return isl_map_copy(AccessRelation);
606}
607
Johannes Doerferta99130f2014-10-13 12:58:03 +0000608std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000609 return stringFromIslObj(AccessRelation);
610}
611
Johannes Doerferta99130f2014-10-13 12:58:03 +0000612__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000613 return isl_map_get_space(AccessRelation);
614}
615
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000616__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000617 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000618}
619
Tobias Grosser6f730082015-09-05 07:46:47 +0000620std::string MemoryAccess::getNewAccessRelationStr() const {
621 return stringFromIslObj(NewAccessRelation);
622}
623
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000624__isl_give isl_basic_map *
625MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000626 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000627 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000628
Tobias Grosser084d8f72012-05-29 09:29:44 +0000629 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000630 isl_basic_set_universe(Statement->getDomainSpace()),
631 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000632}
633
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000634// Formalize no out-of-bound access assumption
635//
636// When delinearizing array accesses we optimistically assume that the
637// delinearized accesses do not access out of bound locations (the subscript
638// expression of each array evaluates for each statement instance that is
639// executed to a value that is larger than zero and strictly smaller than the
640// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000641// dimension for which we do not need to assume any upper bound. At this point
642// we formalize this assumption to ensure that at code generation time the
643// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000644//
645// To find the set of constraints necessary to avoid out of bound accesses, we
646// first build the set of data locations that are not within array bounds. We
647// then apply the reverse access relation to obtain the set of iterations that
648// may contain invalid accesses and reduce this set of iterations to the ones
649// that are actually executed by intersecting them with the domain of the
650// statement. If we now project out all loop dimensions, we obtain a set of
651// parameters that may cause statement instances to be executed that may
652// possibly yield out of bound memory accesses. The complement of these
653// constraints is the set of constraints that needs to be assumed to ensure such
654// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000655void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000656 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000657 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000658 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000659 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000660 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
661 isl_pw_aff *Var =
662 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
663 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
664
665 isl_set *DimOutside;
666
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000667 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000668 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000669 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
670 isl_space_dim(Space, isl_dim_set));
671 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
672 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000673
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000674 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000675
676 Outside = isl_set_union(Outside, DimOutside);
677 }
678
679 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
680 Outside = isl_set_intersect(Outside, Statement->getDomain());
681 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000682
683 // Remove divs to avoid the construction of overly complicated assumptions.
684 // Doing so increases the set of parameter combinations that are assumed to
685 // not appear. This is always save, but may make the resulting run-time check
686 // bail out more often than strictly necessary.
687 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000688 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000689 const auto &Loc = getAccessInstruction()
690 ? getAccessInstruction()->getDebugLoc()
691 : DebugLoc();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000692 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
693 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000694 isl_space_free(Space);
695}
696
Johannes Doerfertcea61932016-02-21 19:13:19 +0000697void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000698 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000699 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000700
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000701 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000702 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000703
704 isl_map *LengthMap;
705 if (Subscripts[1] == nullptr) {
706 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
707 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000708 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000709 LengthMap = isl_map_from_pw_aff(LengthPWA);
710 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
711 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
712 }
713 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
714 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000715 SubscriptMap =
716 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000717 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
718 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
719 getStatement()->getDomainId());
720}
721
Johannes Doerferte7044942015-02-24 11:58:30 +0000722void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
723 ScalarEvolution *SE = Statement->getParent()->getSE();
724
Johannes Doerfertcea61932016-02-21 19:13:19 +0000725 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000726 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000727 return;
728
729 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000730 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
731 return;
732
733 auto *PtrSCEV = SE->getSCEV(Ptr);
734 if (isa<SCEVCouldNotCompute>(PtrSCEV))
735 return;
736
737 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
738 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
739 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
740
741 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
742 if (Range.isFullSet())
743 return;
744
Tobias Grosserb3a85882017-02-12 08:11:12 +0000745 if (Range.isWrappedSet())
746 return;
747
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000748 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000749
Johannes Doerferte7044942015-02-24 11:58:30 +0000750 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000751 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000752 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000753 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000754
755 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000756 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000757
Tobias Grosserb3a85882017-02-12 08:11:12 +0000758 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
759
Johannes Doerferte7044942015-02-24 11:58:30 +0000760 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
761 AccessRange =
762 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
763 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
764}
765
Tobias Grosser491b7992016-12-02 05:21:22 +0000766void MemoryAccess::foldAccessRelation() {
767 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
768 return;
769
Michael Krusee2bccbb2015-09-18 19:59:43 +0000770 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000771
772 for (int i = Size - 2; i >= 0; --i) {
773 isl_space *Space;
774 isl_map *MapOne, *MapTwo;
Roman Gareevf5aff702016-09-12 17:08:31 +0000775 isl_pw_aff *DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000776
777 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
778 isl_pw_aff_free(DimSize);
779 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
780
781 Space = isl_map_get_space(AccessRelation);
782 Space = isl_space_map_from_set(isl_space_range(Space));
783 Space = isl_space_align_params(Space, SpaceSize);
784
785 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
786 isl_id_free(ParamId);
787
788 MapOne = isl_map_universe(isl_space_copy(Space));
789 for (int j = 0; j < Size; ++j)
790 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
791 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
792
793 MapTwo = isl_map_universe(isl_space_copy(Space));
794 for (int j = 0; j < Size; ++j)
795 if (j < i || j > i + 1)
796 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
797
798 isl_local_space *LS = isl_local_space_from_space(Space);
799 isl_constraint *C;
800 C = isl_equality_alloc(isl_local_space_copy(LS));
801 C = isl_constraint_set_constant_si(C, -1);
802 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
803 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
804 MapTwo = isl_map_add_constraint(MapTwo, C);
805 C = isl_equality_alloc(LS);
806 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
807 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
808 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
809 MapTwo = isl_map_add_constraint(MapTwo, C);
810 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
811
812 MapOne = isl_map_union(MapOne, MapTwo);
813 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
814 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000815
816 isl_id *BaseAddrId = getScopArrayInfo()->getBasePtrId();
817 auto Space = Statement->getDomainSpace();
818 AccessRelation = isl_map_set_tuple_id(
819 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
820 AccessRelation =
821 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
822 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
823 isl_space_free(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000824}
825
Tobias Grosserc80d6972016-09-02 06:33:33 +0000826/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000827static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000828 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000829 if (Size == 1)
830 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000831
832 // Only one factor needs to be divisible.
833 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
834 for (auto *FactorExpr : MulExpr->operands())
835 if (isDivisible(FactorExpr, Size, SE))
836 return true;
837 return false;
838 }
839
840 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
841 // to be divisble.
842 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
843 for (auto *OpExpr : NAryExpr->operands())
844 if (!isDivisible(OpExpr, Size, SE))
845 return false;
846 return true;
847 }
848
849 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
850 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
851 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
852 return MulSCEV == Expr;
853}
854
Michael Krusee2bccbb2015-09-18 19:59:43 +0000855void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
856 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000857
Johannes Doerfert85676e32016-04-23 14:32:34 +0000858 // Initialize the invalid domain which describes all iterations for which the
859 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000860 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
861 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
862 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000863
Michael Krusee2bccbb2015-09-18 19:59:43 +0000864 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000865 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000866
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000867 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
868 buildMemIntrinsicAccessRelation();
869 AccessRelation =
870 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
871 return;
872 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000873
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000874 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000875 // We overapproximate non-affine accesses with a possible access to the
876 // whole array. For read accesses it does not make a difference, if an
877 // access must or may happen. However, for write accesses it is important to
878 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000879 if (!AccessRelation)
880 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
881
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000882 AccessRelation =
883 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000884 return;
885 }
886
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000887 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000888 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000889
Michael Krusee2bccbb2015-09-18 19:59:43 +0000890 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000891 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000892 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000893 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000894 }
895
Tobias Grosser79baa212014-04-10 08:38:02 +0000896 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000897 AccessRelation = isl_map_set_tuple_id(
898 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000899 AccessRelation =
900 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
901
Tobias Grosseraa660a92015-03-30 00:07:50 +0000902 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000903 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000904}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000905
Michael Krusecac948e2015-10-02 13:53:07 +0000906MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000907 AccessType AccType, Value *BaseAddress,
908 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000909 ArrayRef<const SCEV *> Subscripts,
910 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000911 MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000912 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Johannes Doerfert85676e32016-04-23 14:32:34 +0000913 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
914 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()),
915 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000916 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000917 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000918 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000919 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000920
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000921 std::string IdName =
922 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000923 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
924}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000925
Roman Gareevb3224ad2016-09-14 06:26:09 +0000926MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
927 __isl_take isl_map *AccRel)
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000928 : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
929 Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
930 IsAffine(true), AccessRelation(nullptr), NewAccessRelation(AccRel) {
Roman Gareevb3224ad2016-09-14 06:26:09 +0000931 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
932 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
933 Sizes.push_back(nullptr);
934 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
935 Sizes.push_back(SAI->getDimensionSize(i));
936 ElementType = SAI->getElementType();
937 BaseAddr = SAI->getBasePtr();
938 BaseName = SAI->getName();
939 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
940 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
941
942 std::string IdName =
943 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
944 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
945}
946
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000947void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +0000948 auto *Ctx = Statement->getParent()->getContext();
949 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
950 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +0000951}
952
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000953const std::string MemoryAccess::getReductionOperatorStr() const {
954 return MemoryAccess::getReductionOperatorStr(getReductionType());
955}
956
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000957__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
958
Johannes Doerfertf6183392014-07-01 20:52:51 +0000959raw_ostream &polly::operator<<(raw_ostream &OS,
960 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000961 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000962 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000963 else
964 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000965 return OS;
966}
967
Tobias Grosser75805372011-04-29 06:27:02 +0000968void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000969 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000970 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000971 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000972 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000973 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000974 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000975 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000976 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000977 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000978 break;
979 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000980 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000981 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000982 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000983 if (hasNewAccessRelation())
984 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000985}
986
Tobias Grosser74394f02013-01-14 22:40:23 +0000987void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000988
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000989__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
990 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000991 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +0000992 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
993 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
994 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000995 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000996}
997
Tobias Grosser75805372011-04-29 06:27:02 +0000998// Create a map in the size of the provided set domain, that maps from the
999// one element of the provided set domain to another element of the provided
1000// set domain.
1001// The mapping is limited to all points that are equal in all but the last
1002// dimension and for which the last dimension of the input is strict smaller
1003// than the last dimension of the output.
1004//
1005// getEqualAndLarger(set[i0, i1, ..., iX]):
1006//
1007// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1008// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1009//
Tobias Grosser2a526fe2016-09-08 11:18:56 +00001010static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +00001011 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001012 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +00001013 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001014
1015 // Set all but the last dimension to be equal for the input and output
1016 //
1017 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1018 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001019 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +00001020 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001021
1022 // Set the last dimension of the input to be strict smaller than the
1023 // last dimension of the output.
1024 //
1025 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001026 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1027 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001028 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001029}
1030
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001031__isl_give isl_set *
1032MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001033 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +00001034 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +00001035 isl_space *Space = isl_space_range(isl_map_get_space(S));
1036 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001037
Sebastian Popa00a0292012-12-18 07:46:06 +00001038 S = isl_map_reverse(S);
1039 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001040
Sebastian Popa00a0292012-12-18 07:46:06 +00001041 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1042 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1043 NextScatt = isl_map_apply_domain(NextScatt, S);
1044 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001045
Sebastian Popa00a0292012-12-18 07:46:06 +00001046 isl_set *Deltas = isl_map_deltas(NextScatt);
1047 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001048}
1049
Sebastian Popa00a0292012-12-18 07:46:06 +00001050bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001051 int StrideWidth) const {
1052 isl_set *Stride, *StrideX;
1053 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001054
Sebastian Popa00a0292012-12-18 07:46:06 +00001055 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001056 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001057 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1058 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1059 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1060 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001061 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001062
Tobias Grosser28dd4862012-01-24 16:42:16 +00001063 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001064 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001065
Tobias Grosser28dd4862012-01-24 16:42:16 +00001066 return IsStrideX;
1067}
1068
Michael Krused56b90a2016-09-01 09:03:27 +00001069bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001070 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001071}
1072
Michael Krused56b90a2016-09-01 09:03:27 +00001073bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001074 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001075}
1076
Tobias Grosserbedef002016-12-02 08:10:56 +00001077void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
1078 isl_map_free(AccessRelation);
1079 AccessRelation = NewAccess;
1080}
1081
Michael Krused56b90a2016-09-01 09:03:27 +00001082void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001083 assert(NewAccess);
1084
1085#ifndef NDEBUG
1086 // Check domain space compatibility.
1087 auto *NewSpace = isl_map_get_space(NewAccess);
1088 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1089 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1090 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1091 isl_space_free(NewDomainSpace);
1092 isl_space_free(OriginalDomainSpace);
1093
1094 // Check whether there is an access for every statement instance.
1095 auto *StmtDomain = getStatement()->getDomain();
1096 StmtDomain = isl_set_intersect_params(
1097 StmtDomain, getStatement()->getParent()->getContext());
1098 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1099 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1100 "Partial accesses not supported");
1101 isl_set_free(NewDomain);
1102 isl_set_free(StmtDomain);
1103
Michael Kruse772ce722016-09-01 19:16:58 +00001104 auto *NewAccessSpace = isl_space_range(NewSpace);
1105 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1106 "Must specify the array that is accessed");
1107 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1108 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1109 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001110
1111 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1112 InvariantEquivClassTy *EqClass =
1113 getStatement()->getParent()->lookupInvariantEquivClass(
1114 SAI->getBasePtr());
1115 assert(EqClass &&
1116 "Access functions to indirect arrays must have an invariant and "
1117 "hoisted base pointer");
1118 }
1119
1120 // Check whether access dimensions correspond to number of dimensions of the
1121 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001122 auto Dims = SAI->getNumberOfDimensions();
1123 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1124 "Access dims must match array dims");
1125 isl_space_free(NewAccessSpace);
1126 isl_id_free(NewArrayId);
1127#endif
1128
Tobias Grosser166c4222015-09-05 07:46:40 +00001129 isl_map_free(NewAccessRelation);
1130 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001131}
Tobias Grosser75805372011-04-29 06:27:02 +00001132
1133//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001134
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001135__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001136 isl_set *Domain = getDomain();
1137 if (isl_set_is_empty(Domain)) {
1138 isl_set_free(Domain);
1139 return isl_map_from_aff(
1140 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1141 }
1142 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001143 if (!Schedule) {
1144 isl_set_free(Domain);
1145 return nullptr;
1146 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001147 Schedule = isl_union_map_intersect_domain(
1148 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1149 if (isl_union_map_is_empty(Schedule)) {
1150 isl_set_free(Domain);
1151 isl_union_map_free(Schedule);
1152 return isl_map_from_aff(
1153 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1154 }
1155 auto *M = isl_map_from_union_map(Schedule);
1156 M = isl_map_coalesce(M);
1157 M = isl_map_gist_domain(M, Domain);
1158 M = isl_map_coalesce(M);
1159 return M;
1160}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001161
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001162__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1163 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001164 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1165 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001166}
1167
Tobias Grosser37eb4222014-02-20 21:43:54 +00001168void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1169 assert(isl_set_is_subset(NewDomain, Domain) &&
1170 "New domain is not a subset of old domain!");
1171 isl_set_free(Domain);
1172 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001173}
1174
Michael Krusecac948e2015-10-02 13:53:07 +00001175void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001176 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001177 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001178 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001179
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001180 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001181 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001182 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001183 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001184 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001185 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001186 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001187 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001188 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001189
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001190 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1191 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001192 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001193 }
1194}
1195
Michael Krusecac948e2015-10-02 13:53:07 +00001196void ScopStmt::addAccess(MemoryAccess *Access) {
1197 Instruction *AccessInst = Access->getAccessInstruction();
1198
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001199 if (Access->isArrayKind()) {
1200 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1201 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001202 } else if (Access->isValueKind() && Access->isWrite()) {
1203 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001204 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001205 assert(!ValueWrites.lookup(AccessVal));
1206
1207 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001208 } else if (Access->isValueKind() && Access->isRead()) {
1209 Value *AccessVal = Access->getAccessValue();
1210 assert(!ValueReads.lookup(AccessVal));
1211
1212 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001213 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001214 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001215 assert(!PHIWrites.lookup(PHI));
1216
1217 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001218 }
1219
1220 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001221}
1222
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001223void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001224 for (MemoryAccess *MA : *this)
1225 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001226
Johannes Doerferta60ad842016-05-10 12:18:22 +00001227 auto *Ctx = Parent.getContext();
1228 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1229 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001230}
1231
Tobias Grosserc80d6972016-09-02 06:33:33 +00001232/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001233static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1234 void *User) {
1235 isl_set **BoundedParts = static_cast<isl_set **>(User);
1236 if (isl_basic_set_is_bounded(BSet))
1237 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1238 else
1239 isl_basic_set_free(BSet);
1240 return isl_stat_ok;
1241}
1242
Tobias Grosserc80d6972016-09-02 06:33:33 +00001243/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001244static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1245 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1246 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1247 isl_set_free(S);
1248 return BoundedParts;
1249}
1250
Tobias Grosserc80d6972016-09-02 06:33:33 +00001251/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001252///
1253/// @returns A separation of @p S into first an unbounded then a bounded subset,
1254/// both with regards to the dimension @p Dim.
1255static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1256partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1257
1258 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001259 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001260
1261 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001262 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001263
1264 // Remove dimensions that are greater than Dim as they are not interesting.
1265 assert(NumDimsS >= Dim + 1);
1266 OnlyDimS =
1267 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1268
1269 // Create artificial parametric upper bounds for dimensions smaller than Dim
1270 // as we are not interested in them.
1271 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1272 for (unsigned u = 0; u < Dim; u++) {
1273 isl_constraint *C = isl_inequality_alloc(
1274 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1275 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1276 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1277 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1278 }
1279
1280 // Collect all bounded parts of OnlyDimS.
1281 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1282
1283 // Create the dimensions greater than Dim again.
1284 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1285 NumDimsS - Dim - 1);
1286
1287 // Remove the artificial upper bound parameters again.
1288 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1289
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001290 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001291 return std::make_pair(UnboundedParts, BoundedParts);
1292}
1293
Tobias Grosserc80d6972016-09-02 06:33:33 +00001294/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001295static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1296 __isl_take isl_set *To) {
1297 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1298 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1299 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1300 }
1301 return To;
1302}
1303
Tobias Grosserc80d6972016-09-02 06:33:33 +00001304/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001305static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001306 __isl_take isl_pw_aff *L,
1307 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001308 switch (Pred) {
1309 case ICmpInst::ICMP_EQ:
1310 return isl_pw_aff_eq_set(L, R);
1311 case ICmpInst::ICMP_NE:
1312 return isl_pw_aff_ne_set(L, R);
1313 case ICmpInst::ICMP_SLT:
1314 return isl_pw_aff_lt_set(L, R);
1315 case ICmpInst::ICMP_SLE:
1316 return isl_pw_aff_le_set(L, R);
1317 case ICmpInst::ICMP_SGT:
1318 return isl_pw_aff_gt_set(L, R);
1319 case ICmpInst::ICMP_SGE:
1320 return isl_pw_aff_ge_set(L, R);
1321 case ICmpInst::ICMP_ULT:
1322 return isl_pw_aff_lt_set(L, R);
1323 case ICmpInst::ICMP_UGT:
1324 return isl_pw_aff_gt_set(L, R);
1325 case ICmpInst::ICMP_ULE:
1326 return isl_pw_aff_le_set(L, R);
1327 case ICmpInst::ICMP_UGE:
1328 return isl_pw_aff_ge_set(L, R);
1329 default:
1330 llvm_unreachable("Non integer predicate not supported");
1331 }
1332}
1333
Tobias Grosserc80d6972016-09-02 06:33:33 +00001334/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001335///
1336/// Helper function that will make sure the dimensions of the result have the
1337/// same isl_id's as the @p Domain.
1338static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1339 __isl_take isl_pw_aff *L,
1340 __isl_take isl_pw_aff *R,
1341 __isl_keep isl_set *Domain) {
1342 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1343 return setDimensionIds(Domain, ConsequenceCondSet);
1344}
1345
Tobias Grosserc80d6972016-09-02 06:33:33 +00001346/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001347///
1348/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001349/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1350/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001351static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001352buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1353 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001354 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1355
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001356 Value *Condition = getConditionFromTerminator(SI);
1357 assert(Condition && "No condition for switch");
1358
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001359 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001360 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001361 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001362 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001363
1364 unsigned NumSuccessors = SI->getNumSuccessors();
1365 ConditionSets.resize(NumSuccessors);
1366 for (auto &Case : SI->cases()) {
1367 unsigned Idx = Case.getSuccessorIndex();
1368 ConstantInt *CaseValue = Case.getCaseValue();
1369
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001370 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001371 isl_set *CaseConditionSet =
1372 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1373 ConditionSets[Idx] = isl_set_coalesce(
1374 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1375 }
1376
1377 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1378 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1379 for (unsigned u = 2; u < NumSuccessors; u++)
1380 ConditionSetUnion =
1381 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1382 ConditionSets[0] = setDimensionIds(
1383 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1384
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001385 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001386
1387 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001388}
1389
Tobias Grosserc80d6972016-09-02 06:33:33 +00001390/// Build the conditions sets for the branch condition @p Condition in
1391/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001392///
1393/// This will fill @p ConditionSets with the conditions under which control
1394/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001395/// have as many elements as @p TI has successors. If @p TI is nullptr the
1396/// context under which @p Condition is true/false will be returned as the
1397/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001398static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001399buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1400 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001401 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1402
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001403 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001404 isl_set *ConsequenceCondSet = nullptr;
1405 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1406 if (CCond->isZero())
1407 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1408 else
1409 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1410 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1411 auto Opcode = BinOp->getOpcode();
1412 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1413
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001414 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1415 ConditionSets) &&
1416 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1417 ConditionSets);
1418 if (!Valid) {
1419 while (!ConditionSets.empty())
1420 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001421 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001422 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001423
1424 isl_set_free(ConditionSets.pop_back_val());
1425 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1426 isl_set_free(ConditionSets.pop_back_val());
1427 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1428
1429 if (Opcode == Instruction::And)
1430 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1431 else
1432 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1433 } else {
1434 auto *ICond = dyn_cast<ICmpInst>(Condition);
1435 assert(ICond &&
1436 "Condition of exiting branch was neither constant nor ICmp!");
1437
1438 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001439 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001440 // For unsigned comparisons we assumed the signed bit of neither operand
1441 // to be set. The comparison is equal to a signed comparison under this
1442 // assumption.
1443 bool NonNeg = ICond->isUnsigned();
1444 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1445 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001446 ConsequenceCondSet =
1447 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1448 }
1449
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001450 // If no terminator was given we are only looking for parameter constraints
1451 // under which @p Condition is true/false.
1452 if (!TI)
1453 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001454 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001455 ConsequenceCondSet = isl_set_coalesce(
1456 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001457
Johannes Doerfertb2885792016-04-26 09:20:41 +00001458 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001459 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001460 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001461
Michael Krusef7a4a942016-05-02 12:25:36 +00001462 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001463 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1464 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001465 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001466 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001467 }
1468
Michael Krusef7a4a942016-05-02 12:25:36 +00001469 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001470 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001471 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001472 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001473 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001474 }
1475
1476 ConditionSets.push_back(ConsequenceCondSet);
1477 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001478
1479 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001480}
1481
Tobias Grosserc80d6972016-09-02 06:33:33 +00001482/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001483///
1484/// This will fill @p ConditionSets with the conditions under which control
1485/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1486/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001487static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001488buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001489 __isl_keep isl_set *Domain,
1490 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1491
1492 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001493 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001494
1495 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1496
1497 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001498 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001499 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001500 }
1501
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001502 Value *Condition = getConditionFromTerminator(TI);
1503 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001504
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001505 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001506}
1507
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001508void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001509 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001510
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001511 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001512 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001513}
1514
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001515void ScopStmt::collectSurroundingLoops() {
1516 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1517 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1518 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1519 isl_id_free(DimId);
1520 }
1521}
1522
Michael Kruse9d080092015-09-11 21:41:48 +00001523ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerferta3519512016-04-23 13:02:23 +00001524 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1525 R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001526
Tobias Grosser16c44032015-07-09 07:31:45 +00001527 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001528}
1529
Michael Kruse9d080092015-09-11 21:41:48 +00001530ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerferta3519512016-04-23 13:02:23 +00001531 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1532 R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001533
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001534 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001535}
1536
Roman Gareevb3224ad2016-09-14 06:26:09 +00001537ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1538 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1539 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1540 R(nullptr), Build(nullptr) {
1541 BaseName = getIslCompatibleName("CopyStmt_", "",
1542 std::to_string(parent.getCopyStmtsNum()));
1543 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1544 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1545 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1546 auto *Access =
1547 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1548 parent.addAccessFunction(Access);
1549 addAccess(Access);
1550 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1551 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1552 parent.addAccessFunction(Access);
1553 addAccess(Access);
1554}
1555
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001556void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001557 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001558
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001559 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001560 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001561 buildAccessRelations();
1562
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001563 if (DetectReductions)
1564 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001565}
1566
Tobias Grosserc80d6972016-09-02 06:33:33 +00001567/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001568///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001569/// Check if the stored value for @p StoreMA is a binary operator with one or
1570/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001571/// used only once (by @p StoreMA) and its load operands are also used only
1572/// once, we have found a possible reduction chain. It starts at an operand
1573/// load and includes the binary operator and @p StoreMA.
1574///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001575/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001576/// escape this block or into any other store except @p StoreMA.
1577void ScopStmt::collectCandiateReductionLoads(
1578 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1579 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1580 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001581 return;
1582
1583 // Skip if there is not one binary operator between the load and the store
1584 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001585 if (!BinOp)
1586 return;
1587
1588 // Skip if the binary operators has multiple uses
1589 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001590 return;
1591
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001592 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001593 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1594 return;
1595
Johannes Doerfert9890a052014-07-01 00:32:29 +00001596 // Skip if the binary operator is outside the current SCoP
1597 if (BinOp->getParent() != Store->getParent())
1598 return;
1599
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001600 // Skip if it is a multiplicative reduction and we disabled them
1601 if (DisableMultiplicativeReductions &&
1602 (BinOp->getOpcode() == Instruction::Mul ||
1603 BinOp->getOpcode() == Instruction::FMul))
1604 return;
1605
Johannes Doerferte58a0122014-06-27 20:31:28 +00001606 // Check the binary operator operands for a candidate load
1607 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1608 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1609 if (!PossibleLoad0 && !PossibleLoad1)
1610 return;
1611
1612 // A load is only a candidate if it cannot escape (thus has only this use)
1613 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001614 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001615 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001616 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001617 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001618 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001619}
1620
Tobias Grosserc80d6972016-09-02 06:33:33 +00001621/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001622///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001623/// Iterate over all store memory accesses and check for valid binary reduction
1624/// like chains. For all candidates we check if they have the same base address
1625/// and there are no other accesses which overlap with them. The base address
1626/// check rules out impossible reductions candidates early. The overlap check,
1627/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001628/// guarantees that none of the intermediate results will escape during
1629/// execution of the loop nest. We basically check here that no other memory
1630/// access can access the same memory as the potential reduction.
1631void ScopStmt::checkForReductions() {
1632 SmallVector<MemoryAccess *, 2> Loads;
1633 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1634
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001635 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001636 // stores and collecting possible reduction loads.
1637 for (MemoryAccess *StoreMA : MemAccs) {
1638 if (StoreMA->isRead())
1639 continue;
1640
1641 Loads.clear();
1642 collectCandiateReductionLoads(StoreMA, Loads);
1643 for (MemoryAccess *LoadMA : Loads)
1644 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1645 }
1646
1647 // Then check each possible candidate pair.
1648 for (const auto &CandidatePair : Candidates) {
1649 bool Valid = true;
1650 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1651 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1652
1653 // Skip those with obviously unequal base addresses.
1654 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1655 isl_map_free(LoadAccs);
1656 isl_map_free(StoreAccs);
1657 continue;
1658 }
1659
1660 // And check if the remaining for overlap with other memory accesses.
1661 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1662 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1663 isl_set *AllAccs = isl_map_range(AllAccsRel);
1664
1665 for (MemoryAccess *MA : MemAccs) {
1666 if (MA == CandidatePair.first || MA == CandidatePair.second)
1667 continue;
1668
1669 isl_map *AccRel =
1670 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1671 isl_set *Accs = isl_map_range(AccRel);
1672
Tobias Grosser55a7af72016-09-08 14:08:07 +00001673 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001674 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1675 Valid = Valid && isl_set_is_empty(OverlapAccs);
1676 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001677 } else {
1678 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001679 }
1680 }
1681
1682 isl_set_free(AllAccs);
1683 if (!Valid)
1684 continue;
1685
Johannes Doerfertf6183392014-07-01 20:52:51 +00001686 const LoadInst *Load =
1687 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1688 MemoryAccess::ReductionType RT =
1689 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1690
Johannes Doerferte58a0122014-06-27 20:31:28 +00001691 // If no overlapping access was found we mark the load and store as
1692 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001693 CandidatePair.first->markAsReductionLike(RT);
1694 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001695 }
Tobias Grosser75805372011-04-29 06:27:02 +00001696}
1697
Tobias Grosser74394f02013-01-14 22:40:23 +00001698std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001699
Tobias Grosser54839312015-04-21 11:37:25 +00001700std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001701 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001702 if (!S)
1703 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001704 auto Str = stringFromIslObj(S);
1705 isl_map_free(S);
1706 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001707}
1708
Johannes Doerferta3519512016-04-23 13:02:23 +00001709void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1710 isl_set_free(InvalidDomain);
1711 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001712}
1713
Michael Kruse375cb5f2016-02-24 22:08:24 +00001714BasicBlock *ScopStmt::getEntryBlock() const {
1715 if (isBlockStmt())
1716 return getBasicBlock();
1717 return getRegion()->getEntry();
1718}
1719
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001720unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001721
Tobias Grosser75805372011-04-29 06:27:02 +00001722const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1723
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001724Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001725 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001726}
1727
Tobias Grosser74394f02013-01-14 22:40:23 +00001728isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001729
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001730__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001731
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001732__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001733 return isl_set_get_space(Domain);
1734}
1735
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001736__isl_give isl_id *ScopStmt::getDomainId() const {
1737 return isl_set_get_tuple_id(Domain);
1738}
Tobias Grossercd95b772012-08-30 11:49:38 +00001739
Johannes Doerfert7c013572016-04-12 09:57:34 +00001740ScopStmt::~ScopStmt() {
1741 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001742 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001743}
Tobias Grosser75805372011-04-29 06:27:02 +00001744
1745void ScopStmt::print(raw_ostream &OS) const {
1746 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001747 OS.indent(12) << "Domain :=\n";
1748
1749 if (Domain) {
1750 OS.indent(16) << getDomainStr() << ";\n";
1751 } else
1752 OS.indent(16) << "n/a\n";
1753
Tobias Grosser54839312015-04-21 11:37:25 +00001754 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001755
1756 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001757 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001758 } else
1759 OS.indent(16) << "n/a\n";
1760
Tobias Grosser083d3d32014-06-28 08:59:45 +00001761 for (MemoryAccess *Access : MemAccs)
1762 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001763}
1764
1765void ScopStmt::dump() const { print(dbgs()); }
1766
Michael Kruse10071822016-05-23 14:45:58 +00001767void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001768 // Remove the memory accesses from this statement together with all scalar
1769 // accesses that were caused by it. MemoryKind::Value READs have no access
1770 // instruction, hence would not be removed by this function. However, it is
1771 // only used for invariant LoadInst accesses, its arguments are always affine,
1772 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1773 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001774 auto Predicate = [&](MemoryAccess *Acc) {
1775 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1776 };
1777 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1778 MemAccs.end());
1779 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001780}
1781
Tobias Grosser75805372011-04-29 06:27:02 +00001782//===----------------------------------------------------------------------===//
1783/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001784
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001785void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001786 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1787 isl_set_free(Context);
1788 Context = NewContext;
1789}
1790
Tobias Grosserc80d6972016-09-02 06:33:33 +00001791/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001792struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001793 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001794 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001795
1796public:
1797 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001798 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001799
1800 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1801 ValueToValueMap &VMap) {
1802 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1803 return SSPR.visit(E);
1804 }
1805
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001806 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1807 auto *Start = visit(E->getStart());
1808 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1809 visit(E->getStepRecurrence(SE)),
1810 E->getLoop(), SCEV::FlagAnyWrap);
1811 return SE.getAddExpr(Start, AddRec);
1812 }
1813
1814 const SCEV *visitUnknown(const SCEVUnknown *E) {
1815 if (auto *NewValue = VMap.lookup(E->getValue()))
1816 return SE.getUnknown(NewValue);
1817 return E;
1818 }
1819};
1820
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001821const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001822 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001823}
1824
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001825void Scop::createParameterId(const SCEV *Parameter) {
1826 assert(Parameters.count(Parameter));
1827 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001828
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001829 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001830
Tobias Grosser8f99c162011-11-15 11:38:55 +00001831 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1832 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001833
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001834 // If this parameter references a specific Value and this value has a name
1835 // we use this name as it is likely to be unique and more useful than just
1836 // a number.
1837 if (Val->hasName())
1838 ParameterName = Val->getName();
1839 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001840 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001841 if (LoadOrigin->hasName()) {
1842 ParameterName += "_loaded_from_";
1843 ParameterName +=
1844 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1845 }
1846 }
1847 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001848
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001849 ParameterName = getIslCompatibleName("", ParameterName, "");
1850
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001851 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1852 const_cast<void *>((const void *)Parameter));
1853 ParameterIds[Parameter] = Id;
1854}
1855
1856void Scop::addParams(const ParameterSetTy &NewParameters) {
1857 for (const SCEV *Parameter : NewParameters) {
1858 // Normalize the SCEV to get the representing element for an invariant load.
1859 Parameter = extractConstantFactor(Parameter, *SE).second;
1860 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1861
1862 if (Parameters.insert(Parameter))
1863 createParameterId(Parameter);
1864 }
1865}
1866
1867__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1868 // Normalize the SCEV to get the representing element for an invariant load.
1869 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1870 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001871}
Tobias Grosser75805372011-04-29 06:27:02 +00001872
Michael Krused56b90a2016-09-01 09:03:27 +00001873__isl_give isl_set *
1874Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001875 isl_set *DomainContext = isl_union_set_params(getDomains());
1876 return isl_set_intersect_params(C, DomainContext);
1877}
1878
Johannes Doerferte0b08072016-05-23 12:43:44 +00001879bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1880 return DT.dominates(BB, getEntry());
1881}
1882
Michael Kruse7037fde2016-12-15 09:25:14 +00001883void Scop::addUserAssumptions(DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001884 auto &F = getFunction();
Michael Kruse7037fde2016-12-15 09:25:14 +00001885
1886 // TODO: Walk the DominatorTree from getRegion().getExit() to its root in
1887 // order to not iterate over blocks we skip anyways.
1888 for (auto &BB : F) {
1889 bool InScop = contains(&BB);
1890 if (!InScop && !isDominatedBy(DT, &BB))
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001891 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001892
Michael Kruse7037fde2016-12-15 09:25:14 +00001893 for (auto &Assumption : BB) {
1894 auto *CI = dyn_cast_or_null<IntrinsicInst>(&Assumption);
1895 if (!CI || CI->getNumArgOperands() != 1 ||
1896 CI->getIntrinsicID() != Intrinsic::assume)
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001897 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001898
Michael Kruse7037fde2016-12-15 09:25:14 +00001899 auto *L = LI.getLoopFor(CI->getParent());
1900 auto *Val = CI->getArgOperand(0);
1901 ParameterSetTy DetectedParams;
1902 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
1903 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1904 CI->getDebugLoc(),
1905 "Non-affine user assumption ignored.");
1906 continue;
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001907 }
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001908
Michael Kruse7037fde2016-12-15 09:25:14 +00001909 // Collect all newly introduced parameters.
1910 ParameterSetTy NewParams;
1911 for (auto *Param : DetectedParams) {
1912 Param = extractConstantFactor(Param, *SE).second;
1913 Param = getRepresentingInvariantLoadSCEV(Param);
1914 if (Parameters.count(Param))
1915 continue;
1916 NewParams.insert(Param);
1917 }
1918
1919 SmallVector<isl_set *, 2> ConditionSets;
1920 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
1921 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
1922 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
1923 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
1924 isl_set_free(Dom);
1925
1926 if (!Valid)
1927 continue;
1928
1929 isl_set *AssumptionCtx = nullptr;
1930 if (InScop) {
1931 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
1932 isl_set_free(ConditionSets[0]);
1933 } else {
1934 AssumptionCtx = isl_set_complement(ConditionSets[1]);
1935 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
1936 }
1937
1938 // Project out newly introduced parameters as they are not otherwise
1939 // useful.
1940 if (!NewParams.empty()) {
1941 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
1942 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
1943 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
1944 isl_id_free(Id);
1945
1946 if (!NewParams.count(Param))
1947 continue;
1948
1949 AssumptionCtx =
1950 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
1951 }
1952 }
1953
1954 emitOptimizationRemarkAnalysis(
1955 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1956 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1957 Context = isl_set_intersect(Context, AssumptionCtx);
1958 }
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001959 }
1960}
1961
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001962void Scop::addUserContext() {
1963 if (UserContextStr.empty())
1964 return;
1965
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001966 isl_set *UserContext =
1967 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001968 isl_space *Space = getParamSpace();
1969 if (isl_space_dim(Space, isl_dim_param) !=
1970 isl_set_dim(UserContext, isl_dim_param)) {
1971 auto SpaceStr = isl_space_to_str(Space);
1972 errs() << "Error: the context provided in -polly-context has not the same "
1973 << "number of dimensions than the computed context. Due to this "
1974 << "mismatch, the -polly-context option is ignored. Please provide "
1975 << "the context in the parameter space: " << SpaceStr << ".\n";
1976 free(SpaceStr);
1977 isl_set_free(UserContext);
1978 isl_space_free(Space);
1979 return;
1980 }
1981
1982 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001983 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1984 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001985
1986 if (strcmp(NameContext, NameUserContext) != 0) {
1987 auto SpaceStr = isl_space_to_str(Space);
1988 errs() << "Error: the name of dimension " << i
1989 << " provided in -polly-context "
1990 << "is '" << NameUserContext << "', but the name in the computed "
1991 << "context is '" << NameContext
1992 << "'. Due to this name mismatch, "
1993 << "the -polly-context option is ignored. Please provide "
1994 << "the context in the parameter space: " << SpaceStr << ".\n";
1995 free(SpaceStr);
1996 isl_set_free(UserContext);
1997 isl_space_free(Space);
1998 return;
1999 }
2000
2001 UserContext =
2002 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2003 isl_space_get_dim_id(Space, isl_dim_param, i));
2004 }
2005
2006 Context = isl_set_intersect(Context, UserContext);
2007 isl_space_free(Space);
2008}
2009
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002010void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002011 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002012
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002013 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002014 for (LoadInst *LInst : RIL) {
2015 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2016
Johannes Doerfert96e54712016-02-07 17:30:13 +00002017 Type *Ty = LInst->getType();
2018 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002019 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002020 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002021 continue;
2022 }
2023
2024 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002025 InvariantEquivClasses.emplace_back(
2026 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002027 }
2028}
2029
Tobias Grosser6be480c2011-11-08 15:41:13 +00002030void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002031 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002032 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002033 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002034 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002035}
2036
Tobias Grosser18daaca2012-05-22 10:47:27 +00002037void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002038 unsigned PDim = 0;
2039 for (auto *Parameter : Parameters) {
2040 ConstantRange SRange = SE->getSignedRange(Parameter);
2041 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002042 }
2043}
2044
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002045void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002046 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002047 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002048
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002049 unsigned PDim = 0;
2050 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002051 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002052 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002053 }
2054
2055 // Align the parameters of all data structures to the model.
2056 Context = isl_set_align_params(Context, Space);
2057
Johannes Doerferta60ad842016-05-10 12:18:22 +00002058 // As all parameters are known add bounds to them.
2059 addParameterBounds();
2060
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002061 for (ScopStmt &Stmt : *this)
2062 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002063
2064 // Simplify the schedule according to the context too.
2065 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002066}
2067
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002068static __isl_give isl_set *
2069simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2070 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002071 // If we have modeled all blocks in the SCoP that have side effects we can
2072 // simplify the context with the constraints that are needed for anything to
2073 // be executed at all. However, if we have error blocks in the SCoP we already
2074 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002075 // domains, thus we cannot use the remaining domain to simplify the
2076 // assumptions.
2077 if (!S.hasErrorBlock()) {
2078 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2079 AssumptionContext =
2080 isl_set_gist_params(AssumptionContext, DomainParameters);
2081 }
2082
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002083 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2084 return AssumptionContext;
2085}
2086
2087void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002088 // The parameter constraints of the iteration domains give us a set of
2089 // constraints that need to hold for all cases where at least a single
2090 // statement iteration is executed in the whole scop. We now simplify the
2091 // assumed context under the assumption that such constraints hold and at
2092 // least a single statement iteration is executed. For cases where no
2093 // statement instances are executed, the assumptions we have taken about
2094 // the executed code do not matter and can be changed.
2095 //
2096 // WARNING: This only holds if the assumptions we have taken do not reduce
2097 // the set of statement instances that are executed. Otherwise we
2098 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002099 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002100 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002101 // performed. In such a case, modifying the run-time conditions and
2102 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002103 // to not be executed.
2104 //
2105 // Example:
2106 //
2107 // When delinearizing the following code:
2108 //
2109 // for (long i = 0; i < 100; i++)
2110 // for (long j = 0; j < m; j++)
2111 // A[i+p][j] = 1.0;
2112 //
2113 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002114 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002115 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002116 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002117 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002118}
2119
Tobias Grosserc80d6972016-09-02 06:33:33 +00002120/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002121static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002122 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2123 isl_pw_multi_aff *MinPMA, *MaxPMA;
2124 isl_pw_aff *LastDimAff;
2125 isl_aff *OneAff;
2126 unsigned Pos;
2127
Johannes Doerfert6296d952016-04-22 11:38:19 +00002128 Set = isl_set_remove_divs(Set);
2129
Tobias Grosser90411a92017-02-16 19:11:33 +00002130 if (isl_set_n_basic_set(Set) >= MaxDisjunctsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002131 isl_set_free(Set);
2132 return isl_stat_error;
2133 }
2134
Johannes Doerfert9143d672014-09-27 11:02:39 +00002135 // Restrict the number of parameters involved in the access as the lexmin/
2136 // lexmax computation will take too long if this number is high.
2137 //
2138 // Experiments with a simple test case using an i7 4800MQ:
2139 //
2140 // #Parameters involved | Time (in sec)
2141 // 6 | 0.01
2142 // 7 | 0.04
2143 // 8 | 0.12
2144 // 9 | 0.40
2145 // 10 | 1.54
2146 // 11 | 6.78
2147 // 12 | 30.38
2148 //
2149 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2150 unsigned InvolvedParams = 0;
2151 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2152 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2153 InvolvedParams++;
2154
2155 if (InvolvedParams > RunTimeChecksMaxParameters) {
2156 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002157 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002158 }
2159 }
2160
Johannes Doerfertb164c792014-09-18 11:17:17 +00002161 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2162 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2163
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002164 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2165 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2166
Johannes Doerfertb164c792014-09-18 11:17:17 +00002167 // Adjust the last dimension of the maximal access by one as we want to
2168 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2169 // we test during code generation might now point after the end of the
2170 // allocated array but we will never dereference it anyway.
2171 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2172 "Assumed at least one output dimension");
2173 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2174 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2175 OneAff = isl_aff_zero_on_domain(
2176 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2177 OneAff = isl_aff_add_constant_si(OneAff, 1);
2178 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2179 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2180
2181 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2182
2183 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002184 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002185}
2186
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002187static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2188 isl_set *Domain = MA->getStatement()->getDomain();
2189 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2190 return isl_set_reset_tuple_id(Domain);
2191}
2192
Tobias Grosserc80d6972016-09-02 06:33:33 +00002193/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002194static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002195 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002196
Tobias Grossere9522232017-01-16 15:49:04 +00002197 MinMaxAccesses.reserve(AliasGroup.size());
2198
2199 isl_union_set *Domains = S.getDomains();
2200 isl_union_map *Accesses = isl_union_map_empty(S.getParamSpace());
2201
2202 for (MemoryAccess *MA : AliasGroup)
2203 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2204
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002205 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2206 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002207 Locations = isl_union_set_coalesce(Locations);
2208 Locations = isl_union_set_detect_equalities(Locations);
Tobias Grosserff400872017-02-01 10:12:09 +00002209 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
2210 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002211 isl_union_set_free(Locations);
2212 return Valid;
2213}
2214
Tobias Grosserc80d6972016-09-02 06:33:33 +00002215/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002216///
2217///{
2218
Tobias Grosserc80d6972016-09-02 06:33:33 +00002219/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002220static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2221 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2222 : RN->getNodeAs<BasicBlock>();
2223}
2224
Tobias Grosserc80d6972016-09-02 06:33:33 +00002225/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002226static inline BasicBlock *
2227getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002228 if (RN->isSubRegion()) {
2229 assert(idx == 0);
2230 return RN->getNodeAs<Region>()->getExit();
2231 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002232 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002233}
2234
Tobias Grosserc80d6972016-09-02 06:33:33 +00002235/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002236static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2237 if (!RN->isSubRegion())
2238 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2239
2240 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2241 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2242 while (L && NonAffineSubRegion->contains(L))
2243 L = L->getParentLoop();
2244 return L;
2245}
2246
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002247static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2248 if (!RN->isSubRegion())
2249 return 1;
2250
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002251 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002252 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002253}
2254
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002255static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2256 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002257 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002258 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002259 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002260 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002261 return true;
2262 return false;
2263}
2264
Johannes Doerfert96425c22015-08-30 21:13:53 +00002265///}
2266
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002267static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2268 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002269 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002270 isl_id *DimId =
2271 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2272 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2273}
2274
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002275__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002276 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002277}
2278
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002279__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002280 auto DIt = DomainMap.find(BB);
2281 if (DIt != DomainMap.end())
2282 return isl_set_copy(DIt->getSecond());
2283
2284 auto &RI = *R.getRegionInfo();
2285 auto *BBR = RI.getRegionFor(BB);
2286 while (BBR->getEntry() == BB)
2287 BBR = BBR->getParent();
2288 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002289}
2290
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002291bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002292
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002293 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002294 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002295 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2296 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002297 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002298
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002299 while (LD-- >= 0) {
2300 S = addDomainDimId(S, LD + 1, L);
2301 L = L->getParentLoop();
2302 }
2303
Johannes Doerferta3519512016-04-23 13:02:23 +00002304 // Initialize the invalid domain.
2305 auto *EntryStmt = getStmtFor(EntryBB);
2306 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2307
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002308 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002309
Johannes Doerfert432658d2016-01-26 11:01:41 +00002310 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002311 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002312
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002313 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002314 return false;
2315
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002316 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002317 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002318
2319 // Error blocks and blocks dominated by them have been assumed to never be
2320 // executed. Representing them in the Scop does not add any value. In fact,
2321 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002322 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002323 // will cause problems when building up a ScopStmt for them.
2324 // Furthermore, basic blocks dominated by error blocks may reference
2325 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002326 // can themselves not be constructed properly. To this end we will replace
2327 // the domains of error blocks and those only reachable via error blocks
2328 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002329 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002330 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002331 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002332 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002333
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002334 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002335}
2336
Tobias Grosserc80d6972016-09-02 06:33:33 +00002337/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002338/// to be compatible to domains constructed for loop @p NewL.
2339///
2340/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2341/// edge from @p OldL to @p NewL.
2342static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2343 __isl_take isl_set *Dom,
2344 Loop *OldL, Loop *NewL) {
2345
2346 // If the loops are the same there is nothing to do.
2347 if (NewL == OldL)
2348 return Dom;
2349
2350 int OldDepth = S.getRelativeLoopDepth(OldL);
2351 int NewDepth = S.getRelativeLoopDepth(NewL);
2352 // If both loops are non-affine loops there is nothing to do.
2353 if (OldDepth == -1 && NewDepth == -1)
2354 return Dom;
2355
2356 // Distinguish three cases:
2357 // 1) The depth is the same but the loops are not.
2358 // => One loop was left one was entered.
2359 // 2) The depth increased from OldL to NewL.
2360 // => One loop was entered, none was left.
2361 // 3) The depth decreased from OldL to NewL.
2362 // => Loops were left were difference of the depths defines how many.
2363 if (OldDepth == NewDepth) {
2364 assert(OldL->getParentLoop() == NewL->getParentLoop());
2365 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2366 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2367 Dom = addDomainDimId(Dom, NewDepth, NewL);
2368 } else if (OldDepth < NewDepth) {
2369 assert(OldDepth + 1 == NewDepth);
2370 auto &R = S.getRegion();
2371 (void)R;
2372 assert(NewL->getParentLoop() == OldL ||
2373 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2374 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2375 Dom = addDomainDimId(Dom, NewDepth, NewL);
2376 } else {
2377 assert(OldDepth > NewDepth);
2378 int Diff = OldDepth - NewDepth;
2379 int NumDim = isl_set_n_dim(Dom);
2380 assert(NumDim >= Diff);
2381 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2382 }
2383
2384 return Dom;
2385}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002386
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002387bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2388 LoopInfo &LI) {
2389 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002390
2391 ReversePostOrderTraversal<Region *> RTraversal(R);
2392 for (auto *RN : RTraversal) {
2393
2394 // Recurse for affine subregions but go on for basic blocks and non-affine
2395 // subregions.
2396 if (RN->isSubRegion()) {
2397 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002398 if (!isNonAffineSubRegion(SubRegion)) {
2399 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002400 continue;
2401 }
2402 }
2403
2404 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2405 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002406 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002407 isl_set *&Domain = DomainMap[BB];
2408 assert(Domain && "Cannot propagate a nullptr");
2409
Johannes Doerferta3519512016-04-23 13:02:23 +00002410 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002411 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002412 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002413
Johannes Doerferta3519512016-04-23 13:02:23 +00002414 if (!IsInvalidBlock) {
2415 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002416 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002417 isl_set_free(InvalidDomain);
2418 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002419 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2420 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2421 AS_RESTRICTION);
2422 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002423 }
2424
Johannes Doerferta3519512016-04-23 13:02:23 +00002425 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002426 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002427 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002428 }
2429
Johannes Doerferta3519512016-04-23 13:02:23 +00002430 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002431 auto *TI = BB->getTerminator();
2432 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2433 for (unsigned u = 0; u < NumSuccs; u++) {
2434 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002435 auto *SuccStmt = getStmtFor(SuccBB);
2436
2437 // Skip successors outside the SCoP.
2438 if (!SuccStmt)
2439 continue;
2440
Johannes Doerferte4459a22016-04-25 13:34:50 +00002441 // Skip backedges.
2442 if (DT.dominates(SuccBB, BB))
2443 continue;
2444
Johannes Doerferta3519512016-04-23 13:02:23 +00002445 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2446 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2447 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2448 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2449 SuccInvalidDomain =
2450 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2451 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2452 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2453 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002454
Michael Krusebc150122016-05-02 12:25:18 +00002455 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002456 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002457 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002458 continue;
2459
Johannes Doerferta3519512016-04-23 13:02:23 +00002460 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002461 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002462 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002463 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002464
2465 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002466 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002467
2468 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002469}
2470
Johannes Doerfert642594a2016-04-04 07:57:39 +00002471void Scop::propagateDomainConstraintsToRegionExit(
2472 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002473 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002474
2475 // Check if the block @p BB is the entry of a region. If so we propagate it's
2476 // domain to the exit block of the region. Otherwise we are done.
2477 auto *RI = R.getRegionInfo();
2478 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2479 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002480 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002481 return;
2482
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002483 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002484 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002485 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002486 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002487 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002488 SmallVector<BasicBlock *, 4> LatchBBs;
2489 BBLoop->getLoopLatches(LatchBBs);
2490 for (auto *LatchBB : LatchBBs)
2491 if (BB != LatchBB && BBReg->contains(LatchBB))
2492 return;
2493 L = L->getParentLoop();
2494 }
2495
2496 auto *Domain = DomainMap[BB];
2497 assert(Domain && "Cannot propagate a nullptr");
2498
2499 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2500
2501 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2502 // adjust the domain before we can propagate it.
2503 auto *AdjustedDomain =
2504 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2505 auto *&ExitDomain = DomainMap[ExitBB];
2506
2507 // If the exit domain is not yet created we set it otherwise we "add" the
2508 // current domain.
2509 ExitDomain =
2510 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2511
Johannes Doerferta3519512016-04-23 13:02:23 +00002512 // Initialize the invalid domain.
2513 auto *ExitStmt = getStmtFor(ExitBB);
2514 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2515
Johannes Doerfert642594a2016-04-04 07:57:39 +00002516 FinishedExitBlocks.insert(ExitBB);
2517}
2518
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002519bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2520 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002521 // To create the domain for each block in R we iterate over all blocks and
2522 // subregions in R and propagate the conditions under which the current region
2523 // element is executed. To this end we iterate in reverse post order over R as
2524 // it ensures that we first visit all predecessors of a region node (either a
2525 // basic block or a subregion) before we visit the region node itself.
2526 // Initially, only the domain for the SCoP region entry block is set and from
2527 // there we propagate the current domain to all successors, however we add the
2528 // condition that the successor is actually executed next.
2529 // As we are only interested in non-loop carried constraints here we can
2530 // simply skip loop back edges.
2531
Johannes Doerfert642594a2016-04-04 07:57:39 +00002532 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002533 ReversePostOrderTraversal<Region *> RTraversal(R);
2534 for (auto *RN : RTraversal) {
2535
2536 // Recurse for affine subregions but go on for basic blocks and non-affine
2537 // subregions.
2538 if (RN->isSubRegion()) {
2539 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002540 if (!isNonAffineSubRegion(SubRegion)) {
2541 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002542 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002543 continue;
2544 }
2545 }
2546
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002547 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002548 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002549
Johannes Doerfert96425c22015-08-30 21:13:53 +00002550 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002551 TerminatorInst *TI = BB->getTerminator();
2552
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002553 if (isa<UnreachableInst>(TI))
2554 continue;
2555
Johannes Doerfertf5673802015-10-01 23:48:18 +00002556 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002557 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002558 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002559 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002560
Johannes Doerfert642594a2016-04-04 07:57:39 +00002561 auto *BBLoop = getRegionNodeLoop(RN, LI);
2562 // Propagate the domain from BB directly to blocks that have a superset
2563 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002564 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002565
2566 // If all successors of BB have been set a domain through the propagation
2567 // above we do not need to build condition sets but can just skip this
2568 // block. However, it is important to note that this is a local property
2569 // with regards to the region @p R. To this end FinishedExitBlocks is a
2570 // local variable.
2571 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2572 return FinishedExitBlocks.count(SuccBB);
2573 };
2574 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2575 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002576
2577 // Build the condition sets for the successor nodes of the current region
2578 // node. If it is a non-affine subregion we will always execute the single
2579 // exit node, hence the single entry node domain is the condition set. For
2580 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002581 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002582 if (RN->isSubRegion())
2583 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002584 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2585 ConditionSets))
2586 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002587
2588 // Now iterate over the successors and set their initial domain based on
2589 // their condition set. We skip back edges here and have to be careful when
2590 // we leave a loop not to keep constraints over a dimension that doesn't
2591 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002592 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002593 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002594 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002595 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002596
Johannes Doerfert535de032016-04-19 14:49:05 +00002597 auto *SuccStmt = getStmtFor(SuccBB);
2598 // Skip blocks outside the region.
2599 if (!SuccStmt) {
2600 isl_set_free(CondSet);
2601 continue;
2602 }
2603
Johannes Doerfert642594a2016-04-04 07:57:39 +00002604 // If we propagate the domain of some block to "SuccBB" we do not have to
2605 // adjust the domain.
2606 if (FinishedExitBlocks.count(SuccBB)) {
2607 isl_set_free(CondSet);
2608 continue;
2609 }
2610
Johannes Doerfert96425c22015-08-30 21:13:53 +00002611 // Skip back edges.
2612 if (DT.dominates(SuccBB, BB)) {
2613 isl_set_free(CondSet);
2614 continue;
2615 }
2616
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002617 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002618 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002619 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002620
2621 // Set the domain for the successor or merge it with an existing domain in
2622 // case there are multiple paths (without loop back edges) to the
2623 // successor block.
2624 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002625
Johannes Doerferta3519512016-04-23 13:02:23 +00002626 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002627 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002628 } else {
2629 // Initialize the invalid domain.
2630 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2631 SuccDomain = CondSet;
2632 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002633
Michael Krusebc150122016-05-02 12:25:18 +00002634 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002635 // In case this happens we will clean up and bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002636 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002637 continue;
2638
2639 invalidate(COMPLEXITY, DebugLoc());
2640 while (++u < ConditionSets.size())
2641 isl_set_free(ConditionSets[u]);
2642 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002643 }
2644 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002645
2646 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002647}
2648
Michael Krused56b90a2016-09-01 09:03:27 +00002649__isl_give isl_set *
2650Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2651 __isl_keep isl_set *Domain,
2652 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002653 // If @p BB is the ScopEntry we are done
2654 if (R.getEntry() == BB)
2655 return isl_set_universe(isl_set_get_space(Domain));
2656
2657 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002658 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002659
2660 // The region info of this function.
2661 auto &RI = *R.getRegionInfo();
2662
2663 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2664
2665 // A domain to collect all predecessor domains, thus all conditions under
2666 // which the block is executed. To this end we start with the empty domain.
2667 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2668
2669 // Set of regions of which the entry block domain has been propagated to BB.
2670 // all predecessors inside any of the regions can be skipped.
2671 SmallSet<Region *, 8> PropagatedRegions;
2672
2673 for (auto *PredBB : predecessors(BB)) {
2674 // Skip backedges.
2675 if (DT.dominates(BB, PredBB))
2676 continue;
2677
2678 // If the predecessor is in a region we used for propagation we can skip it.
2679 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2680 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2681 PredBBInRegion)) {
2682 continue;
2683 }
2684
2685 // Check if there is a valid region we can use for propagation, thus look
2686 // for a region that contains the predecessor and has @p BB as exit block.
2687 auto *PredR = RI.getRegionFor(PredBB);
2688 while (PredR->getExit() != BB && !PredR->contains(BB))
2689 PredR->getParent();
2690
2691 // If a valid region for propagation was found use the entry of that region
2692 // for propagation, otherwise the PredBB directly.
2693 if (PredR->getExit() == BB) {
2694 PredBB = PredR->getEntry();
2695 PropagatedRegions.insert(PredR);
2696 }
2697
Johannes Doerfert41cda152016-04-08 10:32:26 +00002698 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002699 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2700 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2701
2702 PredDom = isl_set_union(PredDom, PredBBDom);
2703 }
2704
2705 return PredDom;
2706}
2707
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002708bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2709 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002710 // Iterate over the region R and propagate the domain constrains from the
2711 // predecessors to the current node. In contrast to the
2712 // buildDomainsWithBranchConstraints function, this one will pull the domain
2713 // information from the predecessors instead of pushing it to the successors.
2714 // Additionally, we assume the domains to be already present in the domain
2715 // map here. However, we iterate again in reverse post order so we know all
2716 // predecessors have been visited before a block or non-affine subregion is
2717 // visited.
2718
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002719 ReversePostOrderTraversal<Region *> RTraversal(R);
2720 for (auto *RN : RTraversal) {
2721
2722 // Recurse for affine subregions but go on for basic blocks and non-affine
2723 // subregions.
2724 if (RN->isSubRegion()) {
2725 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002726 if (!isNonAffineSubRegion(SubRegion)) {
2727 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002728 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002729 continue;
2730 }
2731 }
2732
2733 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002734 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002735 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002736
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002737 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002738 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002739 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002740 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002741
Johannes Doerfert642594a2016-04-04 07:57:39 +00002742 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002743 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002744 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2745 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002746 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002747
2748 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002749}
2750
Tobias Grosserc80d6972016-09-02 06:33:33 +00002751/// Create a map to map from a given iteration to a subsequent iteration.
2752///
2753/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2754/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002755/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002756///
2757/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002758static __isl_give isl_map *
2759createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2760 auto *MapSpace = isl_space_map_from_set(SetSpace);
2761 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2762 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2763 if (u != Dim)
2764 NextIterationMap =
2765 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2766 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2767 C = isl_constraint_set_constant_si(C, 1);
2768 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2769 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2770 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2771 return NextIterationMap;
2772}
2773
Johannes Doerfert297c7202016-05-10 13:06:42 +00002774bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002775 int LoopDepth = getRelativeLoopDepth(L);
2776 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002777
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002778 BasicBlock *HeaderBB = L->getHeader();
2779 assert(DomainMap.count(HeaderBB));
2780 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002781
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002782 isl_map *NextIterationMap =
2783 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002784
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002785 isl_set *UnionBackedgeCondition =
2786 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002787
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002788 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2789 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002790
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002791 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002792
2793 // If the latch is only reachable via error statements we skip it.
2794 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2795 if (!LatchBBDom)
2796 continue;
2797
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002798 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002799
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002800 TerminatorInst *TI = LatchBB->getTerminator();
2801 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00002802 assert(BI && "Only branch instructions allowed in loop latches");
2803
2804 if (BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002805 BackedgeCondition = isl_set_copy(LatchBBDom);
2806 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002807 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002808 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002809 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
Michael Krusee1dc3872016-11-03 15:19:41 +00002810 ConditionSets)) {
2811 isl_map_free(NextIterationMap);
2812 isl_set_free(UnionBackedgeCondition);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002813 return false;
Michael Krusee1dc3872016-11-03 15:19:41 +00002814 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002815
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002816 // Free the non back edge condition set as we do not need it.
2817 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002818
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002819 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002820 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002821
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002822 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2823 assert(LatchLoopDepth >= LoopDepth);
2824 BackedgeCondition =
2825 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2826 LatchLoopDepth - LoopDepth);
2827 UnionBackedgeCondition =
2828 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002829 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002830
2831 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2832 for (int i = 0; i < LoopDepth; i++)
2833 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2834
2835 isl_set *UnionBackedgeConditionComplement =
2836 isl_set_complement(UnionBackedgeCondition);
2837 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2838 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2839 UnionBackedgeConditionComplement =
2840 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2841 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2842 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2843
2844 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2845 HeaderBBDom = Parts.second;
2846
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002847 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2848 // the bounded assumptions to the context as they are already implied by the
2849 // <nsw> tag.
2850 if (Affinator.hasNSWAddRecForLoop(L)) {
2851 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002852 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002853 }
2854
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002855 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002856 recordAssumption(INFINITELOOP, UnboundedCtx,
2857 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002858 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002859}
2860
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002861MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00002862 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002863
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00002864 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002865 if (!PointerBaseInst)
2866 return nullptr;
2867
2868 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2869 if (!BasePtrStmt)
2870 return nullptr;
2871
2872 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2873}
2874
2875bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2876 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00002877 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
2878 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
2879 bool Hoistable = NHCtx != nullptr;
2880 isl_set_free(NHCtx);
2881 return !Hoistable;
2882 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002883
Tobias Grosserbe372d52017-02-09 10:11:58 +00002884 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00002885 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002886 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00002887 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002888
2889 return false;
2890}
2891
Johannes Doerfert5210da52016-06-02 11:06:54 +00002892bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002893 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00002894 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002895
Johannes Doerfertcd195322016-11-17 21:41:08 +00002896 if (buildAliasGroups(AA)) {
2897 // Aliasing assumptions do not go through addAssumption but we still want to
2898 // collect statistics so we do it here explicitly.
2899 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00002900 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00002901 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00002902 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002903
2904 // If a problem occurs while building the alias groups we need to delete
2905 // this SCoP and pretend it wasn't valid in the first place. To this end
2906 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002907 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002908
2909 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2910 << " could not be created as the number of parameters involved "
2911 "is too high. The SCoP will be "
2912 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2913 "the maximal number of parameters but be advised that the "
2914 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00002915 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002916}
2917
Tobias Grosser889830b2017-02-09 23:12:22 +00002918std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00002919Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002920 AliasSetTracker AST(AA);
2921
2922 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00002923 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002924 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002925
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002926 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002927 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2928 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00002929
2930 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002931 if (StmtDomainEmpty)
2932 continue;
2933
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002934 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002935 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002936 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002937 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00002938 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00002939 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002940 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00002941 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002942 else
2943 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002944 AST.add(Acc);
2945 }
2946 }
2947
Tobias Grosser9edcf072017-01-16 14:07:57 +00002948 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002949 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002950 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002951 continue;
2952 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002953 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002954 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002955 if (AG.size() < 2)
2956 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002957 AliasGroups.push_back(std::move(AG));
2958 }
2959
Tobias Grosser9edcf072017-01-16 14:07:57 +00002960 return std::make_tuple(AliasGroups, HasWriteAccess);
2961}
2962
Tobias Grossere39f9122017-01-16 14:08:00 +00002963void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002964 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2965 AliasGroupTy NewAG;
2966 AliasGroupTy &AG = AliasGroups[u];
2967 AliasGroupTy::iterator AGI = AG.begin();
2968 isl_set *AGDomain = getAccessDomain(*AGI);
2969 while (AGI != AG.end()) {
2970 MemoryAccess *MA = *AGI;
2971 isl_set *MADomain = getAccessDomain(MA);
2972 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2973 NewAG.push_back(MA);
2974 AGI = AG.erase(AGI);
2975 isl_set_free(MADomain);
2976 } else {
2977 AGDomain = isl_set_union(AGDomain, MADomain);
2978 AGI++;
2979 }
2980 }
2981 if (NewAG.size() > 1)
2982 AliasGroups.push_back(std::move(NewAG));
2983 isl_set_free(AGDomain);
2984 }
Tobias Grossere39f9122017-01-16 14:08:00 +00002985}
2986
2987bool Scop::buildAliasGroups(AliasAnalysis &AA) {
2988 // To create sound alias checks we perform the following steps:
2989 // o) We partition each group into read only and non read only accesses.
2990 // o) For each group with more than one base pointer we then compute minimal
2991 // and maximal accesses to each array of a group in read only and non
2992 // read only partitions separately.
2993 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00002994 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00002995
2996 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
2997
2998 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002999
Johannes Doerfert13771732014-10-01 12:40:46 +00003000 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003001 bool Valid = buildAliasGroup(AG, HasWriteAccess);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003002 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003003 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003004 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003005
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003006 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003007}
3008
Tobias Grosser77f32572017-01-16 15:49:07 +00003009bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003010 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003011 AliasGroupTy ReadOnlyAccesses;
3012 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003013 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003014
3015 auto &F = getFunction();
3016
3017 if (AliasGroup.size() < 2)
3018 return true;
3019
3020 for (MemoryAccess *Access : AliasGroup) {
3021 emitOptimizationRemarkAnalysis(
3022 F.getContext(), DEBUG_TYPE, F,
3023 Access->getAccessInstruction()->getDebugLoc(),
3024 "Possibly aliasing pointer, use restrict keyword.");
3025
Tobias Grosser889830b2017-02-09 23:12:22 +00003026 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3027 if (HasWriteAccess.count(Array)) {
3028 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003029 ReadWriteAccesses.push_back(Access);
3030 } else {
3031 ReadOnlyAccesses.push_back(Access);
3032 }
3033 }
3034
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003035 // If there are no read-only pointers, and less than two read-write pointers,
3036 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003037 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003038 return true;
3039
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003040 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003041 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003042 return true;
3043
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003044 // For non-affine accesses, no alias check can be generated as we cannot
3045 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003046 for (MemoryAccess *MA : AliasGroup) {
3047 if (!MA->isAffine()) {
3048 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3049 return false;
3050 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003051 }
3052
3053 // Ensure that for all memory accesses for which we generate alias checks,
3054 // their base pointers are available.
3055 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003056 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3057 addRequiredInvariantLoad(
3058 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3059 }
3060
3061 MinMaxAliasGroups.emplace_back();
3062 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3063 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3064 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3065
3066 bool Valid;
3067
3068 Valid =
3069 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3070
3071 if (!Valid)
3072 return false;
3073
3074 // Bail out if the number of values we need to compare is too large.
3075 // This is important as the number of comparisons grows quadratically with
3076 // the number of values we need to compare.
3077 if (MinMaxAccessesReadWrite.size() + ReadOnlyAccesses.size() >
3078 RunTimeChecksMaxArraysPerGroup)
3079 return false;
3080
3081 Valid =
3082 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3083
3084 if (!Valid)
3085 return false;
3086
3087 return true;
3088}
3089
Tobias Grosserc80d6972016-09-02 06:33:33 +00003090/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003091static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003092 // Start with the smallest loop containing the entry and expand that
3093 // loop until it contains all blocks in the region. If there is a loop
3094 // containing all blocks in the region check if it is itself contained
3095 // and if so take the parent loop as it will be the smallest containing
3096 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003097 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003098 while (L) {
3099 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003100 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003101 AllContained &= L->contains(BB);
3102 if (AllContained)
3103 break;
3104 L = L->getParentLoop();
3105 }
3106
Johannes Doerfertef744432016-05-23 12:42:38 +00003107 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003108}
3109
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003110Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003111 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003112 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003113 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003114 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3115 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3116 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3117 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003118 if (IslOnErrorAbort)
3119 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003120 buildContext();
3121}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003122
Tobias Grosserbedef002016-12-02 08:10:56 +00003123void Scop::foldSizeConstantsToRight() {
3124 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3125
3126 for (auto Array : arrays()) {
3127 if (Array->getNumberOfDimensions() <= 1)
3128 continue;
3129
3130 isl_space *Space = Array->getSpace();
3131
3132 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3133
3134 if (!isl_union_set_contains(Accessed, Space)) {
3135 isl_space_free(Space);
3136 continue;
3137 }
3138
3139 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3140
3141 isl_map *Transform =
3142 isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3143
3144 std::vector<int> Int;
3145
3146 int Dims = isl_set_dim(Elements, isl_dim_set);
3147 for (int i = 0; i < Dims; i++) {
3148 isl_set *DimOnly =
3149 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3150 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3151 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3152
3153 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3154
3155 if (i == Dims - 1) {
3156 Int.push_back(1);
3157 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3158 isl_basic_set_free(DimHull);
3159 continue;
3160 }
3161
3162 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3163 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3164 isl_val *Val = isl_aff_get_denominator_val(Diff);
3165 isl_aff_free(Diff);
3166
3167 int ValInt = 1;
3168
3169 if (isl_val_is_int(Val))
3170 ValInt = isl_val_get_num_si(Val);
3171 isl_val_free(Val);
3172
3173 Int.push_back(ValInt);
3174
3175 isl_constraint *C = isl_constraint_alloc_equality(
3176 isl_local_space_from_space(isl_map_get_space(Transform)));
3177 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3178 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3179 Transform = isl_map_add_constraint(Transform, C);
3180 isl_basic_set_free(DimHull);
3181 continue;
3182 }
3183
3184 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3185 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3186
3187 int ValInt = 1;
3188 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3189 ValInt = 0;
3190 }
3191
3192 Int.push_back(ValInt);
3193 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3194 isl_basic_set_free(DimHull);
3195 isl_basic_set_free(ZeroSet);
3196 }
3197
3198 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3199
3200 if (!isl_set_is_subset(Elements, MappedElements)) {
3201 isl_set_free(Elements);
3202 isl_set_free(MappedElements);
3203 isl_map_free(Transform);
3204 continue;
3205 }
3206
3207 isl_set_free(MappedElements);
3208
3209 bool CanFold = true;
3210
3211 if (Int[0] <= 1)
3212 CanFold = false;
3213
3214 unsigned NumDims = Array->getNumberOfDimensions();
3215 for (unsigned i = 1; i < NumDims - 1; i++)
3216 if (Int[0] != Int[i] && Int[i])
3217 CanFold = false;
3218
3219 if (!CanFold) {
3220 isl_set_free(Elements);
3221 isl_map_free(Transform);
3222 continue;
3223 }
3224
Tobias Grosserbedef002016-12-02 08:10:56 +00003225 for (auto &Access : AccessFunctions)
3226 if (Access->getScopArrayInfo() == Array)
3227 Access->setAccessRelation(isl_map_apply_range(
3228 Access->getAccessRelation(), isl_map_copy(Transform)));
3229
3230 isl_map_free(Transform);
3231
3232 std::vector<const SCEV *> Sizes;
3233 for (unsigned i = 0; i < NumDims; i++) {
3234 auto Size = Array->getDimensionSize(i);
3235
3236 if (i == NumDims - 1)
3237 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3238 Sizes.push_back(Size);
3239 }
3240
3241 Array->updateSizes(Sizes, false /* CheckConsistency */);
3242
3243 isl_set_free(Elements);
3244 }
3245 isl_union_set_free(Accessed);
3246 return;
3247}
3248
Tobias Grosser491b7992016-12-02 05:21:22 +00003249void Scop::finalizeAccesses() {
3250 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003251 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003252 foldAccessRelations();
3253 assumeNoOutOfBounds();
3254}
3255
Michael Kruse7037fde2016-12-15 09:25:14 +00003256void Scop::init(AliasAnalysis &AA, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003257 buildInvariantEquivalenceClasses();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003258
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003259 if (!buildDomains(&R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003260 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003261
Michael Kruse7037fde2016-12-15 09:25:14 +00003262 addUserAssumptions(DT, LI);
Johannes Doerfertff68f462016-04-19 14:49:42 +00003263
Johannes Doerfert26404542016-05-10 12:19:47 +00003264 // Remove empty statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003265 // Exit early in case there are no executable statements left in this scop.
Michael Kruse977d38b2016-07-22 17:31:17 +00003266 simplifySCoP(false);
Michael Kruseafe06702015-10-02 16:33:27 +00003267 if (Stmts.empty())
3268 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003269
Michael Krusecac948e2015-10-02 13:53:07 +00003270 // The ScopStmts now have enough information to initialize themselves.
3271 for (ScopStmt &Stmt : Stmts)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003272 Stmt.init(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00003273
Johannes Doerfertb1d66082016-12-01 11:12:14 +00003274 // Check early for a feasible runtime context.
3275 if (!hasFeasibleRuntimeContext())
3276 return;
3277
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003278 // Check early for profitability. Afterwards it cannot change anymore,
3279 // only the runtime context could become infeasible.
3280 if (!isProfitable()) {
3281 invalidate(PROFITABLE, DebugLoc());
Tobias Grosser8286b832015-11-02 11:29:32 +00003282 return;
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003283 }
3284
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003285 buildSchedule(LI);
Tobias Grosser8286b832015-11-02 11:29:32 +00003286
Tobias Grosser491b7992016-12-02 05:21:22 +00003287 finalizeAccesses();
3288
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003289 realignParams();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003290 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003291
3292 // After the context was fully constructed, thus all our knowledge about
3293 // the parameters is in there, we add all recorded assumptions to the
3294 // assumed/invalid context.
3295 addRecordedAssumptions();
3296
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003297 simplifyContexts();
Johannes Doerfert5210da52016-06-02 11:06:54 +00003298 if (!buildAliasChecks(AA))
3299 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003300
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003301 hoistInvariantLoads();
3302 verifyInvariantLoads();
Michael Kruse977d38b2016-07-22 17:31:17 +00003303 simplifySCoP(true);
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003304
3305 // Check late for a feasible runtime context because profitability did not
3306 // change.
Johannes Doerfertb1d66082016-12-01 11:12:14 +00003307 if (!hasFeasibleRuntimeContext())
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003308 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003309}
3310
3311Scop::~Scop() {
3312 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003313 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003314 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003315 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003316
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003317 for (auto &It : ParameterIds)
3318 isl_id_free(It.second);
3319
Johannes Doerfert96425c22015-08-30 21:13:53 +00003320 for (auto It : DomainMap)
3321 isl_set_free(It.second);
3322
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003323 for (auto &AS : RecordedAssumptions)
3324 isl_set_free(AS.Set);
3325
Johannes Doerfertb164c792014-09-18 11:17:17 +00003326 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003327 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003328 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003329 isl_pw_multi_aff_free(MMA.first);
3330 isl_pw_multi_aff_free(MMA.second);
3331 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003332 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003333 isl_pw_multi_aff_free(MMA.first);
3334 isl_pw_multi_aff_free(MMA.second);
3335 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003336 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003337
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003338 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003339 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003340
3341 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003342 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003343 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003344 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003345 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003346 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003347 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003348}
3349
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003350void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003351 // Check all array accesses for each base pointer and find a (virtual) element
3352 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003353 for (ScopStmt &Stmt : *this)
3354 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003355 if (!Access->isArrayKind())
3356 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003357 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003358 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3359
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003360 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003361 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003362 unsigned DivisibleSize = Array->getElemSizeInBytes();
3363 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003364 while (!isDivisible(Subscript, DivisibleSize, *SE))
3365 DivisibleSize /= 2;
3366 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003367 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003368 }
3369
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003370 for (auto &Stmt : *this)
3371 for (auto &Access : Stmt)
3372 Access->updateDimensionality();
3373}
3374
Tobias Grosser491b7992016-12-02 05:21:22 +00003375void Scop::foldAccessRelations() {
3376 for (auto &Stmt : *this)
3377 for (auto &Access : Stmt)
3378 Access->foldAccessRelation();
3379}
3380
3381void Scop::assumeNoOutOfBounds() {
3382 for (auto &Stmt : *this)
3383 for (auto &Access : Stmt)
3384 Access->assumeNoOutOfBound();
3385}
3386
Michael Kruse977d38b2016-07-22 17:31:17 +00003387void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003388 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3389 ScopStmt &Stmt = *StmtIt;
3390
Johannes Doerfert26404542016-05-10 12:19:47 +00003391 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003392 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003393 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003394
Johannes Doerferteca9e892015-11-03 16:54:49 +00003395 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003396 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003397 bool OnlyRead = true;
3398 for (MemoryAccess *MA : Stmt) {
3399 if (MA->isRead())
3400 continue;
3401
3402 OnlyRead = false;
3403 break;
3404 }
3405
3406 RemoveStmt = OnlyRead;
3407 }
3408
Johannes Doerfert26404542016-05-10 12:19:47 +00003409 if (!RemoveStmt) {
3410 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003411 continue;
3412 }
3413
Johannes Doerfert26404542016-05-10 12:19:47 +00003414 // Remove the statement because it is unnecessary.
3415 if (Stmt.isRegionStmt())
3416 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3417 StmtMap.erase(BB);
3418 else
3419 StmtMap.erase(Stmt.getBasicBlock());
3420
3421 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003422 }
3423}
3424
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003425InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003426 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3427 if (!LInst)
3428 return nullptr;
3429
3430 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3431 LInst = cast<LoadInst>(Rep);
3432
Johannes Doerfert96e54712016-02-07 17:30:13 +00003433 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003434 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003435 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003436 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003437 continue;
3438
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003439 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003440 for (auto *MA : MAs)
3441 if (MA->getAccessInstruction() == Val)
3442 return &IAClass;
3443 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003444
3445 return nullptr;
3446}
3447
Tobias Grosserc80d6972016-09-02 06:33:33 +00003448/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003449static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003450 bool MAInvalidCtxIsEmpty,
3451 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003452 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3453 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3454 // TODO: We can provide more information for better but more expensive
3455 // results.
3456 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3457 LInst->getAlignment(), DL))
3458 return false;
3459
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003460 // If the location might be overwritten we do not hoist it unconditionally.
3461 //
3462 // TODO: This is probably to conservative.
3463 if (!NonHoistableCtxIsEmpty)
3464 return false;
3465
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003466 // If a dereferencable load is in a statement that is modeled precisely we can
3467 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003468 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003469 return true;
3470
3471 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003472 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003473 // statement domain.
3474 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3475 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3476 return false;
3477 return true;
3478}
3479
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003480void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003481
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003482 if (InvMAs.empty())
3483 return;
3484
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003485 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003486 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003487
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003488 // Get the context under which the statement is executed but remove the error
3489 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003490 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003491 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003492
Tobias Grosser90411a92017-02-16 19:11:33 +00003493 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003494 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003495 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3496 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003497 for (auto &InvMA : InvMAs)
3498 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003499 return;
3500 }
3501
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003502 // Project out all parameters that relate to loads in the statement. Otherwise
3503 // we could have cyclic dependences on the constraints under which the
3504 // hoisted loads are executed and we could not determine an order in which to
3505 // pre-load them. This happens because not only lower bounds are part of the
3506 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003507 for (auto &InvMA : InvMAs) {
3508 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003509 Instruction *AccInst = MA->getAccessInstruction();
3510 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003511 SetVector<Value *> Values;
3512 for (const SCEV *Parameter : Parameters) {
3513 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003514 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003515 if (!Values.count(AccInst))
3516 continue;
3517
3518 if (isl_id *ParamId = getIdForParam(Parameter)) {
3519 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3520 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3521 isl_id_free(ParamId);
3522 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003523 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003524 }
3525 }
3526
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003527 for (auto &InvMA : InvMAs) {
3528 auto *MA = InvMA.MA;
3529 auto *NHCtx = InvMA.NonHoistableCtx;
3530
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003531 // Check for another invariant access that accesses the same location as
3532 // MA and if found consolidate them. Otherwise create a new equivalence
3533 // class at the end of InvariantEquivClasses.
3534 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003535 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003536 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3537
Johannes Doerfert85676e32016-04-23 14:32:34 +00003538 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003539 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003540 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3541
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003542 isl_set *MACtx;
3543 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003544 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3545 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003546 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003547 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003548 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003549 } else {
3550 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003551 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003552 MACtx = isl_set_gist_params(MACtx, getContext());
3553 }
3554
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003555 bool Consolidated = false;
3556 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003557 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003558 continue;
3559
Johannes Doerfertdf880232016-03-03 12:26:58 +00003560 // If the pointer and the type is equal check if the access function wrt.
3561 // to the domain is equal too. It can happen that the domain fixes
3562 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003563 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003564 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003565 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003566 if (!MAs.empty()) {
3567 auto *LastMA = MAs.front();
3568
3569 auto *AR = isl_map_range(MA->getAccessRelation());
3570 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3571 bool SameAR = isl_set_is_equal(AR, LastAR);
3572 isl_set_free(AR);
3573 isl_set_free(LastAR);
3574
3575 if (!SameAR)
3576 continue;
3577 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003578
3579 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003580 MAs.push_front(MA);
3581
Johannes Doerfertdf880232016-03-03 12:26:58 +00003582 Consolidated = true;
3583
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003584 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003585 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003586 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003587 IAClassDomainCtx =
3588 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003589 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003590 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003591 break;
3592 }
3593
3594 if (Consolidated)
3595 continue;
3596
3597 // If we did not consolidate MA, thus did not find an equivalence class
3598 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003599 InvariantEquivClasses.emplace_back(
3600 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003601 }
3602
3603 isl_set_free(DomainCtx);
3604}
3605
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003606__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3607 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003608 // TODO: Loads that are not loop carried, hence are in a statement with
3609 // zero iterators, are by construction invariant, though we
3610 // currently "hoist" them anyway. This is necessary because we allow
3611 // them to be treated as parameters (e.g., in conditions) and our code
3612 // generation would otherwise use the old value.
3613
3614 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003615 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003616
Johannes Doerfertc9765462016-11-17 22:11:56 +00003617 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3618 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003619 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003620
3621 // Skip accesses that have an invariant base pointer which is defined but
3622 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3623 // returns a pointer that is used as a base address. However, as we want
3624 // to hoist indirect pointers, we allow the base pointer to be defined in
3625 // the region if it is also a memory access. Each ScopArrayInfo object
3626 // that has a base pointer origin has a base pointer that is loaded and
3627 // that it is invariant, thus it will be hoisted too. However, if there is
3628 // no base pointer origin we check that the base pointer is defined
3629 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003630 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003631 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003632 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003633
3634 // Skip accesses in non-affine subregions as they might not be executed
3635 // under the same condition as the entry of the non-affine subregion.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003636 if (BB != LI->getParent())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003637 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003638
3639 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003640 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003641
3642 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3643 Stmt.getNumIterators())) {
3644 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003645 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003646 }
3647
3648 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3649 isl_set *AccessRange = isl_map_range(AccessRelation);
3650
3651 isl_union_map *Written = isl_union_map_intersect_range(
3652 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003653 auto *WrittenCtx = isl_union_map_params(Written);
3654 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003655
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003656 if (!IsWritten)
3657 return WrittenCtx;
3658
3659 WrittenCtx = isl_set_remove_divs(WrittenCtx);
Tobias Grosser90411a92017-02-16 19:11:33 +00003660 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctsInDomain;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003661 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3662 isl_set_free(WrittenCtx);
3663 return nullptr;
3664 }
3665
3666 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3667 AS_RESTRICTION);
3668 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003669}
3670
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003671void Scop::verifyInvariantLoads() {
3672 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003673 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003674 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003675 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003676 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003677 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3678 return;
3679 }
3680 }
3681}
3682
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003683void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003684 if (!PollyInvariantLoadHoisting)
3685 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003686
Tobias Grosser0865e7752016-02-29 07:29:42 +00003687 isl_union_map *Writes = getWrites();
3688 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003689 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003690
Tobias Grosser0865e7752016-02-29 07:29:42 +00003691 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003692 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3693 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003694
3695 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003696 for (auto InvMA : InvariantAccesses)
3697 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003698 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003699 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003700 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003701}
3702
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003703const ScopArrayInfo *
3704Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
3705 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
3706 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00003707 assert((BasePtr || BaseName) &&
3708 "BasePtr and BaseName can not be nullptr at the same time.");
3709 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3710 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3711 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003712 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003713 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003714 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003715 DL, this, BaseName));
3716 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003717 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003718 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003719 // In case of mismatching array sizes, we bail out by setting the run-time
3720 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003721 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003722 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003723 }
Tobias Grosserab671442015-05-23 05:58:27 +00003724 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003725}
3726
Roman Gareevd7754a12016-07-30 09:25:51 +00003727const ScopArrayInfo *
3728Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3729 const std::vector<unsigned> &Sizes) {
3730 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3731 std::vector<const SCEV *> SCEVSizes;
3732
3733 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003734 if (size)
3735 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3736 else
3737 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003738
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003739 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3740 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00003741 return SAI;
3742}
3743
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003744const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003745 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003746 assert(SAI && "No ScopArrayInfo available for this base pointer");
3747 return SAI;
3748}
3749
Tobias Grosser74394f02013-01-14 22:40:23 +00003750std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003751
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003752std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003753 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003754 return stringFromIslObj(AssumedContext);
3755}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003756
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003757std::string Scop::getInvalidContextStr() const {
3758 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003759}
Tobias Grosser75805372011-04-29 06:27:02 +00003760
3761std::string Scop::getNameStr() const {
3762 std::string ExitName, EntryName;
3763 raw_string_ostream ExitStr(ExitName);
3764 raw_string_ostream EntryStr(EntryName);
3765
Tobias Grosserf240b482014-01-09 10:42:15 +00003766 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003767 EntryStr.str();
3768
3769 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003770 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003771 ExitStr.str();
3772 } else
3773 ExitName = "FunctionExit";
3774
3775 return EntryName + "---" + ExitName;
3776}
3777
Tobias Grosser74394f02013-01-14 22:40:23 +00003778__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003779__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003780 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003781}
3782
Tobias Grossere86109f2013-10-29 21:05:49 +00003783__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003784 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003785 return isl_set_copy(AssumedContext);
3786}
3787
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003788bool Scop::isProfitable() const {
3789 if (PollyProcessUnprofitable)
3790 return true;
3791
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003792 if (isEmpty())
3793 return false;
3794
3795 unsigned OptimizableStmtsOrLoops = 0;
3796 for (auto &Stmt : *this) {
3797 if (Stmt.getNumIterators() == 0)
3798 continue;
3799
3800 bool ContainsArrayAccs = false;
3801 bool ContainsScalarAccs = false;
3802 for (auto *MA : Stmt) {
3803 if (MA->isRead())
3804 continue;
3805 ContainsArrayAccs |= MA->isArrayKind();
3806 ContainsScalarAccs |= MA->isScalarKind();
3807 }
3808
Michael Kruse6ab44762016-10-04 17:33:39 +00003809 if (!UnprofitableScalarAccs || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003810 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3811 }
3812
3813 return OptimizableStmtsOrLoops > 1;
3814}
3815
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003816bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003817 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003818 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003819 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3820 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3821 isl_set_is_subset(PositiveContext, NegativeContext));
3822 isl_set_free(PositiveContext);
3823 if (!IsFeasible) {
3824 isl_set_free(NegativeContext);
3825 return false;
3826 }
3827
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003828 auto *DomainContext = isl_union_set_params(getDomains());
3829 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003830 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003831 isl_set_free(NegativeContext);
3832 isl_set_free(DomainContext);
3833
Johannes Doerfert43788c52015-08-20 05:58:56 +00003834 return IsFeasible;
3835}
3836
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003837static std::string toString(AssumptionKind Kind) {
3838 switch (Kind) {
3839 case ALIASING:
3840 return "No-aliasing";
3841 case INBOUNDS:
3842 return "Inbounds";
3843 case WRAPPING:
3844 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00003845 case UNSIGNED:
3846 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003847 case COMPLEXITY:
3848 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003849 case PROFITABLE:
3850 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003851 case ERRORBLOCK:
3852 return "No-error";
3853 case INFINITELOOP:
3854 return "Finite loop";
3855 case INVARIANTLOAD:
3856 return "Invariant load";
3857 case DELINEARIZATION:
3858 return "Delinearization";
3859 }
3860 llvm_unreachable("Unknown AssumptionKind!");
3861}
3862
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003863bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
3864 if (Sign == AS_ASSUMPTION) {
3865 if (isl_set_is_subset(Context, Set))
3866 return false;
3867
3868 if (isl_set_is_subset(AssumedContext, Set))
3869 return false;
3870 } else {
3871 if (isl_set_is_disjoint(Set, Context))
3872 return false;
3873
3874 if (isl_set_is_subset(Set, InvalidContext))
3875 return false;
3876 }
3877 return true;
3878}
3879
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003880bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3881 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003882 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
3883 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003884
Johannes Doerfertb3265a32016-11-17 22:08:40 +00003885 // Do never emit trivial assumptions as they only clutter the output.
3886 if (!PollyRemarksMinimal) {
3887 isl_set *Univ = nullptr;
3888 if (Sign == AS_ASSUMPTION)
3889 Univ = isl_set_universe(isl_set_get_space(Set));
3890
3891 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
3892 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
3893 isl_set_free(Univ);
3894
3895 if (IsTrivial)
3896 return false;
3897 }
3898
Johannes Doerfertcd195322016-11-17 21:41:08 +00003899 switch (Kind) {
3900 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003901 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003902 break;
3903 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003904 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003905 break;
3906 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003907 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003908 break;
3909 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003910 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003911 break;
3912 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003913 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003914 break;
3915 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003916 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003917 break;
3918 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003919 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003920 break;
3921 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003922 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003923 break;
3924 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003925 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003926 break;
3927 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003928 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003929 break;
3930 }
3931
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003932 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003933 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3934 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003935 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003936 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003937}
3938
3939void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003940 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003941 // Simplify the assumptions/restrictions first.
3942 Set = isl_set_gist_params(Set, getContext());
3943
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003944 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3945 isl_set_free(Set);
3946 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003947 }
3948
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003949 if (Sign == AS_ASSUMPTION) {
3950 AssumedContext = isl_set_intersect(AssumedContext, Set);
3951 AssumedContext = isl_set_coalesce(AssumedContext);
3952 } else {
3953 InvalidContext = isl_set_union(InvalidContext, Set);
3954 InvalidContext = isl_set_coalesce(InvalidContext);
3955 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003956}
3957
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003958void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003959 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00003960 assert((isl_set_is_params(Set) || BB) &&
3961 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003962 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003963}
3964
3965void Scop::addRecordedAssumptions() {
3966 while (!RecordedAssumptions.empty()) {
3967 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003968
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003969 if (!AS.BB) {
3970 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
3971 continue;
3972 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003973
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003974 // If the domain was deleted the assumptions are void.
3975 isl_set *Dom = getDomainConditions(AS.BB);
3976 if (!Dom) {
3977 isl_set_free(AS.Set);
3978 continue;
3979 }
3980
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003981 // If a basic block was given use its domain to simplify the assumption.
3982 // In case of restrictions we know they only have to hold on the domain,
3983 // thus we can intersect them with the domain of the block. However, for
3984 // assumptions the domain has to imply them, thus:
3985 // _ _____
3986 // Dom => S <==> A v B <==> A - B
3987 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003988 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003989 // assumption.
3990 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003991 if (AS.Sign == AS_RESTRICTION)
3992 S = isl_set_params(isl_set_intersect(S, Dom));
3993 else /* (AS.Sign == AS_ASSUMPTION) */
3994 S = isl_set_params(isl_set_subtract(Dom, S));
3995
3996 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003997 }
3998}
3999
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004000void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004001 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004002}
4003
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004004__isl_give isl_set *Scop::getInvalidContext() const {
4005 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004006}
4007
Tobias Grosser75805372011-04-29 06:27:02 +00004008void Scop::printContext(raw_ostream &OS) const {
4009 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004010 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004011
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004012 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004013 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004014
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004015 OS.indent(4) << "Invalid Context:\n";
4016 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004017
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004018 unsigned Dim = 0;
4019 for (const SCEV *Parameter : Parameters)
4020 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004021}
4022
Johannes Doerfertb164c792014-09-18 11:17:17 +00004023void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004024 int noOfGroups = 0;
4025 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004026 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004027 noOfGroups += 1;
4028 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004029 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004030 }
4031
Tobias Grosserbb853c22015-07-25 12:31:03 +00004032 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004033 if (MinMaxAliasGroups.empty()) {
4034 OS.indent(8) << "n/a\n";
4035 return;
4036 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004037
Tobias Grosserbb853c22015-07-25 12:31:03 +00004038 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004039
4040 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004041 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004042 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004043 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004044 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4045 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004046 }
4047 OS << " ]]\n";
4048 }
4049
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004050 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004051 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004052 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004053 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004054 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4055 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004056 }
4057 OS << " ]]\n";
4058 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004059 }
4060}
4061
Tobias Grosser75805372011-04-29 06:27:02 +00004062void Scop::printStatements(raw_ostream &OS) const {
4063 OS << "Statements {\n";
4064
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004065 for (const ScopStmt &Stmt : *this)
4066 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00004067
4068 OS.indent(4) << "}\n";
4069}
4070
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004071void Scop::printArrayInfo(raw_ostream &OS) const {
4072 OS << "Arrays {\n";
4073
Tobias Grosserab671442015-05-23 05:58:27 +00004074 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004075 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004076
4077 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004078
4079 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4080
4081 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004082 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004083
4084 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004085}
4086
Tobias Grosser75805372011-04-29 06:27:02 +00004087void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004088 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004089 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004090 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004091 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004092 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004093 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004094 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004095 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004096 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004097 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004098 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4099 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004100 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004101 }
4102 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004103 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004104 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004105 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00004106 printStatements(OS.indent(4));
4107}
4108
4109void Scop::dump() const { print(dbgs()); }
4110
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004111isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004112
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004113__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4114 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004115 // First try to use the SCEVAffinator to generate a piecewise defined
4116 // affine function from @p E in the context of @p BB. If that tasks becomes to
4117 // complex the affinator might return a nullptr. In such a case we invalidate
4118 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004119 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004120 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004121 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004122 // TODO: We could use a heuristic and either use:
4123 // SCEVAffinator::takeNonNegativeAssumption
4124 // or
4125 // SCEVAffinator::interpretAsUnsigned
4126 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004127 if (NonNegative)
4128 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004129 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004130 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004131
4132 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
4133 invalidate(COMPLEXITY, DL);
4134 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004135}
4136
Tobias Grosser808cd692015-07-14 09:33:13 +00004137__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004138 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004139
Tobias Grosser808cd692015-07-14 09:33:13 +00004140 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004141 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004142
4143 return Domain;
4144}
4145
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004146__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4147 PWACtx PWAC = getPwAff(E, BB);
4148 isl_set_free(PWAC.second);
4149 return PWAC.first;
4150}
4151
Tobias Grossere5a35142015-11-12 14:07:09 +00004152__isl_give isl_union_map *
4153Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4154 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004155
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004156 for (ScopStmt &Stmt : *this) {
4157 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004158 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004159 continue;
4160
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004161 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004162 isl_map *AccessDomain = MA->getAccessRelation();
4163 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004164 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004165 }
4166 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004167 return isl_union_map_coalesce(Accesses);
4168}
4169
4170__isl_give isl_union_map *Scop::getMustWrites() {
4171 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004172}
4173
4174__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004175 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004176}
4177
Tobias Grosser37eb4222014-02-20 21:43:54 +00004178__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004179 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004180}
4181
4182__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004183 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004184}
4185
Tobias Grosser2ac23382015-11-12 14:07:13 +00004186__isl_give isl_union_map *Scop::getAccesses() {
4187 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4188}
4189
Roman Gareevb3224ad2016-09-14 06:26:09 +00004190// Check whether @p Node is an extension node.
4191//
4192// @return true if @p Node is an extension node.
4193isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4194 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4195 return isl_bool_error;
4196 else
4197 return isl_bool_true;
4198}
4199
4200bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4201 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4202 nullptr) == isl_stat_error;
4203}
4204
Tobias Grosser808cd692015-07-14 09:33:13 +00004205__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004206 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004207 if (containsExtensionNode(Tree)) {
4208 isl_schedule_free(Tree);
4209 return nullptr;
4210 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004211 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004212 isl_schedule_free(Tree);
4213 return S;
4214}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004215
Tobias Grosser808cd692015-07-14 09:33:13 +00004216__isl_give isl_schedule *Scop::getScheduleTree() const {
4217 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4218 getDomains());
4219}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004220
Tobias Grosser808cd692015-07-14 09:33:13 +00004221void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4222 auto *S = isl_schedule_from_domain(getDomains());
4223 S = isl_schedule_insert_partial_schedule(
4224 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4225 isl_schedule_free(Schedule);
4226 Schedule = S;
4227}
4228
4229void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4230 isl_schedule_free(Schedule);
4231 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004232}
4233
4234bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4235 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004236 for (ScopStmt &Stmt : *this) {
4237 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004238 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4239 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4240
4241 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4242 isl_union_set_free(StmtDomain);
4243 isl_union_set_free(NewStmtDomain);
4244 continue;
4245 }
4246
4247 Changed = true;
4248
4249 isl_union_set_free(StmtDomain);
4250 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4251
4252 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004253 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004254 isl_union_set_free(NewStmtDomain);
4255 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004256 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004257 }
4258 isl_union_set_free(Domain);
4259 return Changed;
4260}
4261
Tobias Grosser75805372011-04-29 06:27:02 +00004262ScalarEvolution *Scop::getSE() const { return SE; }
4263
Tobias Grosser808cd692015-07-14 09:33:13 +00004264struct MapToDimensionDataTy {
4265 int N;
4266 isl_union_pw_multi_aff *Res;
4267};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004268
Tobias Grosserc80d6972016-09-02 06:33:33 +00004269// Create a function that maps the elements of 'Set' to its N-th dimension and
4270// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004271//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004272// @param Set The input set.
4273// @param User->N The dimension to map to.
4274// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004275//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004276// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004277static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4278 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4279 int Dim;
4280 isl_space *Space;
4281 isl_pw_multi_aff *PMA;
4282
4283 Dim = isl_set_dim(Set, isl_dim_set);
4284 Space = isl_set_get_space(Set);
4285 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4286 Dim - Data->N);
4287 if (Data->N > 1)
4288 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4289 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4290
4291 isl_set_free(Set);
4292
4293 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004294}
4295
Tobias Grosserc80d6972016-09-02 06:33:33 +00004296// Create an isl_multi_union_aff that defines an identity mapping from the
4297// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004298//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004299// # Example:
4300//
4301// Domain: { A[i,j]; B[i,j,k] }
4302// N: 1
4303//
4304// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4305//
4306// @param USet A union set describing the elements for which to generate a
4307// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004308// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004309// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004310static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004311mapToDimension(__isl_take isl_union_set *USet, int N) {
4312 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004313 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004314 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004315
Tobias Grosser808cd692015-07-14 09:33:13 +00004316 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004317
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004318 auto *Space = isl_union_set_get_space(USet);
4319 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004320
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004321 Data = {N, PwAff};
4322
4323 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004324 (void)Res;
4325
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004326 assert(Res == isl_stat_ok);
4327
4328 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004329 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4330}
4331
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004332void Scop::addScopStmt(BasicBlock *BB) {
4333 assert(BB && "Unexpected nullptr!");
4334 Stmts.emplace_back(*this, *BB);
4335 auto *Stmt = &Stmts.back();
4336 StmtMap[BB] = Stmt;
4337}
4338
4339void Scop::addScopStmt(Region *R) {
4340 assert(R && "Unexpected nullptr!");
4341 Stmts.emplace_back(*this, *R);
4342 auto *Stmt = &Stmts.back();
4343 for (BasicBlock *BB : R->blocks())
Tobias Grosser808cd692015-07-14 09:33:13 +00004344 StmtMap[BB] = Stmt;
Tobias Grosser808cd692015-07-14 09:33:13 +00004345}
4346
Roman Gareevb3224ad2016-09-14 06:26:09 +00004347ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4348 __isl_take isl_map *TargetRel,
4349 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004350#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004351 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4352 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4353 assert(isl_set_is_subset(Domain, TargetDomain) &&
4354 "Target access not defined for complete statement domain");
4355 assert(isl_set_is_subset(Domain, SourceDomain) &&
4356 "Source access not defined for complete statement domain");
4357 isl_set_free(SourceDomain);
4358 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004359#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004360 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4361 CopyStmtsNum++;
4362 return &(Stmts.back());
4363}
4364
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004365void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004366 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004367 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004368 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004369 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4370 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004371}
4372
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004373/// To generate a schedule for the elements in a Region we traverse the Region
4374/// in reverse-post-order and add the contained RegionNodes in traversal order
4375/// to the schedule of the loop that is currently at the top of the LoopStack.
4376/// For loop-free codes, this results in a correct sequential ordering.
4377///
4378/// Example:
4379/// bb1(0)
4380/// / \.
4381/// bb2(1) bb3(2)
4382/// \ / \.
4383/// bb4(3) bb5(4)
4384/// \ /
4385/// bb6(5)
4386///
4387/// Including loops requires additional processing. Whenever a loop header is
4388/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4389/// from an empty schedule, we first process all RegionNodes that are within
4390/// this loop and complete the sequential schedule at this loop-level before
4391/// processing about any other nodes. To implement this
4392/// loop-nodes-first-processing, the reverse post-order traversal is
4393/// insufficient. Hence, we additionally check if the traversal yields
4394/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4395/// These region-nodes are then queue and only traverse after the all nodes
4396/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004397void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004398 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004399
4400 ReversePostOrderTraversal<Region *> RTraversal(R);
4401 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4402 std::deque<RegionNode *> DelayList;
4403 bool LastRNWaiting = false;
4404
4405 // Iterate over the region @p R in reverse post-order but queue
4406 // sub-regions/blocks iff they are not part of the last encountered but not
4407 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4408 // that we queued the last sub-region/block from the reverse post-order
4409 // iterator. If it is set we have to explore the next sub-region/block from
4410 // the iterator (if any) to guarantee progress. If it is not set we first try
4411 // the next queued sub-region/blocks.
4412 while (!WorkList.empty() || !DelayList.empty()) {
4413 RegionNode *RN;
4414
4415 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4416 RN = WorkList.front();
4417 WorkList.pop_front();
4418 LastRNWaiting = false;
4419 } else {
4420 RN = DelayList.front();
4421 DelayList.pop_front();
4422 }
4423
4424 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004425 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004426 L = OuterScopLoop;
4427
Tobias Grosser151ae322016-04-03 19:36:52 +00004428 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004429 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004430 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004431 LastRNWaiting = true;
4432 DelayList.push_back(RN);
4433 continue;
4434 }
4435 LoopStack.push_back({L, nullptr, 0});
4436 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004437 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004438 }
4439
4440 return;
4441}
4442
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004443void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004444
Tobias Grosser8362c262016-01-06 15:30:06 +00004445 if (RN->isSubRegion()) {
4446 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004447 if (!isNonAffineSubRegion(LocalRegion)) {
4448 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004449 return;
4450 }
4451 }
Michael Kruse046dde42015-08-10 13:01:57 +00004452
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004453 auto &LoopData = LoopStack.back();
4454 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004455
Michael Kruse6f7721f2016-02-24 22:08:19 +00004456 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004457 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4458 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004459 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004460 }
4461
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004462 // Check if we just processed the last node in this loop. If we did, finalize
4463 // the loop by:
4464 //
4465 // - adding new schedule dimensions
4466 // - folding the resulting schedule into the parent loop schedule
4467 // - dropping the loop schedule from the LoopStack.
4468 //
4469 // Then continue to check surrounding loops, which might also have been
4470 // completed by this node.
4471 while (LoopData.L &&
4472 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004473 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004474 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004475
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004476 LoopStack.pop_back();
4477 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004478
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004479 if (Schedule) {
4480 auto *Domain = isl_schedule_get_domain(Schedule);
4481 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4482 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4483 NextLoopData.Schedule =
4484 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004485 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004486
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004487 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4488 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004489 }
Tobias Grosser75805372011-04-29 06:27:02 +00004490}
4491
Michael Kruse6f7721f2016-02-24 22:08:19 +00004492ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004493 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004494 if (StmtMapIt == StmtMap.end())
4495 return nullptr;
4496 return StmtMapIt->second;
4497}
4498
Michael Kruse6f7721f2016-02-24 22:08:19 +00004499ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4500 if (RN->isSubRegion())
4501 return getStmtFor(RN->getNodeAs<Region>());
4502 return getStmtFor(RN->getNodeAs<BasicBlock>());
4503}
4504
4505ScopStmt *Scop::getStmtFor(Region *R) const {
4506 ScopStmt *Stmt = getStmtFor(R->getEntry());
4507 assert(!Stmt || Stmt->getRegion() == R);
4508 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004509}
4510
Johannes Doerfert96425c22015-08-30 21:13:53 +00004511int Scop::getRelativeLoopDepth(const Loop *L) const {
4512 Loop *OuterLoop =
4513 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4514 if (!OuterLoop)
4515 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004516 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4517}
4518
Roman Gareevd7754a12016-07-30 09:25:51 +00004519ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4520 for (auto &SAI : arrays()) {
4521 if (SAI->getName() == BaseName)
4522 return SAI;
4523 }
4524 return nullptr;
4525}
4526
Johannes Doerfert99191c72016-05-31 09:41:04 +00004527//===----------------------------------------------------------------------===//
4528void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4529 AU.addRequired<LoopInfoWrapperPass>();
4530 AU.addRequired<RegionInfoPass>();
4531 AU.addRequired<DominatorTreeWrapperPass>();
4532 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4533 AU.addRequiredTransitive<ScopDetection>();
4534 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004535 AU.setPreservesAll();
4536}
4537
4538bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4539 auto &SD = getAnalysis<ScopDetection>();
4540
4541 if (!SD.isMaxRegionInScop(*R))
4542 return false;
4543
4544 Function *F = R->getEntry()->getParent();
4545 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4546 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4547 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4548 auto const &DL = F->getParent()->getDataLayout();
4549 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004550
Michael Kruse7037fde2016-12-15 09:25:14 +00004551 ScopBuilder SB(R, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004552 S = SB.getScop(); // take ownership of scop object
Tobias Grosser75805372011-04-29 06:27:02 +00004553 return false;
4554}
4555
Johannes Doerfert99191c72016-05-31 09:41:04 +00004556void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004557 if (S)
4558 S->print(OS);
4559 else
4560 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004561}
Tobias Grosser75805372011-04-29 06:27:02 +00004562
Johannes Doerfert99191c72016-05-31 09:41:04 +00004563char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004564
Johannes Doerfert99191c72016-05-31 09:41:04 +00004565Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4566
4567INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004568 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004569 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004570INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00004571INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004572INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004573INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004574INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004575INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004576INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004577 "Polly - Create polyhedral description of Scops", false,
4578 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004579
4580//===----------------------------------------------------------------------===//
4581void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4582 AU.addRequired<LoopInfoWrapperPass>();
4583 AU.addRequired<RegionInfoPass>();
4584 AU.addRequired<DominatorTreeWrapperPass>();
4585 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4586 AU.addRequiredTransitive<ScopDetection>();
4587 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004588 AU.setPreservesAll();
4589}
4590
4591bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4592 auto &SD = getAnalysis<ScopDetection>();
4593
4594 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4595 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4596 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4597 auto const &DL = F.getParent()->getDataLayout();
4598 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004599
4600 /// Create polyhedral descripton of scops for all the valid regions of a
4601 /// function.
4602 for (auto &It : SD) {
4603 Region *R = const_cast<Region *>(It);
4604 if (!SD.isMaxRegionInScop(*R))
4605 continue;
4606
Michael Kruse7037fde2016-12-15 09:25:14 +00004607 ScopBuilder SB(R, AA, DL, DT, LI, SD, SE);
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004608 std::unique_ptr<Scop> S = SB.getScop();
4609 if (!S)
4610 continue;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004611 bool Inserted =
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004612 RegionToScopMap.insert(std::make_pair(R, std::move(S))).second;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004613 assert(Inserted && "Building Scop for the same region twice!");
4614 (void)Inserted;
4615 }
4616 return false;
4617}
4618
4619void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4620 for (auto &It : RegionToScopMap) {
4621 if (It.second)
4622 It.second->print(OS);
4623 else
4624 OS << "Invalid Scop!\n";
4625 }
4626}
4627
4628char ScopInfoWrapperPass::ID = 0;
4629
4630Pass *polly::createScopInfoWrapperPassPass() {
4631 return new ScopInfoWrapperPass();
4632}
4633
4634INITIALIZE_PASS_BEGIN(
4635 ScopInfoWrapperPass, "polly-function-scops",
4636 "Polly - Create polyhedral description of all Scops of a function", false,
4637 false);
4638INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004639INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4640INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4641INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4642INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4643INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4644INITIALIZE_PASS_END(
4645 ScopInfoWrapperPass, "polly-function-scops",
4646 "Polly - Create polyhedral description of all Scops of a function", false,
4647 false)