blob: f890c1eb74071941cc703cfc7ff1432d580daff4 [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
Michael Krusebc150122016-05-02 12:25:18 +000080static int const MaxDisjunctionsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +000081
Johannes Doerfert2f705842016-04-12 16:09:44 +000082static cl::opt<bool> PollyRemarksMinimal(
83 "polly-remarks-minimal",
84 cl::desc("Do not emit remarks about assumptions that are known"),
85 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
86
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000087// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000088// operations can overflow easily. Additive reductions and bit operations
89// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000090static cl::opt<bool> DisableMultiplicativeReductions(
91 "polly-disable-multiplicative-reductions",
92 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
93 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000094
Johannes Doerfert9143d672014-09-27 11:02:39 +000095static cl::opt<unsigned> RunTimeChecksMaxParameters(
96 "polly-rtc-max-parameters",
97 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
98 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
99
Tobias Grosser71500722015-03-28 15:11:14 +0000100static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
101 "polly-rtc-max-arrays-per-group",
102 cl::desc("The maximal number of arrays to compare in each alias group."),
103 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000104
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000105static cl::opt<std::string> UserContextStr(
106 "polly-context", cl::value_desc("isl parameter set"),
107 cl::desc("Provide additional constraints on the context parameters"),
108 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000109
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000110static cl::opt<bool> DetectReductions("polly-detect-reductions",
111 cl::desc("Detect and exploit reductions"),
112 cl::Hidden, cl::ZeroOrMore,
113 cl::init(true), cl::cat(PollyCategory));
114
Tobias Grosser2937b592016-04-29 11:43:20 +0000115static cl::opt<bool>
116 IslOnErrorAbort("polly-on-isl-error-abort",
117 cl::desc("Abort if an isl error is encountered"),
118 cl::init(true), cl::cat(PollyCategory));
119
Michael Kruse6ab44762016-10-04 17:33:39 +0000120static cl::opt<bool> UnprofitableScalarAccs(
121 "polly-unprofitable-scalar-accs",
122 cl::desc("Count statements with scalar accesses as not optimizable"),
123 cl::Hidden, cl::init(true), cl::cat(PollyCategory));
124
Michael Kruse7bf39442015-09-10 12:46:52 +0000125//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000126
Michael Kruse046dde42015-08-10 13:01:57 +0000127// Create a sequence of two schedules. Either argument may be null and is
128// interpreted as the empty schedule. Can also return null if both schedules are
129// empty.
130static __isl_give isl_schedule *
131combineInSequence(__isl_take isl_schedule *Prev,
132 __isl_take isl_schedule *Succ) {
133 if (!Prev)
134 return Succ;
135 if (!Succ)
136 return Prev;
137
138 return isl_schedule_sequence(Prev, Succ);
139}
140
Johannes Doerferte7044942015-02-24 11:58:30 +0000141static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
142 const ConstantRange &Range,
143 int dim,
144 enum isl_dim_type type) {
145 isl_val *V;
146 isl_ctx *ctx = isl_set_get_ctx(S);
147
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000148 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
149 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000150 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000151 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
152
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000153 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000154 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000155 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000156 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000157 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
158
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000159 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000160 return isl_set_union(SLB, SUB);
161 else
162 return isl_set_intersect(SLB, SUB);
163}
164
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000165static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
166 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
167 if (!BasePtrLI)
168 return nullptr;
169
Johannes Doerfert952b5302016-05-23 12:40:48 +0000170 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000171 return nullptr;
172
173 ScalarEvolution &SE = *S->getSE();
174
175 auto *OriginBaseSCEV =
176 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
177 if (!OriginBaseSCEV)
178 return nullptr;
179
180 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
181 if (!OriginBaseSCEVUnknown)
182 return nullptr;
183
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000184 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000185 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000186}
187
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000188ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000189 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000190 const DataLayout &DL, Scop *S,
191 const char *BaseName)
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000192 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000193 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000194 BaseName ? BaseName
195 : getIslCompatibleName("MemRef_", BasePtr,
196 Kind == MemoryKind::PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000197 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000198
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000199 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000200
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000201 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000202 BasePtrOriginSAI = nullptr;
203 return;
204 }
205
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000206 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
207 if (BasePtrOriginSAI)
208 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000209}
210
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000211__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000212 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000213 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
214 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
215 return Space;
216}
217
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000218bool ScopArrayInfo::isReadOnly() {
219 isl_union_set *WriteSet = isl_union_map_range(S.getWrites());
220 isl_space *Space = getSpace();
221 WriteSet = isl_union_set_intersect(
222 WriteSet, isl_union_set_from_set(isl_set_universe(Space)));
223
224 bool IsReadOnly = isl_union_set_is_empty(WriteSet);
225 isl_union_set_free(WriteSet);
226
227 return IsReadOnly;
228}
229
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000230void ScopArrayInfo::updateElementType(Type *NewElementType) {
231 if (NewElementType == ElementType)
232 return;
233
Tobias Grosserd840fc72016-02-04 13:18:42 +0000234 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
235 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
236
Johannes Doerferta7920982016-02-25 14:08:48 +0000237 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000238 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000239
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000240 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
241 ElementType = NewElementType;
242 } else {
243 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
244 ElementType = IntegerType::get(ElementType->getContext(), GCD);
245 }
246}
247
Tobias Grosserbedef002016-12-02 08:10:56 +0000248bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
249 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000250 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
251 int ExtraDimsNew = NewSizes.size() - SharedDims;
252 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000253
Tobias Grosserbedef002016-12-02 08:10:56 +0000254 if (CheckConsistency) {
255 for (int i = 0; i < SharedDims; i++) {
256 auto *NewSize = NewSizes[i + ExtraDimsNew];
257 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
258 if (NewSize && KnownSize && NewSize != KnownSize)
259 return false;
260 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000261
Tobias Grosserbedef002016-12-02 08:10:56 +0000262 if (DimensionSizes.size() >= NewSizes.size())
263 return true;
264 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000265
266 DimensionSizes.clear();
267 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
268 NewSizes.end());
269 for (isl_pw_aff *Size : DimensionSizesPw)
270 isl_pw_aff_free(Size);
271 DimensionSizesPw.clear();
272 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000273 if (!Expr) {
274 DimensionSizesPw.push_back(nullptr);
275 continue;
276 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000277 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000278 DimensionSizesPw.push_back(Size);
279 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000280 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000281}
282
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000283ScopArrayInfo::~ScopArrayInfo() {
284 isl_id_free(Id);
285 for (isl_pw_aff *Size : DimensionSizesPw)
286 isl_pw_aff_free(Size);
287}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000288
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000289std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
290
291int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000292 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000293}
294
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000295__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
296 return isl_id_copy(Id);
297}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000298
299void ScopArrayInfo::dump() const { print(errs()); }
300
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000301void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000302 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000303 unsigned u = 0;
304 if (getNumberOfDimensions() > 0 && !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000305 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000306 u++;
307 }
308 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000309 OS << "[";
310
Tobias Grosser26253842015-11-10 14:24:21 +0000311 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000312 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000313 OS << " " << Size << " ";
314 isl_pw_aff_free(Size);
315 } else {
316 OS << *getDimensionSize(u);
317 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000318
319 OS << "]";
320 }
321
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000322 OS << ";";
323
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000324 if (BasePtrOriginSAI)
325 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
326
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000327 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000328}
329
330const ScopArrayInfo *
331ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
332 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
333 assert(Id && "Output dimension didn't have an ID");
334 return getFromId(Id);
335}
336
Michael Krused56b90a2016-09-01 09:03:27 +0000337const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000338 void *User = isl_id_get_user(Id);
339 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
340 isl_id_free(Id);
341 return SAI;
342}
343
Michael Kruse3b425ff2016-04-11 14:34:08 +0000344void MemoryAccess::wrapConstantDimensions() {
345 auto *SAI = getScopArrayInfo();
346 auto *ArraySpace = SAI->getSpace();
347 auto *Ctx = isl_space_get_ctx(ArraySpace);
348 unsigned DimsArray = SAI->getNumberOfDimensions();
349
350 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
351 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
352 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
353
354 // Begin with last dimension, to iteratively carry into higher dimensions.
355 for (int i = DimsArray - 1; i > 0; i--) {
356 auto *DimSize = SAI->getDimensionSize(i);
357 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
358
359 // This transformation is not applicable to dimensions with dynamic size.
360 if (!DimSizeCst)
361 continue;
362
363 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
364 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
365 isl_dim_set, i);
366 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
367 isl_dim_set, i - 1);
368
369 // Compute: index % size
370 // Modulo must apply in the divide of the previous iteration, if any.
371 auto *Modulo = isl_aff_copy(Var);
372 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
373 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
374
375 // Compute: floor(index / size)
376 auto *Divide = Var;
377 Divide = isl_aff_div(
378 Divide,
379 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
380 Divide = isl_aff_floor(Divide);
381 Divide = isl_aff_add(Divide, PrevVar);
382 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
383
384 // Apply Modulo and Divide.
385 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
386 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
387 }
388
389 // Apply all modulo/divides on the accesses.
390 AccessRelation =
391 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
392 AccessRelation = isl_map_detect_equalities(AccessRelation);
393 isl_local_space_free(LArraySpace);
394}
395
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000396void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000397 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000398 auto *ArraySpace = SAI->getSpace();
399 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000400 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000401
402 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
403 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
404 auto DimsMissing = DimsArray - DimsAccess;
405
Michael Kruse375cb5f2016-02-24 22:08:24 +0000406 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000407 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000408 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000409 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000410
Johannes Doerferta90943d2016-02-21 16:37:25 +0000411 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000412 isl_set_universe(AccessSpace),
413 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000414
415 for (unsigned i = 0; i < DimsMissing; i++)
416 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
417
418 for (unsigned i = DimsMissing; i < DimsArray; i++)
419 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
420
421 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000422
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000423 // For the non delinearized arrays, divide the access function of the last
424 // subscript by the size of the elements in the array.
425 //
426 // A stride one array access in C expressed as A[i] is expressed in
427 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
428 // two subsequent values of 'i' index two values that are stored next to
429 // each other in memory. By this division we make this characteristic
430 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000431 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000432 // that divides the offsets of all accesses to this base pointer.
433 if (DimsAccess == 1) {
434 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
435 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
436 }
437
Michael Kruse3b425ff2016-04-11 14:34:08 +0000438 // We currently do this only if we added at least one dimension, which means
439 // some dimension's indices have not been specified, an indicator that some
440 // index values have been added together.
441 // TODO: Investigate general usefulness; Effect on unit tests is to make index
442 // expressions more complicated.
443 if (DimsMissing)
444 wrapConstantDimensions();
445
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000446 if (!isAffine())
447 computeBoundsOnAccessRelation(ArrayElemSize);
448
Tobias Grosserd840fc72016-02-04 13:18:42 +0000449 // Introduce multi-element accesses in case the type loaded by this memory
450 // access is larger than the canonical element type of the array.
451 //
452 // An access ((float *)A)[i] to an array char *A is modeled as
453 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000454 if (ElemBytes > ArrayElemSize) {
455 assert(ElemBytes % ArrayElemSize == 0 &&
456 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000457 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000458 isl_set_universe(isl_space_copy(ArraySpace)),
459 isl_set_universe(isl_space_copy(ArraySpace)));
460 for (unsigned i = 0; i < DimsArray - 1; i++)
461 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
462
Tobias Grosserd840fc72016-02-04 13:18:42 +0000463 isl_constraint *C;
464 isl_local_space *LS;
465
466 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000467 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
468
469 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
470 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000471 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000472 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
473 Map = isl_map_add_constraint(Map, C);
474
475 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000476 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000477 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
478 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
479 Map = isl_map_add_constraint(Map, C);
480 AccessRelation = isl_map_apply_range(AccessRelation, Map);
481 }
482
483 isl_space_free(ArraySpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000484}
485
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000486const std::string
487MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
488 switch (RT) {
489 case MemoryAccess::RT_NONE:
490 llvm_unreachable("Requested a reduction operator string for a memory "
491 "access which isn't a reduction");
492 case MemoryAccess::RT_ADD:
493 return "+";
494 case MemoryAccess::RT_MUL:
495 return "*";
496 case MemoryAccess::RT_BOR:
497 return "|";
498 case MemoryAccess::RT_BXOR:
499 return "^";
500 case MemoryAccess::RT_BAND:
501 return "&";
502 }
503 llvm_unreachable("Unknown reduction type");
504 return "";
505}
506
Tobias Grosserc80d6972016-09-02 06:33:33 +0000507/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000508static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
509 const Instruction *Load) {
510 if (!BinOp)
511 return MemoryAccess::RT_NONE;
512 switch (BinOp->getOpcode()) {
513 case Instruction::FAdd:
514 if (!BinOp->hasUnsafeAlgebra())
515 return MemoryAccess::RT_NONE;
516 // Fall through
517 case Instruction::Add:
518 return MemoryAccess::RT_ADD;
519 case Instruction::Or:
520 return MemoryAccess::RT_BOR;
521 case Instruction::Xor:
522 return MemoryAccess::RT_BXOR;
523 case Instruction::And:
524 return MemoryAccess::RT_BAND;
525 case Instruction::FMul:
526 if (!BinOp->hasUnsafeAlgebra())
527 return MemoryAccess::RT_NONE;
528 // Fall through
529 case Instruction::Mul:
530 if (DisableMultiplicativeReductions)
531 return MemoryAccess::RT_NONE;
532 return MemoryAccess::RT_MUL;
533 default:
534 return MemoryAccess::RT_NONE;
535 }
536}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000537
Tobias Grosser75805372011-04-29 06:27:02 +0000538MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000539 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000540 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000541 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000542 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000543}
544
Michael Kruse2fa35192016-09-01 19:53:31 +0000545const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000546 isl_id *ArrayId = getArrayId();
547 void *User = isl_id_get_user(ArrayId);
548 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
549 isl_id_free(ArrayId);
550 return SAI;
551}
552
Michael Kruse2fa35192016-09-01 19:53:31 +0000553const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
554 isl_id *ArrayId = getLatestArrayId();
555 void *User = isl_id_get_user(ArrayId);
556 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
557 isl_id_free(ArrayId);
558 return SAI;
559}
560
561__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000562 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
563}
564
Michael Kruse2fa35192016-09-01 19:53:31 +0000565__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
566 if (!hasNewAccessRelation())
567 return getOriginalArrayId();
568 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
569}
570
Tobias Grosserd840fc72016-02-04 13:18:42 +0000571__isl_give isl_map *MemoryAccess::getAddressFunction() const {
572 return isl_map_lexmin(getAccessRelation());
573}
574
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000575__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
576 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000577 isl_map *Schedule, *ScheduledAccRel;
578 isl_union_set *UDomain;
579
580 UDomain = isl_union_set_from_set(getStatement()->getDomain());
581 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
582 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000583 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000584 return isl_pw_multi_aff_from_map(ScheduledAccRel);
585}
586
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000587__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000588 return isl_map_copy(AccessRelation);
589}
590
Johannes Doerferta99130f2014-10-13 12:58:03 +0000591std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000592 return stringFromIslObj(AccessRelation);
593}
594
Johannes Doerferta99130f2014-10-13 12:58:03 +0000595__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000596 return isl_map_get_space(AccessRelation);
597}
598
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000599__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000600 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000601}
602
Tobias Grosser6f730082015-09-05 07:46:47 +0000603std::string MemoryAccess::getNewAccessRelationStr() const {
604 return stringFromIslObj(NewAccessRelation);
605}
606
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000607__isl_give isl_basic_map *
608MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000609 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000610 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000611
Tobias Grosser084d8f72012-05-29 09:29:44 +0000612 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000613 isl_basic_set_universe(Statement->getDomainSpace()),
614 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000615}
616
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000617// Formalize no out-of-bound access assumption
618//
619// When delinearizing array accesses we optimistically assume that the
620// delinearized accesses do not access out of bound locations (the subscript
621// expression of each array evaluates for each statement instance that is
622// executed to a value that is larger than zero and strictly smaller than the
623// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000624// dimension for which we do not need to assume any upper bound. At this point
625// we formalize this assumption to ensure that at code generation time the
626// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000627//
628// To find the set of constraints necessary to avoid out of bound accesses, we
629// first build the set of data locations that are not within array bounds. We
630// then apply the reverse access relation to obtain the set of iterations that
631// may contain invalid accesses and reduce this set of iterations to the ones
632// that are actually executed by intersecting them with the domain of the
633// statement. If we now project out all loop dimensions, we obtain a set of
634// parameters that may cause statement instances to be executed that may
635// possibly yield out of bound memory accesses. The complement of these
636// constraints is the set of constraints that needs to be assumed to ensure such
637// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000638void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000639 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000640 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000641 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000642 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000643 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
644 isl_pw_aff *Var =
645 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
646 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
647
648 isl_set *DimOutside;
649
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000650 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000651 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000652 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
653 isl_space_dim(Space, isl_dim_set));
654 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
655 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000656
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000657 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000658
659 Outside = isl_set_union(Outside, DimOutside);
660 }
661
662 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
663 Outside = isl_set_intersect(Outside, Statement->getDomain());
664 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000665
666 // Remove divs to avoid the construction of overly complicated assumptions.
667 // Doing so increases the set of parameter combinations that are assumed to
668 // not appear. This is always save, but may make the resulting run-time check
669 // bail out more often than strictly necessary.
670 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000671 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000672 const auto &Loc = getAccessInstruction()
673 ? getAccessInstruction()->getDebugLoc()
674 : DebugLoc();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000675 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
676 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000677 isl_space_free(Space);
678}
679
Johannes Doerfertcea61932016-02-21 19:13:19 +0000680void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000681 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000682 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000683
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000684 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000685 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000686
687 isl_map *LengthMap;
688 if (Subscripts[1] == nullptr) {
689 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
690 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000691 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000692 LengthMap = isl_map_from_pw_aff(LengthPWA);
693 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
694 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
695 }
696 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
697 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000698 SubscriptMap =
699 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000700 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
701 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
702 getStatement()->getDomainId());
703}
704
Johannes Doerferte7044942015-02-24 11:58:30 +0000705void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
706 ScalarEvolution *SE = Statement->getParent()->getSE();
707
Johannes Doerfertcea61932016-02-21 19:13:19 +0000708 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000709 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000710 return;
711
712 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000713 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
714 return;
715
716 auto *PtrSCEV = SE->getSCEV(Ptr);
717 if (isa<SCEVCouldNotCompute>(PtrSCEV))
718 return;
719
720 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
721 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
722 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
723
724 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
725 if (Range.isFullSet())
726 return;
727
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000728 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000729 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000730 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000731 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000732 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000733
734 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000735 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000736
737 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
738 AccessRange =
739 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
740 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
741}
742
Tobias Grosser491b7992016-12-02 05:21:22 +0000743void MemoryAccess::foldAccessRelation() {
744 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
745 return;
746
Michael Krusee2bccbb2015-09-18 19:59:43 +0000747 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000748
749 for (int i = Size - 2; i >= 0; --i) {
750 isl_space *Space;
751 isl_map *MapOne, *MapTwo;
Roman Gareevf5aff702016-09-12 17:08:31 +0000752 isl_pw_aff *DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000753
754 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
755 isl_pw_aff_free(DimSize);
756 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
757
758 Space = isl_map_get_space(AccessRelation);
759 Space = isl_space_map_from_set(isl_space_range(Space));
760 Space = isl_space_align_params(Space, SpaceSize);
761
762 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
763 isl_id_free(ParamId);
764
765 MapOne = isl_map_universe(isl_space_copy(Space));
766 for (int j = 0; j < Size; ++j)
767 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
768 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
769
770 MapTwo = isl_map_universe(isl_space_copy(Space));
771 for (int j = 0; j < Size; ++j)
772 if (j < i || j > i + 1)
773 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
774
775 isl_local_space *LS = isl_local_space_from_space(Space);
776 isl_constraint *C;
777 C = isl_equality_alloc(isl_local_space_copy(LS));
778 C = isl_constraint_set_constant_si(C, -1);
779 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
780 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
781 MapTwo = isl_map_add_constraint(MapTwo, C);
782 C = isl_equality_alloc(LS);
783 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
784 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
785 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
786 MapTwo = isl_map_add_constraint(MapTwo, C);
787 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
788
789 MapOne = isl_map_union(MapOne, MapTwo);
790 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
791 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000792
793 isl_id *BaseAddrId = getScopArrayInfo()->getBasePtrId();
794 auto Space = Statement->getDomainSpace();
795 AccessRelation = isl_map_set_tuple_id(
796 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
797 AccessRelation =
798 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
799 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
800 isl_space_free(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000801}
802
Tobias Grosserc80d6972016-09-02 06:33:33 +0000803/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000804static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000805 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000806 if (Size == 1)
807 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000808
809 // Only one factor needs to be divisible.
810 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
811 for (auto *FactorExpr : MulExpr->operands())
812 if (isDivisible(FactorExpr, Size, SE))
813 return true;
814 return false;
815 }
816
817 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
818 // to be divisble.
819 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
820 for (auto *OpExpr : NAryExpr->operands())
821 if (!isDivisible(OpExpr, Size, SE))
822 return false;
823 return true;
824 }
825
826 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
827 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
828 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
829 return MulSCEV == Expr;
830}
831
Michael Krusee2bccbb2015-09-18 19:59:43 +0000832void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
833 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000834
Johannes Doerfert85676e32016-04-23 14:32:34 +0000835 // Initialize the invalid domain which describes all iterations for which the
836 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000837 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
838 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
839 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000840
Michael Krusee2bccbb2015-09-18 19:59:43 +0000841 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000842 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000843
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000844 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
845 buildMemIntrinsicAccessRelation();
846 AccessRelation =
847 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
848 return;
849 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000850
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000851 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000852 // We overapproximate non-affine accesses with a possible access to the
853 // whole array. For read accesses it does not make a difference, if an
854 // access must or may happen. However, for write accesses it is important to
855 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000856 if (!AccessRelation)
857 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
858
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000859 AccessRelation =
860 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000861 return;
862 }
863
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000864 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000865 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000866
Michael Krusee2bccbb2015-09-18 19:59:43 +0000867 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000868 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000869 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000870 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000871 }
872
Tobias Grosser79baa212014-04-10 08:38:02 +0000873 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000874 AccessRelation = isl_map_set_tuple_id(
875 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000876 AccessRelation =
877 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
878
Tobias Grosseraa660a92015-03-30 00:07:50 +0000879 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000880 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000881}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000882
Michael Krusecac948e2015-10-02 13:53:07 +0000883MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000884 AccessType AccType, Value *BaseAddress,
885 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000886 ArrayRef<const SCEV *> Subscripts,
887 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000888 MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000889 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Johannes Doerfert85676e32016-04-23 14:32:34 +0000890 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
891 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()),
892 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000893 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000894 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000895 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000896 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000897
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000898 std::string IdName =
899 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000900 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
901}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000902
Roman Gareevb3224ad2016-09-14 06:26:09 +0000903MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
904 __isl_take isl_map *AccRel)
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000905 : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
906 Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
907 IsAffine(true), AccessRelation(nullptr), NewAccessRelation(AccRel) {
Roman Gareevb3224ad2016-09-14 06:26:09 +0000908 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
909 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
910 Sizes.push_back(nullptr);
911 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
912 Sizes.push_back(SAI->getDimensionSize(i));
913 ElementType = SAI->getElementType();
914 BaseAddr = SAI->getBasePtr();
915 BaseName = SAI->getName();
916 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
917 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
918
919 std::string IdName =
920 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
921 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
922}
923
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000924void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +0000925 auto *Ctx = Statement->getParent()->getContext();
926 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
927 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +0000928}
929
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000930const std::string MemoryAccess::getReductionOperatorStr() const {
931 return MemoryAccess::getReductionOperatorStr(getReductionType());
932}
933
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000934__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
935
Johannes Doerfertf6183392014-07-01 20:52:51 +0000936raw_ostream &polly::operator<<(raw_ostream &OS,
937 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000938 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000939 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000940 else
941 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000942 return OS;
943}
944
Tobias Grosser75805372011-04-29 06:27:02 +0000945void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000946 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000947 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000948 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000949 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000950 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000951 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000952 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000953 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000954 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000955 break;
956 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000957 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000958 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000959 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000960 if (hasNewAccessRelation())
961 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000962}
963
Tobias Grosser74394f02013-01-14 22:40:23 +0000964void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000965
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000966__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
967 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000968 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +0000969 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
970 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
971 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000972 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000973}
974
Tobias Grosser75805372011-04-29 06:27:02 +0000975// Create a map in the size of the provided set domain, that maps from the
976// one element of the provided set domain to another element of the provided
977// set domain.
978// The mapping is limited to all points that are equal in all but the last
979// dimension and for which the last dimension of the input is strict smaller
980// than the last dimension of the output.
981//
982// getEqualAndLarger(set[i0, i1, ..., iX]):
983//
984// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
985// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
986//
Tobias Grosser2a526fe2016-09-08 11:18:56 +0000987static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000988 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000989 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000990 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000991
992 // Set all but the last dimension to be equal for the input and output
993 //
994 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
995 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000996 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000997 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000998
999 // Set the last dimension of the input to be strict smaller than the
1000 // last dimension of the output.
1001 //
1002 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001003 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1004 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001005 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001006}
1007
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001008__isl_give isl_set *
1009MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001010 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +00001011 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +00001012 isl_space *Space = isl_space_range(isl_map_get_space(S));
1013 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001014
Sebastian Popa00a0292012-12-18 07:46:06 +00001015 S = isl_map_reverse(S);
1016 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001017
Sebastian Popa00a0292012-12-18 07:46:06 +00001018 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1019 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1020 NextScatt = isl_map_apply_domain(NextScatt, S);
1021 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001022
Sebastian Popa00a0292012-12-18 07:46:06 +00001023 isl_set *Deltas = isl_map_deltas(NextScatt);
1024 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001025}
1026
Sebastian Popa00a0292012-12-18 07:46:06 +00001027bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001028 int StrideWidth) const {
1029 isl_set *Stride, *StrideX;
1030 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001031
Sebastian Popa00a0292012-12-18 07:46:06 +00001032 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001033 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001034 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1035 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1036 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1037 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001038 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001039
Tobias Grosser28dd4862012-01-24 16:42:16 +00001040 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001041 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001042
Tobias Grosser28dd4862012-01-24 16:42:16 +00001043 return IsStrideX;
1044}
1045
Michael Krused56b90a2016-09-01 09:03:27 +00001046bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001047 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001048}
1049
Michael Krused56b90a2016-09-01 09:03:27 +00001050bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001051 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001052}
1053
Tobias Grosserbedef002016-12-02 08:10:56 +00001054void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
1055 isl_map_free(AccessRelation);
1056 AccessRelation = NewAccess;
1057}
1058
Michael Krused56b90a2016-09-01 09:03:27 +00001059void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001060 assert(NewAccess);
1061
1062#ifndef NDEBUG
1063 // Check domain space compatibility.
1064 auto *NewSpace = isl_map_get_space(NewAccess);
1065 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1066 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1067 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1068 isl_space_free(NewDomainSpace);
1069 isl_space_free(OriginalDomainSpace);
1070
1071 // Check whether there is an access for every statement instance.
1072 auto *StmtDomain = getStatement()->getDomain();
1073 StmtDomain = isl_set_intersect_params(
1074 StmtDomain, getStatement()->getParent()->getContext());
1075 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1076 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1077 "Partial accesses not supported");
1078 isl_set_free(NewDomain);
1079 isl_set_free(StmtDomain);
1080
Michael Kruse772ce722016-09-01 19:16:58 +00001081 auto *NewAccessSpace = isl_space_range(NewSpace);
1082 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1083 "Must specify the array that is accessed");
1084 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1085 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1086 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001087
1088 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1089 InvariantEquivClassTy *EqClass =
1090 getStatement()->getParent()->lookupInvariantEquivClass(
1091 SAI->getBasePtr());
1092 assert(EqClass &&
1093 "Access functions to indirect arrays must have an invariant and "
1094 "hoisted base pointer");
1095 }
1096
1097 // Check whether access dimensions correspond to number of dimensions of the
1098 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001099 auto Dims = SAI->getNumberOfDimensions();
1100 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1101 "Access dims must match array dims");
1102 isl_space_free(NewAccessSpace);
1103 isl_id_free(NewArrayId);
1104#endif
1105
Tobias Grosser166c4222015-09-05 07:46:40 +00001106 isl_map_free(NewAccessRelation);
1107 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001108}
Tobias Grosser75805372011-04-29 06:27:02 +00001109
1110//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001111
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001112__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001113 isl_set *Domain = getDomain();
1114 if (isl_set_is_empty(Domain)) {
1115 isl_set_free(Domain);
1116 return isl_map_from_aff(
1117 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1118 }
1119 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001120 if (!Schedule) {
1121 isl_set_free(Domain);
1122 return nullptr;
1123 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001124 Schedule = isl_union_map_intersect_domain(
1125 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1126 if (isl_union_map_is_empty(Schedule)) {
1127 isl_set_free(Domain);
1128 isl_union_map_free(Schedule);
1129 return isl_map_from_aff(
1130 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1131 }
1132 auto *M = isl_map_from_union_map(Schedule);
1133 M = isl_map_coalesce(M);
1134 M = isl_map_gist_domain(M, Domain);
1135 M = isl_map_coalesce(M);
1136 return M;
1137}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001138
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001139__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1140 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001141 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1142 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001143}
1144
Tobias Grosser37eb4222014-02-20 21:43:54 +00001145void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1146 assert(isl_set_is_subset(NewDomain, Domain) &&
1147 "New domain is not a subset of old domain!");
1148 isl_set_free(Domain);
1149 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001150}
1151
Michael Krusecac948e2015-10-02 13:53:07 +00001152void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001153 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001154 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001155 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001156
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001157 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001158 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001159 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001160 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001161 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001162 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001163 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001164 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001165 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001166
Johannes Doerfertadeab372016-02-07 13:57:32 +00001167 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1168 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001169 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001170 }
1171}
1172
Michael Krusecac948e2015-10-02 13:53:07 +00001173void ScopStmt::addAccess(MemoryAccess *Access) {
1174 Instruction *AccessInst = Access->getAccessInstruction();
1175
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001176 if (Access->isArrayKind()) {
1177 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1178 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001179 } else if (Access->isValueKind() && Access->isWrite()) {
1180 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001181 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001182 assert(!ValueWrites.lookup(AccessVal));
1183
1184 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001185 } else if (Access->isValueKind() && Access->isRead()) {
1186 Value *AccessVal = Access->getAccessValue();
1187 assert(!ValueReads.lookup(AccessVal));
1188
1189 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001190 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1191 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1192 assert(!PHIWrites.lookup(PHI));
1193
1194 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001195 }
1196
1197 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001198}
1199
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001200void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001201 for (MemoryAccess *MA : *this)
1202 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001203
Johannes Doerferta60ad842016-05-10 12:18:22 +00001204 auto *Ctx = Parent.getContext();
1205 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1206 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001207}
1208
Tobias Grosserc80d6972016-09-02 06:33:33 +00001209/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001210static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1211 void *User) {
1212 isl_set **BoundedParts = static_cast<isl_set **>(User);
1213 if (isl_basic_set_is_bounded(BSet))
1214 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1215 else
1216 isl_basic_set_free(BSet);
1217 return isl_stat_ok;
1218}
1219
Tobias Grosserc80d6972016-09-02 06:33:33 +00001220/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001221static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1222 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1223 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1224 isl_set_free(S);
1225 return BoundedParts;
1226}
1227
Tobias Grosserc80d6972016-09-02 06:33:33 +00001228/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001229///
1230/// @returns A separation of @p S into first an unbounded then a bounded subset,
1231/// both with regards to the dimension @p Dim.
1232static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1233partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1234
1235 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001236 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001237
1238 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001239 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001240
1241 // Remove dimensions that are greater than Dim as they are not interesting.
1242 assert(NumDimsS >= Dim + 1);
1243 OnlyDimS =
1244 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1245
1246 // Create artificial parametric upper bounds for dimensions smaller than Dim
1247 // as we are not interested in them.
1248 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1249 for (unsigned u = 0; u < Dim; u++) {
1250 isl_constraint *C = isl_inequality_alloc(
1251 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1252 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1253 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1254 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1255 }
1256
1257 // Collect all bounded parts of OnlyDimS.
1258 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1259
1260 // Create the dimensions greater than Dim again.
1261 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1262 NumDimsS - Dim - 1);
1263
1264 // Remove the artificial upper bound parameters again.
1265 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1266
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001267 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001268 return std::make_pair(UnboundedParts, BoundedParts);
1269}
1270
Tobias Grosserc80d6972016-09-02 06:33:33 +00001271/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001272static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1273 __isl_take isl_set *To) {
1274 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1275 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1276 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1277 }
1278 return To;
1279}
1280
Tobias Grosserc80d6972016-09-02 06:33:33 +00001281/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001282static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001283 __isl_take isl_pw_aff *L,
1284 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001285 switch (Pred) {
1286 case ICmpInst::ICMP_EQ:
1287 return isl_pw_aff_eq_set(L, R);
1288 case ICmpInst::ICMP_NE:
1289 return isl_pw_aff_ne_set(L, R);
1290 case ICmpInst::ICMP_SLT:
1291 return isl_pw_aff_lt_set(L, R);
1292 case ICmpInst::ICMP_SLE:
1293 return isl_pw_aff_le_set(L, R);
1294 case ICmpInst::ICMP_SGT:
1295 return isl_pw_aff_gt_set(L, R);
1296 case ICmpInst::ICMP_SGE:
1297 return isl_pw_aff_ge_set(L, R);
1298 case ICmpInst::ICMP_ULT:
1299 return isl_pw_aff_lt_set(L, R);
1300 case ICmpInst::ICMP_UGT:
1301 return isl_pw_aff_gt_set(L, R);
1302 case ICmpInst::ICMP_ULE:
1303 return isl_pw_aff_le_set(L, R);
1304 case ICmpInst::ICMP_UGE:
1305 return isl_pw_aff_ge_set(L, R);
1306 default:
1307 llvm_unreachable("Non integer predicate not supported");
1308 }
1309}
1310
Tobias Grosserc80d6972016-09-02 06:33:33 +00001311/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001312///
1313/// Helper function that will make sure the dimensions of the result have the
1314/// same isl_id's as the @p Domain.
1315static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1316 __isl_take isl_pw_aff *L,
1317 __isl_take isl_pw_aff *R,
1318 __isl_keep isl_set *Domain) {
1319 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1320 return setDimensionIds(Domain, ConsequenceCondSet);
1321}
1322
Tobias Grosserc80d6972016-09-02 06:33:33 +00001323/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001324///
1325/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001326/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1327/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001328static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001329buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1330 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001331 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1332
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001333 Value *Condition = getConditionFromTerminator(SI);
1334 assert(Condition && "No condition for switch");
1335
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001336 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001337 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001338 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001339 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001340
1341 unsigned NumSuccessors = SI->getNumSuccessors();
1342 ConditionSets.resize(NumSuccessors);
1343 for (auto &Case : SI->cases()) {
1344 unsigned Idx = Case.getSuccessorIndex();
1345 ConstantInt *CaseValue = Case.getCaseValue();
1346
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001347 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001348 isl_set *CaseConditionSet =
1349 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1350 ConditionSets[Idx] = isl_set_coalesce(
1351 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1352 }
1353
1354 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1355 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1356 for (unsigned u = 2; u < NumSuccessors; u++)
1357 ConditionSetUnion =
1358 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1359 ConditionSets[0] = setDimensionIds(
1360 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1361
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001362 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001363
1364 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001365}
1366
Tobias Grosserc80d6972016-09-02 06:33:33 +00001367/// Build the conditions sets for the branch condition @p Condition in
1368/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001369///
1370/// This will fill @p ConditionSets with the conditions under which control
1371/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001372/// have as many elements as @p TI has successors. If @p TI is nullptr the
1373/// context under which @p Condition is true/false will be returned as the
1374/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001375static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001376buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1377 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001378 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1379
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001380 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001381 isl_set *ConsequenceCondSet = nullptr;
1382 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1383 if (CCond->isZero())
1384 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1385 else
1386 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1387 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1388 auto Opcode = BinOp->getOpcode();
1389 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1390
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001391 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1392 ConditionSets) &&
1393 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1394 ConditionSets);
1395 if (!Valid) {
1396 while (!ConditionSets.empty())
1397 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001398 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001399 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001400
1401 isl_set_free(ConditionSets.pop_back_val());
1402 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1403 isl_set_free(ConditionSets.pop_back_val());
1404 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1405
1406 if (Opcode == Instruction::And)
1407 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1408 else
1409 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1410 } else {
1411 auto *ICond = dyn_cast<ICmpInst>(Condition);
1412 assert(ICond &&
1413 "Condition of exiting branch was neither constant nor ICmp!");
1414
1415 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001416 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001417 // For unsigned comparisons we assumed the signed bit of neither operand
1418 // to be set. The comparison is equal to a signed comparison under this
1419 // assumption.
1420 bool NonNeg = ICond->isUnsigned();
1421 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1422 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001423 ConsequenceCondSet =
1424 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1425 }
1426
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001427 // If no terminator was given we are only looking for parameter constraints
1428 // under which @p Condition is true/false.
1429 if (!TI)
1430 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001431 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001432 ConsequenceCondSet = isl_set_coalesce(
1433 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001434
Johannes Doerfertb2885792016-04-26 09:20:41 +00001435 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001436 bool TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001437 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001438
Michael Krusef7a4a942016-05-02 12:25:36 +00001439 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001440 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1441 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001442 TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001443 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001444 }
1445
Michael Krusef7a4a942016-05-02 12:25:36 +00001446 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001447 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001448 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001449 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001450 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001451 }
1452
1453 ConditionSets.push_back(ConsequenceCondSet);
1454 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001455
1456 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001457}
1458
Tobias Grosserc80d6972016-09-02 06:33:33 +00001459/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001460///
1461/// This will fill @p ConditionSets with the conditions under which control
1462/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1463/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001464static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001465buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001466 __isl_keep isl_set *Domain,
1467 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1468
1469 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001470 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001471
1472 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1473
1474 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001475 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001476 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001477 }
1478
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001479 Value *Condition = getConditionFromTerminator(TI);
1480 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001481
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001482 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001483}
1484
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001485void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001486 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001487
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001488 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001489 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001490}
1491
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001492void ScopStmt::collectSurroundingLoops() {
1493 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1494 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1495 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1496 isl_id_free(DimId);
1497 }
1498}
1499
Michael Kruse9d080092015-09-11 21:41:48 +00001500ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerferta3519512016-04-23 13:02:23 +00001501 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1502 R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001503
Tobias Grosser16c44032015-07-09 07:31:45 +00001504 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001505}
1506
Michael Kruse9d080092015-09-11 21:41:48 +00001507ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerferta3519512016-04-23 13:02:23 +00001508 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1509 R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001510
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001511 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001512}
1513
Roman Gareevb3224ad2016-09-14 06:26:09 +00001514ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1515 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1516 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1517 R(nullptr), Build(nullptr) {
1518 BaseName = getIslCompatibleName("CopyStmt_", "",
1519 std::to_string(parent.getCopyStmtsNum()));
1520 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1521 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1522 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1523 auto *Access =
1524 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1525 parent.addAccessFunction(Access);
1526 addAccess(Access);
1527 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1528 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1529 parent.addAccessFunction(Access);
1530 addAccess(Access);
1531}
1532
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001533void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001534 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001535
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001536 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001537 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001538 buildAccessRelations();
1539
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001540 if (DetectReductions)
1541 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001542}
1543
Tobias Grosserc80d6972016-09-02 06:33:33 +00001544/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001545///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001546/// Check if the stored value for @p StoreMA is a binary operator with one or
1547/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001548/// used only once (by @p StoreMA) and its load operands are also used only
1549/// once, we have found a possible reduction chain. It starts at an operand
1550/// load and includes the binary operator and @p StoreMA.
1551///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001552/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001553/// escape this block or into any other store except @p StoreMA.
1554void ScopStmt::collectCandiateReductionLoads(
1555 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1556 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1557 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001558 return;
1559
1560 // Skip if there is not one binary operator between the load and the store
1561 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001562 if (!BinOp)
1563 return;
1564
1565 // Skip if the binary operators has multiple uses
1566 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001567 return;
1568
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001569 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001570 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1571 return;
1572
Johannes Doerfert9890a052014-07-01 00:32:29 +00001573 // Skip if the binary operator is outside the current SCoP
1574 if (BinOp->getParent() != Store->getParent())
1575 return;
1576
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001577 // Skip if it is a multiplicative reduction and we disabled them
1578 if (DisableMultiplicativeReductions &&
1579 (BinOp->getOpcode() == Instruction::Mul ||
1580 BinOp->getOpcode() == Instruction::FMul))
1581 return;
1582
Johannes Doerferte58a0122014-06-27 20:31:28 +00001583 // Check the binary operator operands for a candidate load
1584 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1585 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1586 if (!PossibleLoad0 && !PossibleLoad1)
1587 return;
1588
1589 // A load is only a candidate if it cannot escape (thus has only this use)
1590 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001591 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001592 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001593 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001594 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001595 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001596}
1597
Tobias Grosserc80d6972016-09-02 06:33:33 +00001598/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001599///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001600/// Iterate over all store memory accesses and check for valid binary reduction
1601/// like chains. For all candidates we check if they have the same base address
1602/// and there are no other accesses which overlap with them. The base address
1603/// check rules out impossible reductions candidates early. The overlap check,
1604/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001605/// guarantees that none of the intermediate results will escape during
1606/// execution of the loop nest. We basically check here that no other memory
1607/// access can access the same memory as the potential reduction.
1608void ScopStmt::checkForReductions() {
1609 SmallVector<MemoryAccess *, 2> Loads;
1610 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1611
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001612 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001613 // stores and collecting possible reduction loads.
1614 for (MemoryAccess *StoreMA : MemAccs) {
1615 if (StoreMA->isRead())
1616 continue;
1617
1618 Loads.clear();
1619 collectCandiateReductionLoads(StoreMA, Loads);
1620 for (MemoryAccess *LoadMA : Loads)
1621 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1622 }
1623
1624 // Then check each possible candidate pair.
1625 for (const auto &CandidatePair : Candidates) {
1626 bool Valid = true;
1627 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1628 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1629
1630 // Skip those with obviously unequal base addresses.
1631 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1632 isl_map_free(LoadAccs);
1633 isl_map_free(StoreAccs);
1634 continue;
1635 }
1636
1637 // And check if the remaining for overlap with other memory accesses.
1638 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1639 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1640 isl_set *AllAccs = isl_map_range(AllAccsRel);
1641
1642 for (MemoryAccess *MA : MemAccs) {
1643 if (MA == CandidatePair.first || MA == CandidatePair.second)
1644 continue;
1645
1646 isl_map *AccRel =
1647 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1648 isl_set *Accs = isl_map_range(AccRel);
1649
Tobias Grosser55a7af72016-09-08 14:08:07 +00001650 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001651 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1652 Valid = Valid && isl_set_is_empty(OverlapAccs);
1653 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001654 } else {
1655 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001656 }
1657 }
1658
1659 isl_set_free(AllAccs);
1660 if (!Valid)
1661 continue;
1662
Johannes Doerfertf6183392014-07-01 20:52:51 +00001663 const LoadInst *Load =
1664 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1665 MemoryAccess::ReductionType RT =
1666 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1667
Johannes Doerferte58a0122014-06-27 20:31:28 +00001668 // If no overlapping access was found we mark the load and store as
1669 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001670 CandidatePair.first->markAsReductionLike(RT);
1671 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001672 }
Tobias Grosser75805372011-04-29 06:27:02 +00001673}
1674
Tobias Grosser74394f02013-01-14 22:40:23 +00001675std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001676
Tobias Grosser54839312015-04-21 11:37:25 +00001677std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001678 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001679 if (!S)
1680 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001681 auto Str = stringFromIslObj(S);
1682 isl_map_free(S);
1683 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001684}
1685
Johannes Doerferta3519512016-04-23 13:02:23 +00001686void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1687 isl_set_free(InvalidDomain);
1688 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001689}
1690
Michael Kruse375cb5f2016-02-24 22:08:24 +00001691BasicBlock *ScopStmt::getEntryBlock() const {
1692 if (isBlockStmt())
1693 return getBasicBlock();
1694 return getRegion()->getEntry();
1695}
1696
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001697unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001698
Tobias Grosser75805372011-04-29 06:27:02 +00001699const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1700
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001701Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001702 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001703}
1704
Tobias Grosser74394f02013-01-14 22:40:23 +00001705isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001706
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001707__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001708
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001709__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001710 return isl_set_get_space(Domain);
1711}
1712
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001713__isl_give isl_id *ScopStmt::getDomainId() const {
1714 return isl_set_get_tuple_id(Domain);
1715}
Tobias Grossercd95b772012-08-30 11:49:38 +00001716
Johannes Doerfert7c013572016-04-12 09:57:34 +00001717ScopStmt::~ScopStmt() {
1718 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001719 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001720}
Tobias Grosser75805372011-04-29 06:27:02 +00001721
1722void ScopStmt::print(raw_ostream &OS) const {
1723 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001724 OS.indent(12) << "Domain :=\n";
1725
1726 if (Domain) {
1727 OS.indent(16) << getDomainStr() << ";\n";
1728 } else
1729 OS.indent(16) << "n/a\n";
1730
Tobias Grosser54839312015-04-21 11:37:25 +00001731 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001732
1733 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001734 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001735 } else
1736 OS.indent(16) << "n/a\n";
1737
Tobias Grosser083d3d32014-06-28 08:59:45 +00001738 for (MemoryAccess *Access : MemAccs)
1739 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001740}
1741
1742void ScopStmt::dump() const { print(dbgs()); }
1743
Michael Kruse10071822016-05-23 14:45:58 +00001744void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001745 // Remove the memory accesses from this statement together with all scalar
1746 // accesses that were caused by it. MemoryKind::Value READs have no access
1747 // instruction, hence would not be removed by this function. However, it is
1748 // only used for invariant LoadInst accesses, its arguments are always affine,
1749 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1750 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001751 auto Predicate = [&](MemoryAccess *Acc) {
1752 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1753 };
1754 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1755 MemAccs.end());
1756 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001757}
1758
Tobias Grosser75805372011-04-29 06:27:02 +00001759//===----------------------------------------------------------------------===//
1760/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001761
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001762void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001763 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1764 isl_set_free(Context);
1765 Context = NewContext;
1766}
1767
Tobias Grosserc80d6972016-09-02 06:33:33 +00001768/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001769struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001770 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001771 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001772
1773public:
1774 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001775 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001776
1777 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1778 ValueToValueMap &VMap) {
1779 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1780 return SSPR.visit(E);
1781 }
1782
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001783 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1784 auto *Start = visit(E->getStart());
1785 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1786 visit(E->getStepRecurrence(SE)),
1787 E->getLoop(), SCEV::FlagAnyWrap);
1788 return SE.getAddExpr(Start, AddRec);
1789 }
1790
1791 const SCEV *visitUnknown(const SCEVUnknown *E) {
1792 if (auto *NewValue = VMap.lookup(E->getValue()))
1793 return SE.getUnknown(NewValue);
1794 return E;
1795 }
1796};
1797
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001798const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001799 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001800}
1801
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001802void Scop::createParameterId(const SCEV *Parameter) {
1803 assert(Parameters.count(Parameter));
1804 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001805
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001806 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001807
Tobias Grosser8f99c162011-11-15 11:38:55 +00001808 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1809 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001810
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001811 // If this parameter references a specific Value and this value has a name
1812 // we use this name as it is likely to be unique and more useful than just
1813 // a number.
1814 if (Val->hasName())
1815 ParameterName = Val->getName();
1816 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001817 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001818 if (LoadOrigin->hasName()) {
1819 ParameterName += "_loaded_from_";
1820 ParameterName +=
1821 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1822 }
1823 }
1824 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001825
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001826 ParameterName = getIslCompatibleName("", ParameterName, "");
1827
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001828 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1829 const_cast<void *>((const void *)Parameter));
1830 ParameterIds[Parameter] = Id;
1831}
1832
1833void Scop::addParams(const ParameterSetTy &NewParameters) {
1834 for (const SCEV *Parameter : NewParameters) {
1835 // Normalize the SCEV to get the representing element for an invariant load.
1836 Parameter = extractConstantFactor(Parameter, *SE).second;
1837 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1838
1839 if (Parameters.insert(Parameter))
1840 createParameterId(Parameter);
1841 }
1842}
1843
1844__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1845 // Normalize the SCEV to get the representing element for an invariant load.
1846 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1847 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001848}
Tobias Grosser75805372011-04-29 06:27:02 +00001849
Michael Krused56b90a2016-09-01 09:03:27 +00001850__isl_give isl_set *
1851Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001852 isl_set *DomainContext = isl_union_set_params(getDomains());
1853 return isl_set_intersect_params(C, DomainContext);
1854}
1855
Johannes Doerferte0b08072016-05-23 12:43:44 +00001856bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1857 return DT.dominates(BB, getEntry());
1858}
1859
Michael Kruse7037fde2016-12-15 09:25:14 +00001860void Scop::addUserAssumptions(DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001861 auto &F = getFunction();
Michael Kruse7037fde2016-12-15 09:25:14 +00001862
1863 // TODO: Walk the DominatorTree from getRegion().getExit() to its root in
1864 // order to not iterate over blocks we skip anyways.
1865 for (auto &BB : F) {
1866 bool InScop = contains(&BB);
1867 if (!InScop && !isDominatedBy(DT, &BB))
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001868 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001869
Michael Kruse7037fde2016-12-15 09:25:14 +00001870 for (auto &Assumption : BB) {
1871 auto *CI = dyn_cast_or_null<IntrinsicInst>(&Assumption);
1872 if (!CI || CI->getNumArgOperands() != 1 ||
1873 CI->getIntrinsicID() != Intrinsic::assume)
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001874 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001875
Michael Kruse7037fde2016-12-15 09:25:14 +00001876 auto *L = LI.getLoopFor(CI->getParent());
1877 auto *Val = CI->getArgOperand(0);
1878 ParameterSetTy DetectedParams;
1879 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
1880 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1881 CI->getDebugLoc(),
1882 "Non-affine user assumption ignored.");
1883 continue;
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001884 }
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001885
Michael Kruse7037fde2016-12-15 09:25:14 +00001886 // Collect all newly introduced parameters.
1887 ParameterSetTy NewParams;
1888 for (auto *Param : DetectedParams) {
1889 Param = extractConstantFactor(Param, *SE).second;
1890 Param = getRepresentingInvariantLoadSCEV(Param);
1891 if (Parameters.count(Param))
1892 continue;
1893 NewParams.insert(Param);
1894 }
1895
1896 SmallVector<isl_set *, 2> ConditionSets;
1897 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
1898 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
1899 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
1900 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
1901 isl_set_free(Dom);
1902
1903 if (!Valid)
1904 continue;
1905
1906 isl_set *AssumptionCtx = nullptr;
1907 if (InScop) {
1908 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
1909 isl_set_free(ConditionSets[0]);
1910 } else {
1911 AssumptionCtx = isl_set_complement(ConditionSets[1]);
1912 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
1913 }
1914
1915 // Project out newly introduced parameters as they are not otherwise
1916 // useful.
1917 if (!NewParams.empty()) {
1918 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
1919 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
1920 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
1921 isl_id_free(Id);
1922
1923 if (!NewParams.count(Param))
1924 continue;
1925
1926 AssumptionCtx =
1927 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
1928 }
1929 }
1930
1931 emitOptimizationRemarkAnalysis(
1932 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1933 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1934 Context = isl_set_intersect(Context, AssumptionCtx);
1935 }
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001936 }
1937}
1938
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001939void Scop::addUserContext() {
1940 if (UserContextStr.empty())
1941 return;
1942
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001943 isl_set *UserContext =
1944 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001945 isl_space *Space = getParamSpace();
1946 if (isl_space_dim(Space, isl_dim_param) !=
1947 isl_set_dim(UserContext, isl_dim_param)) {
1948 auto SpaceStr = isl_space_to_str(Space);
1949 errs() << "Error: the context provided in -polly-context has not the same "
1950 << "number of dimensions than the computed context. Due to this "
1951 << "mismatch, the -polly-context option is ignored. Please provide "
1952 << "the context in the parameter space: " << SpaceStr << ".\n";
1953 free(SpaceStr);
1954 isl_set_free(UserContext);
1955 isl_space_free(Space);
1956 return;
1957 }
1958
1959 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001960 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1961 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001962
1963 if (strcmp(NameContext, NameUserContext) != 0) {
1964 auto SpaceStr = isl_space_to_str(Space);
1965 errs() << "Error: the name of dimension " << i
1966 << " provided in -polly-context "
1967 << "is '" << NameUserContext << "', but the name in the computed "
1968 << "context is '" << NameContext
1969 << "'. Due to this name mismatch, "
1970 << "the -polly-context option is ignored. Please provide "
1971 << "the context in the parameter space: " << SpaceStr << ".\n";
1972 free(SpaceStr);
1973 isl_set_free(UserContext);
1974 isl_space_free(Space);
1975 return;
1976 }
1977
1978 UserContext =
1979 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1980 isl_space_get_dim_id(Space, isl_dim_param, i));
1981 }
1982
1983 Context = isl_set_intersect(Context, UserContext);
1984 isl_space_free(Space);
1985}
1986
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001987void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001988 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001989
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001990 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001991 for (LoadInst *LInst : RIL) {
1992 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1993
Johannes Doerfert96e54712016-02-07 17:30:13 +00001994 Type *Ty = LInst->getType();
1995 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001996 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001997 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001998 continue;
1999 }
2000
2001 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002002 InvariantEquivClasses.emplace_back(
2003 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002004 }
2005}
2006
Tobias Grosser6be480c2011-11-08 15:41:13 +00002007void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002008 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002009 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002010 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002011 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002012}
2013
Tobias Grosser18daaca2012-05-22 10:47:27 +00002014void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002015 unsigned PDim = 0;
2016 for (auto *Parameter : Parameters) {
2017 ConstantRange SRange = SE->getSignedRange(Parameter);
2018 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002019 }
2020}
2021
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002022void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002023 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002024 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002025
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002026 unsigned PDim = 0;
2027 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002028 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002029 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002030 }
2031
2032 // Align the parameters of all data structures to the model.
2033 Context = isl_set_align_params(Context, Space);
2034
Johannes Doerferta60ad842016-05-10 12:18:22 +00002035 // As all parameters are known add bounds to them.
2036 addParameterBounds();
2037
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002038 for (ScopStmt &Stmt : *this)
2039 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002040
2041 // Simplify the schedule according to the context too.
2042 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002043}
2044
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002045static __isl_give isl_set *
2046simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2047 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002048 // If we have modeled all blocks in the SCoP that have side effects we can
2049 // simplify the context with the constraints that are needed for anything to
2050 // be executed at all. However, if we have error blocks in the SCoP we already
2051 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002052 // domains, thus we cannot use the remaining domain to simplify the
2053 // assumptions.
2054 if (!S.hasErrorBlock()) {
2055 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2056 AssumptionContext =
2057 isl_set_gist_params(AssumptionContext, DomainParameters);
2058 }
2059
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002060 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2061 return AssumptionContext;
2062}
2063
2064void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002065 // The parameter constraints of the iteration domains give us a set of
2066 // constraints that need to hold for all cases where at least a single
2067 // statement iteration is executed in the whole scop. We now simplify the
2068 // assumed context under the assumption that such constraints hold and at
2069 // least a single statement iteration is executed. For cases where no
2070 // statement instances are executed, the assumptions we have taken about
2071 // the executed code do not matter and can be changed.
2072 //
2073 // WARNING: This only holds if the assumptions we have taken do not reduce
2074 // the set of statement instances that are executed. Otherwise we
2075 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002076 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002077 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002078 // performed. In such a case, modifying the run-time conditions and
2079 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002080 // to not be executed.
2081 //
2082 // Example:
2083 //
2084 // When delinearizing the following code:
2085 //
2086 // for (long i = 0; i < 100; i++)
2087 // for (long j = 0; j < m; j++)
2088 // A[i+p][j] = 1.0;
2089 //
2090 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002091 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002092 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002093 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002094 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002095}
2096
Tobias Grosserc80d6972016-09-02 06:33:33 +00002097/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002098static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002099 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2100 isl_pw_multi_aff *MinPMA, *MaxPMA;
2101 isl_pw_aff *LastDimAff;
2102 isl_aff *OneAff;
2103 unsigned Pos;
2104
Johannes Doerfert6296d952016-04-22 11:38:19 +00002105 Set = isl_set_remove_divs(Set);
2106
Michael Krusebc150122016-05-02 12:25:18 +00002107 if (isl_set_n_basic_set(Set) >= MaxDisjunctionsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002108 isl_set_free(Set);
2109 return isl_stat_error;
2110 }
2111
Johannes Doerfert9143d672014-09-27 11:02:39 +00002112 // Restrict the number of parameters involved in the access as the lexmin/
2113 // lexmax computation will take too long if this number is high.
2114 //
2115 // Experiments with a simple test case using an i7 4800MQ:
2116 //
2117 // #Parameters involved | Time (in sec)
2118 // 6 | 0.01
2119 // 7 | 0.04
2120 // 8 | 0.12
2121 // 9 | 0.40
2122 // 10 | 1.54
2123 // 11 | 6.78
2124 // 12 | 30.38
2125 //
2126 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2127 unsigned InvolvedParams = 0;
2128 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2129 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2130 InvolvedParams++;
2131
2132 if (InvolvedParams > RunTimeChecksMaxParameters) {
2133 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002134 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002135 }
2136 }
2137
Johannes Doerfertb164c792014-09-18 11:17:17 +00002138 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2139 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2140
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002141 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2142 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2143
Johannes Doerfertb164c792014-09-18 11:17:17 +00002144 // Adjust the last dimension of the maximal access by one as we want to
2145 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2146 // we test during code generation might now point after the end of the
2147 // allocated array but we will never dereference it anyway.
2148 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2149 "Assumed at least one output dimension");
2150 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2151 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2152 OneAff = isl_aff_zero_on_domain(
2153 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2154 OneAff = isl_aff_add_constant_si(OneAff, 1);
2155 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2156 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2157
2158 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2159
2160 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002161 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002162}
2163
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002164static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2165 isl_set *Domain = MA->getStatement()->getDomain();
2166 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2167 return isl_set_reset_tuple_id(Domain);
2168}
2169
Tobias Grosserc80d6972016-09-02 06:33:33 +00002170/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002171static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002172 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002173
Tobias Grossere9522232017-01-16 15:49:04 +00002174 MinMaxAccesses.reserve(AliasGroup.size());
2175
2176 isl_union_set *Domains = S.getDomains();
2177 isl_union_map *Accesses = isl_union_map_empty(S.getParamSpace());
2178
2179 for (MemoryAccess *MA : AliasGroup)
2180 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2181
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002182 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2183 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002184 Locations = isl_union_set_coalesce(Locations);
2185 Locations = isl_union_set_detect_equalities(Locations);
Tobias Grosserff400872017-02-01 10:12:09 +00002186 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
2187 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002188 isl_union_set_free(Locations);
2189 return Valid;
2190}
2191
Tobias Grosserc80d6972016-09-02 06:33:33 +00002192/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002193///
2194///{
2195
Tobias Grosserc80d6972016-09-02 06:33:33 +00002196/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002197static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2198 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2199 : RN->getNodeAs<BasicBlock>();
2200}
2201
Tobias Grosserc80d6972016-09-02 06:33:33 +00002202/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002203static inline BasicBlock *
2204getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002205 if (RN->isSubRegion()) {
2206 assert(idx == 0);
2207 return RN->getNodeAs<Region>()->getExit();
2208 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002209 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002210}
2211
Tobias Grosserc80d6972016-09-02 06:33:33 +00002212/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002213static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2214 if (!RN->isSubRegion())
2215 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2216
2217 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2218 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2219 while (L && NonAffineSubRegion->contains(L))
2220 L = L->getParentLoop();
2221 return L;
2222}
2223
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002224static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2225 if (!RN->isSubRegion())
2226 return 1;
2227
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002228 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002229 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002230}
2231
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002232static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2233 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002234 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002235 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002236 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002237 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002238 return true;
2239 return false;
2240}
2241
Johannes Doerfert96425c22015-08-30 21:13:53 +00002242///}
2243
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002244static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2245 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002246 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002247 isl_id *DimId =
2248 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2249 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2250}
2251
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002252__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002253 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002254}
2255
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002256__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002257 auto DIt = DomainMap.find(BB);
2258 if (DIt != DomainMap.end())
2259 return isl_set_copy(DIt->getSecond());
2260
2261 auto &RI = *R.getRegionInfo();
2262 auto *BBR = RI.getRegionFor(BB);
2263 while (BBR->getEntry() == BB)
2264 BBR = BBR->getParent();
2265 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002266}
2267
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002268bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002269
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002270 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002271 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002272 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2273 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002274 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002275
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002276 while (LD-- >= 0) {
2277 S = addDomainDimId(S, LD + 1, L);
2278 L = L->getParentLoop();
2279 }
2280
Johannes Doerferta3519512016-04-23 13:02:23 +00002281 // Initialize the invalid domain.
2282 auto *EntryStmt = getStmtFor(EntryBB);
2283 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2284
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002285 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002286
Johannes Doerfert432658d2016-01-26 11:01:41 +00002287 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002288 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002289
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002290 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002291 return false;
2292
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002293 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002294 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002295
2296 // Error blocks and blocks dominated by them have been assumed to never be
2297 // executed. Representing them in the Scop does not add any value. In fact,
2298 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002299 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002300 // will cause problems when building up a ScopStmt for them.
2301 // Furthermore, basic blocks dominated by error blocks may reference
2302 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002303 // can themselves not be constructed properly. To this end we will replace
2304 // the domains of error blocks and those only reachable via error blocks
2305 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002306 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002307 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002308 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002309 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002310
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002311 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002312}
2313
Tobias Grosserc80d6972016-09-02 06:33:33 +00002314/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002315/// to be compatible to domains constructed for loop @p NewL.
2316///
2317/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2318/// edge from @p OldL to @p NewL.
2319static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2320 __isl_take isl_set *Dom,
2321 Loop *OldL, Loop *NewL) {
2322
2323 // If the loops are the same there is nothing to do.
2324 if (NewL == OldL)
2325 return Dom;
2326
2327 int OldDepth = S.getRelativeLoopDepth(OldL);
2328 int NewDepth = S.getRelativeLoopDepth(NewL);
2329 // If both loops are non-affine loops there is nothing to do.
2330 if (OldDepth == -1 && NewDepth == -1)
2331 return Dom;
2332
2333 // Distinguish three cases:
2334 // 1) The depth is the same but the loops are not.
2335 // => One loop was left one was entered.
2336 // 2) The depth increased from OldL to NewL.
2337 // => One loop was entered, none was left.
2338 // 3) The depth decreased from OldL to NewL.
2339 // => Loops were left were difference of the depths defines how many.
2340 if (OldDepth == NewDepth) {
2341 assert(OldL->getParentLoop() == NewL->getParentLoop());
2342 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2343 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2344 Dom = addDomainDimId(Dom, NewDepth, NewL);
2345 } else if (OldDepth < NewDepth) {
2346 assert(OldDepth + 1 == NewDepth);
2347 auto &R = S.getRegion();
2348 (void)R;
2349 assert(NewL->getParentLoop() == OldL ||
2350 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2351 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2352 Dom = addDomainDimId(Dom, NewDepth, NewL);
2353 } else {
2354 assert(OldDepth > NewDepth);
2355 int Diff = OldDepth - NewDepth;
2356 int NumDim = isl_set_n_dim(Dom);
2357 assert(NumDim >= Diff);
2358 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2359 }
2360
2361 return Dom;
2362}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002363
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002364bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2365 LoopInfo &LI) {
2366 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002367
2368 ReversePostOrderTraversal<Region *> RTraversal(R);
2369 for (auto *RN : RTraversal) {
2370
2371 // Recurse for affine subregions but go on for basic blocks and non-affine
2372 // subregions.
2373 if (RN->isSubRegion()) {
2374 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002375 if (!isNonAffineSubRegion(SubRegion)) {
2376 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002377 continue;
2378 }
2379 }
2380
2381 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2382 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002383 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002384 isl_set *&Domain = DomainMap[BB];
2385 assert(Domain && "Cannot propagate a nullptr");
2386
Johannes Doerferta3519512016-04-23 13:02:23 +00002387 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002388 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002389 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002390
Johannes Doerferta3519512016-04-23 13:02:23 +00002391 if (!IsInvalidBlock) {
2392 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002393 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002394 isl_set_free(InvalidDomain);
2395 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002396 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2397 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2398 AS_RESTRICTION);
2399 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002400 }
2401
Johannes Doerferta3519512016-04-23 13:02:23 +00002402 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002403 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002404 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002405 }
2406
Johannes Doerferta3519512016-04-23 13:02:23 +00002407 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002408 auto *TI = BB->getTerminator();
2409 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2410 for (unsigned u = 0; u < NumSuccs; u++) {
2411 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002412 auto *SuccStmt = getStmtFor(SuccBB);
2413
2414 // Skip successors outside the SCoP.
2415 if (!SuccStmt)
2416 continue;
2417
Johannes Doerferte4459a22016-04-25 13:34:50 +00002418 // Skip backedges.
2419 if (DT.dominates(SuccBB, BB))
2420 continue;
2421
Johannes Doerferta3519512016-04-23 13:02:23 +00002422 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2423 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2424 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2425 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2426 SuccInvalidDomain =
2427 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2428 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2429 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2430 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002431
Michael Krusebc150122016-05-02 12:25:18 +00002432 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002433 // In case this happens we will bail.
Michael Krusebc150122016-05-02 12:25:18 +00002434 if (NumConjucts < MaxDisjunctionsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002435 continue;
2436
Johannes Doerferta3519512016-04-23 13:02:23 +00002437 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002438 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002439 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002440 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002441
2442 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002443 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002444
2445 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002446}
2447
Johannes Doerfert642594a2016-04-04 07:57:39 +00002448void Scop::propagateDomainConstraintsToRegionExit(
2449 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002450 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002451
2452 // Check if the block @p BB is the entry of a region. If so we propagate it's
2453 // domain to the exit block of the region. Otherwise we are done.
2454 auto *RI = R.getRegionInfo();
2455 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2456 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002457 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002458 return;
2459
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002460 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002461 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002462 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002463 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002464 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002465 SmallVector<BasicBlock *, 4> LatchBBs;
2466 BBLoop->getLoopLatches(LatchBBs);
2467 for (auto *LatchBB : LatchBBs)
2468 if (BB != LatchBB && BBReg->contains(LatchBB))
2469 return;
2470 L = L->getParentLoop();
2471 }
2472
2473 auto *Domain = DomainMap[BB];
2474 assert(Domain && "Cannot propagate a nullptr");
2475
2476 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2477
2478 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2479 // adjust the domain before we can propagate it.
2480 auto *AdjustedDomain =
2481 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2482 auto *&ExitDomain = DomainMap[ExitBB];
2483
2484 // If the exit domain is not yet created we set it otherwise we "add" the
2485 // current domain.
2486 ExitDomain =
2487 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2488
Johannes Doerferta3519512016-04-23 13:02:23 +00002489 // Initialize the invalid domain.
2490 auto *ExitStmt = getStmtFor(ExitBB);
2491 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2492
Johannes Doerfert642594a2016-04-04 07:57:39 +00002493 FinishedExitBlocks.insert(ExitBB);
2494}
2495
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002496bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2497 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002498 // To create the domain for each block in R we iterate over all blocks and
2499 // subregions in R and propagate the conditions under which the current region
2500 // element is executed. To this end we iterate in reverse post order over R as
2501 // it ensures that we first visit all predecessors of a region node (either a
2502 // basic block or a subregion) before we visit the region node itself.
2503 // Initially, only the domain for the SCoP region entry block is set and from
2504 // there we propagate the current domain to all successors, however we add the
2505 // condition that the successor is actually executed next.
2506 // As we are only interested in non-loop carried constraints here we can
2507 // simply skip loop back edges.
2508
Johannes Doerfert642594a2016-04-04 07:57:39 +00002509 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002510 ReversePostOrderTraversal<Region *> RTraversal(R);
2511 for (auto *RN : RTraversal) {
2512
2513 // Recurse for affine subregions but go on for basic blocks and non-affine
2514 // subregions.
2515 if (RN->isSubRegion()) {
2516 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002517 if (!isNonAffineSubRegion(SubRegion)) {
2518 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002519 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002520 continue;
2521 }
2522 }
2523
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002524 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002525 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002526
Johannes Doerfert96425c22015-08-30 21:13:53 +00002527 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002528 TerminatorInst *TI = BB->getTerminator();
2529
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002530 if (isa<UnreachableInst>(TI))
2531 continue;
2532
Johannes Doerfertf5673802015-10-01 23:48:18 +00002533 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002534 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002535 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002536 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002537
Johannes Doerfert642594a2016-04-04 07:57:39 +00002538 auto *BBLoop = getRegionNodeLoop(RN, LI);
2539 // Propagate the domain from BB directly to blocks that have a superset
2540 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002541 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002542
2543 // If all successors of BB have been set a domain through the propagation
2544 // above we do not need to build condition sets but can just skip this
2545 // block. However, it is important to note that this is a local property
2546 // with regards to the region @p R. To this end FinishedExitBlocks is a
2547 // local variable.
2548 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2549 return FinishedExitBlocks.count(SuccBB);
2550 };
2551 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2552 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002553
2554 // Build the condition sets for the successor nodes of the current region
2555 // node. If it is a non-affine subregion we will always execute the single
2556 // exit node, hence the single entry node domain is the condition set. For
2557 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002558 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002559 if (RN->isSubRegion())
2560 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002561 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2562 ConditionSets))
2563 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002564
2565 // Now iterate over the successors and set their initial domain based on
2566 // their condition set. We skip back edges here and have to be careful when
2567 // we leave a loop not to keep constraints over a dimension that doesn't
2568 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002569 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002570 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002571 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002572 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002573
Johannes Doerfert535de032016-04-19 14:49:05 +00002574 auto *SuccStmt = getStmtFor(SuccBB);
2575 // Skip blocks outside the region.
2576 if (!SuccStmt) {
2577 isl_set_free(CondSet);
2578 continue;
2579 }
2580
Johannes Doerfert642594a2016-04-04 07:57:39 +00002581 // If we propagate the domain of some block to "SuccBB" we do not have to
2582 // adjust the domain.
2583 if (FinishedExitBlocks.count(SuccBB)) {
2584 isl_set_free(CondSet);
2585 continue;
2586 }
2587
Johannes Doerfert96425c22015-08-30 21:13:53 +00002588 // Skip back edges.
2589 if (DT.dominates(SuccBB, BB)) {
2590 isl_set_free(CondSet);
2591 continue;
2592 }
2593
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002594 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002595 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002596 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002597
2598 // Set the domain for the successor or merge it with an existing domain in
2599 // case there are multiple paths (without loop back edges) to the
2600 // successor block.
2601 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002602
Johannes Doerferta3519512016-04-23 13:02:23 +00002603 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002604 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002605 } else {
2606 // Initialize the invalid domain.
2607 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2608 SuccDomain = CondSet;
2609 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002610
Michael Krusebc150122016-05-02 12:25:18 +00002611 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002612 // In case this happens we will clean up and bail.
Michael Krusebc150122016-05-02 12:25:18 +00002613 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctionsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002614 continue;
2615
2616 invalidate(COMPLEXITY, DebugLoc());
2617 while (++u < ConditionSets.size())
2618 isl_set_free(ConditionSets[u]);
2619 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002620 }
2621 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002622
2623 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002624}
2625
Michael Krused56b90a2016-09-01 09:03:27 +00002626__isl_give isl_set *
2627Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2628 __isl_keep isl_set *Domain,
2629 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002630 // If @p BB is the ScopEntry we are done
2631 if (R.getEntry() == BB)
2632 return isl_set_universe(isl_set_get_space(Domain));
2633
2634 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002635 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002636
2637 // The region info of this function.
2638 auto &RI = *R.getRegionInfo();
2639
2640 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2641
2642 // A domain to collect all predecessor domains, thus all conditions under
2643 // which the block is executed. To this end we start with the empty domain.
2644 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2645
2646 // Set of regions of which the entry block domain has been propagated to BB.
2647 // all predecessors inside any of the regions can be skipped.
2648 SmallSet<Region *, 8> PropagatedRegions;
2649
2650 for (auto *PredBB : predecessors(BB)) {
2651 // Skip backedges.
2652 if (DT.dominates(BB, PredBB))
2653 continue;
2654
2655 // If the predecessor is in a region we used for propagation we can skip it.
2656 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2657 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2658 PredBBInRegion)) {
2659 continue;
2660 }
2661
2662 // Check if there is a valid region we can use for propagation, thus look
2663 // for a region that contains the predecessor and has @p BB as exit block.
2664 auto *PredR = RI.getRegionFor(PredBB);
2665 while (PredR->getExit() != BB && !PredR->contains(BB))
2666 PredR->getParent();
2667
2668 // If a valid region for propagation was found use the entry of that region
2669 // for propagation, otherwise the PredBB directly.
2670 if (PredR->getExit() == BB) {
2671 PredBB = PredR->getEntry();
2672 PropagatedRegions.insert(PredR);
2673 }
2674
Johannes Doerfert41cda152016-04-08 10:32:26 +00002675 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002676 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2677 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2678
2679 PredDom = isl_set_union(PredDom, PredBBDom);
2680 }
2681
2682 return PredDom;
2683}
2684
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002685bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2686 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002687 // Iterate over the region R and propagate the domain constrains from the
2688 // predecessors to the current node. In contrast to the
2689 // buildDomainsWithBranchConstraints function, this one will pull the domain
2690 // information from the predecessors instead of pushing it to the successors.
2691 // Additionally, we assume the domains to be already present in the domain
2692 // map here. However, we iterate again in reverse post order so we know all
2693 // predecessors have been visited before a block or non-affine subregion is
2694 // visited.
2695
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002696 ReversePostOrderTraversal<Region *> RTraversal(R);
2697 for (auto *RN : RTraversal) {
2698
2699 // Recurse for affine subregions but go on for basic blocks and non-affine
2700 // subregions.
2701 if (RN->isSubRegion()) {
2702 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002703 if (!isNonAffineSubRegion(SubRegion)) {
2704 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002705 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002706 continue;
2707 }
2708 }
2709
2710 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002711 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002712 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002713
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002714 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002715 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002716 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002717 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002718
Johannes Doerfert642594a2016-04-04 07:57:39 +00002719 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002720 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002721 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2722 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002723 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002724
2725 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002726}
2727
Tobias Grosserc80d6972016-09-02 06:33:33 +00002728/// Create a map to map from a given iteration to a subsequent iteration.
2729///
2730/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2731/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002732/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002733///
2734/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002735static __isl_give isl_map *
2736createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2737 auto *MapSpace = isl_space_map_from_set(SetSpace);
2738 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2739 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2740 if (u != Dim)
2741 NextIterationMap =
2742 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2743 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2744 C = isl_constraint_set_constant_si(C, 1);
2745 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2746 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2747 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2748 return NextIterationMap;
2749}
2750
Johannes Doerfert297c7202016-05-10 13:06:42 +00002751bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002752 int LoopDepth = getRelativeLoopDepth(L);
2753 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002754
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002755 BasicBlock *HeaderBB = L->getHeader();
2756 assert(DomainMap.count(HeaderBB));
2757 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002758
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002759 isl_map *NextIterationMap =
2760 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002761
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002762 isl_set *UnionBackedgeCondition =
2763 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002764
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002765 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2766 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002767
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002768 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002769
2770 // If the latch is only reachable via error statements we skip it.
2771 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2772 if (!LatchBBDom)
2773 continue;
2774
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002775 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002776
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002777 TerminatorInst *TI = LatchBB->getTerminator();
2778 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00002779 assert(BI && "Only branch instructions allowed in loop latches");
2780
2781 if (BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002782 BackedgeCondition = isl_set_copy(LatchBBDom);
2783 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002784 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002785 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002786 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
Michael Krusee1dc3872016-11-03 15:19:41 +00002787 ConditionSets)) {
2788 isl_map_free(NextIterationMap);
2789 isl_set_free(UnionBackedgeCondition);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002790 return false;
Michael Krusee1dc3872016-11-03 15:19:41 +00002791 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002792
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002793 // Free the non back edge condition set as we do not need it.
2794 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002795
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002796 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002797 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002798
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002799 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2800 assert(LatchLoopDepth >= LoopDepth);
2801 BackedgeCondition =
2802 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2803 LatchLoopDepth - LoopDepth);
2804 UnionBackedgeCondition =
2805 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002806 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002807
2808 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2809 for (int i = 0; i < LoopDepth; i++)
2810 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2811
2812 isl_set *UnionBackedgeConditionComplement =
2813 isl_set_complement(UnionBackedgeCondition);
2814 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2815 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2816 UnionBackedgeConditionComplement =
2817 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2818 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2819 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2820
2821 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2822 HeaderBBDom = Parts.second;
2823
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002824 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2825 // the bounded assumptions to the context as they are already implied by the
2826 // <nsw> tag.
2827 if (Affinator.hasNSWAddRecForLoop(L)) {
2828 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002829 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002830 }
2831
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002832 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002833 recordAssumption(INFINITELOOP, UnboundedCtx,
2834 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002835 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002836}
2837
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002838MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00002839 Value *PointerBase = MA->getBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002840
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00002841 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002842 if (!PointerBaseInst)
2843 return nullptr;
2844
2845 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2846 if (!BasePtrStmt)
2847 return nullptr;
2848
2849 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2850}
2851
2852bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2853 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00002854 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
2855 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
2856 bool Hoistable = NHCtx != nullptr;
2857 isl_set_free(NHCtx);
2858 return !Hoistable;
2859 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002860
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00002861 Value *BaseAddr = MA->getBaseAddr();
2862 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002863 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00002864 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002865
2866 return false;
2867}
2868
Johannes Doerfert5210da52016-06-02 11:06:54 +00002869bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002870 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00002871 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002872
Johannes Doerfertcd195322016-11-17 21:41:08 +00002873 if (buildAliasGroups(AA)) {
2874 // Aliasing assumptions do not go through addAssumption but we still want to
2875 // collect statistics so we do it here explicitly.
2876 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00002877 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00002878 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00002879 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002880
2881 // If a problem occurs while building the alias groups we need to delete
2882 // this SCoP and pretend it wasn't valid in the first place. To this end
2883 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002884 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002885
2886 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2887 << " could not be created as the number of parameters involved "
2888 "is too high. The SCoP will be "
2889 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2890 "the maximal number of parameters but be advised that the "
2891 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00002892 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002893}
2894
Tobias Grosser9edcf072017-01-16 14:07:57 +00002895std::tuple<Scop::AliasGroupVectorTy, DenseSet<Value *>>
2896Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002897 AliasSetTracker AST(AA);
2898
2899 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002900 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002901 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002902
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002903 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002904 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2905 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00002906
2907 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002908 if (StmtDomainEmpty)
2909 continue;
2910
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002911 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002912 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002913 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002914 if (!MA->isRead())
2915 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002916 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002917 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00002918 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002919 else
2920 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002921 AST.add(Acc);
2922 }
2923 }
2924
Tobias Grosser9edcf072017-01-16 14:07:57 +00002925 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002926 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002927 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002928 continue;
2929 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002930 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002931 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002932 if (AG.size() < 2)
2933 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002934 AliasGroups.push_back(std::move(AG));
2935 }
2936
Tobias Grosser9edcf072017-01-16 14:07:57 +00002937 return std::make_tuple(AliasGroups, HasWriteAccess);
2938}
2939
Tobias Grossere39f9122017-01-16 14:08:00 +00002940void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002941 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2942 AliasGroupTy NewAG;
2943 AliasGroupTy &AG = AliasGroups[u];
2944 AliasGroupTy::iterator AGI = AG.begin();
2945 isl_set *AGDomain = getAccessDomain(*AGI);
2946 while (AGI != AG.end()) {
2947 MemoryAccess *MA = *AGI;
2948 isl_set *MADomain = getAccessDomain(MA);
2949 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2950 NewAG.push_back(MA);
2951 AGI = AG.erase(AGI);
2952 isl_set_free(MADomain);
2953 } else {
2954 AGDomain = isl_set_union(AGDomain, MADomain);
2955 AGI++;
2956 }
2957 }
2958 if (NewAG.size() > 1)
2959 AliasGroups.push_back(std::move(NewAG));
2960 isl_set_free(AGDomain);
2961 }
Tobias Grossere39f9122017-01-16 14:08:00 +00002962}
2963
2964bool Scop::buildAliasGroups(AliasAnalysis &AA) {
2965 // To create sound alias checks we perform the following steps:
2966 // o) We partition each group into read only and non read only accesses.
2967 // o) For each group with more than one base pointer we then compute minimal
2968 // and maximal accesses to each array of a group in read only and non
2969 // read only partitions separately.
2970 AliasGroupVectorTy AliasGroups;
2971 DenseSet<Value *> HasWriteAccess;
2972
2973 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
2974
2975 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002976
Johannes Doerfert13771732014-10-01 12:40:46 +00002977 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser77f32572017-01-16 15:49:07 +00002978 bool Valid = buildAliasGroup(AG, HasWriteAccess);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002979 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002980 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002981 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002982
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002983 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002984}
2985
Tobias Grosser77f32572017-01-16 15:49:07 +00002986bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
2987 DenseSet<Value *> HasWriteAccess) {
2988 AliasGroupTy ReadOnlyAccesses;
2989 AliasGroupTy ReadWriteAccesses;
Tobias Grosserf3c145f2017-01-16 15:49:09 +00002990 SmallPtrSet<const Value *, 4> ReadWriteBaseValues;
Tobias Grosser77f32572017-01-16 15:49:07 +00002991
2992 auto &F = getFunction();
2993
2994 if (AliasGroup.size() < 2)
2995 return true;
2996
2997 for (MemoryAccess *Access : AliasGroup) {
2998 emitOptimizationRemarkAnalysis(
2999 F.getContext(), DEBUG_TYPE, F,
3000 Access->getAccessInstruction()->getDebugLoc(),
3001 "Possibly aliasing pointer, use restrict keyword.");
3002
3003 Value *BaseAddr = Access->getBaseAddr();
3004 if (HasWriteAccess.count(BaseAddr)) {
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003005 ReadWriteBaseValues.insert(BaseAddr);
Tobias Grosser77f32572017-01-16 15:49:07 +00003006 ReadWriteAccesses.push_back(Access);
3007 } else {
3008 ReadOnlyAccesses.push_back(Access);
3009 }
3010 }
3011
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003012 // If there are no read-only pointers, and less than two read-write pointers,
3013 // no alias check is needed.
3014 if (ReadOnlyAccesses.empty() && ReadWriteBaseValues.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003015 return true;
3016
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003017 // If there is no read-write pointer, no alias check is needed.
3018 if (ReadWriteBaseValues.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003019 return true;
3020
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003021 // For non-affine accesses, no alias check can be generated as we cannot
3022 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003023 for (MemoryAccess *MA : AliasGroup) {
3024 if (!MA->isAffine()) {
3025 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3026 return false;
3027 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003028 }
3029
3030 // Ensure that for all memory accesses for which we generate alias checks,
3031 // their base pointers are available.
3032 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003033 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3034 addRequiredInvariantLoad(
3035 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3036 }
3037
3038 MinMaxAliasGroups.emplace_back();
3039 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3040 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3041 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3042
3043 bool Valid;
3044
3045 Valid =
3046 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3047
3048 if (!Valid)
3049 return false;
3050
3051 // Bail out if the number of values we need to compare is too large.
3052 // This is important as the number of comparisons grows quadratically with
3053 // the number of values we need to compare.
3054 if (MinMaxAccessesReadWrite.size() + ReadOnlyAccesses.size() >
3055 RunTimeChecksMaxArraysPerGroup)
3056 return false;
3057
3058 Valid =
3059 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3060
3061 if (!Valid)
3062 return false;
3063
3064 return true;
3065}
3066
Tobias Grosserc80d6972016-09-02 06:33:33 +00003067/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003068static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003069 // Start with the smallest loop containing the entry and expand that
3070 // loop until it contains all blocks in the region. If there is a loop
3071 // containing all blocks in the region check if it is itself contained
3072 // and if so take the parent loop as it will be the smallest containing
3073 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003074 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003075 while (L) {
3076 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003077 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003078 AllContained &= L->contains(BB);
3079 if (AllContained)
3080 break;
3081 L = L->getParentLoop();
3082 }
3083
Johannes Doerfertef744432016-05-23 12:42:38 +00003084 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003085}
3086
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003087Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003088 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003089 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003090 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003091 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3092 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3093 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3094 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003095 if (IslOnErrorAbort)
3096 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003097 buildContext();
3098}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003099
Tobias Grosserbedef002016-12-02 08:10:56 +00003100void Scop::foldSizeConstantsToRight() {
3101 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3102
3103 for (auto Array : arrays()) {
3104 if (Array->getNumberOfDimensions() <= 1)
3105 continue;
3106
3107 isl_space *Space = Array->getSpace();
3108
3109 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3110
3111 if (!isl_union_set_contains(Accessed, Space)) {
3112 isl_space_free(Space);
3113 continue;
3114 }
3115
3116 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3117
3118 isl_map *Transform =
3119 isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3120
3121 std::vector<int> Int;
3122
3123 int Dims = isl_set_dim(Elements, isl_dim_set);
3124 for (int i = 0; i < Dims; i++) {
3125 isl_set *DimOnly =
3126 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3127 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3128 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3129
3130 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3131
3132 if (i == Dims - 1) {
3133 Int.push_back(1);
3134 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3135 isl_basic_set_free(DimHull);
3136 continue;
3137 }
3138
3139 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3140 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3141 isl_val *Val = isl_aff_get_denominator_val(Diff);
3142 isl_aff_free(Diff);
3143
3144 int ValInt = 1;
3145
3146 if (isl_val_is_int(Val))
3147 ValInt = isl_val_get_num_si(Val);
3148 isl_val_free(Val);
3149
3150 Int.push_back(ValInt);
3151
3152 isl_constraint *C = isl_constraint_alloc_equality(
3153 isl_local_space_from_space(isl_map_get_space(Transform)));
3154 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3155 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3156 Transform = isl_map_add_constraint(Transform, C);
3157 isl_basic_set_free(DimHull);
3158 continue;
3159 }
3160
3161 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3162 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3163
3164 int ValInt = 1;
3165 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3166 ValInt = 0;
3167 }
3168
3169 Int.push_back(ValInt);
3170 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3171 isl_basic_set_free(DimHull);
3172 isl_basic_set_free(ZeroSet);
3173 }
3174
3175 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3176
3177 if (!isl_set_is_subset(Elements, MappedElements)) {
3178 isl_set_free(Elements);
3179 isl_set_free(MappedElements);
3180 isl_map_free(Transform);
3181 continue;
3182 }
3183
3184 isl_set_free(MappedElements);
3185
3186 bool CanFold = true;
3187
3188 if (Int[0] <= 1)
3189 CanFold = false;
3190
3191 unsigned NumDims = Array->getNumberOfDimensions();
3192 for (unsigned i = 1; i < NumDims - 1; i++)
3193 if (Int[0] != Int[i] && Int[i])
3194 CanFold = false;
3195
3196 if (!CanFold) {
3197 isl_set_free(Elements);
3198 isl_map_free(Transform);
3199 continue;
3200 }
3201
Tobias Grosserbedef002016-12-02 08:10:56 +00003202 for (auto &Access : AccessFunctions)
3203 if (Access->getScopArrayInfo() == Array)
3204 Access->setAccessRelation(isl_map_apply_range(
3205 Access->getAccessRelation(), isl_map_copy(Transform)));
3206
3207 isl_map_free(Transform);
3208
3209 std::vector<const SCEV *> Sizes;
3210 for (unsigned i = 0; i < NumDims; i++) {
3211 auto Size = Array->getDimensionSize(i);
3212
3213 if (i == NumDims - 1)
3214 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3215 Sizes.push_back(Size);
3216 }
3217
3218 Array->updateSizes(Sizes, false /* CheckConsistency */);
3219
3220 isl_set_free(Elements);
3221 }
3222 isl_union_set_free(Accessed);
3223 return;
3224}
3225
Tobias Grosser491b7992016-12-02 05:21:22 +00003226void Scop::finalizeAccesses() {
3227 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003228 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003229 foldAccessRelations();
3230 assumeNoOutOfBounds();
3231}
3232
Michael Kruse7037fde2016-12-15 09:25:14 +00003233void Scop::init(AliasAnalysis &AA, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003234 buildInvariantEquivalenceClasses();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003235
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003236 if (!buildDomains(&R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003237 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003238
Michael Kruse7037fde2016-12-15 09:25:14 +00003239 addUserAssumptions(DT, LI);
Johannes Doerfertff68f462016-04-19 14:49:42 +00003240
Johannes Doerfert26404542016-05-10 12:19:47 +00003241 // Remove empty statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003242 // Exit early in case there are no executable statements left in this scop.
Michael Kruse977d38b2016-07-22 17:31:17 +00003243 simplifySCoP(false);
Michael Kruseafe06702015-10-02 16:33:27 +00003244 if (Stmts.empty())
3245 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003246
Michael Krusecac948e2015-10-02 13:53:07 +00003247 // The ScopStmts now have enough information to initialize themselves.
3248 for (ScopStmt &Stmt : Stmts)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003249 Stmt.init(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00003250
Johannes Doerfertb1d66082016-12-01 11:12:14 +00003251 // Check early for a feasible runtime context.
3252 if (!hasFeasibleRuntimeContext())
3253 return;
3254
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003255 // Check early for profitability. Afterwards it cannot change anymore,
3256 // only the runtime context could become infeasible.
3257 if (!isProfitable()) {
3258 invalidate(PROFITABLE, DebugLoc());
Tobias Grosser8286b832015-11-02 11:29:32 +00003259 return;
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003260 }
3261
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003262 buildSchedule(LI);
Tobias Grosser8286b832015-11-02 11:29:32 +00003263
Tobias Grosser491b7992016-12-02 05:21:22 +00003264 finalizeAccesses();
3265
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003266 realignParams();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003267 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003268
3269 // After the context was fully constructed, thus all our knowledge about
3270 // the parameters is in there, we add all recorded assumptions to the
3271 // assumed/invalid context.
3272 addRecordedAssumptions();
3273
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003274 simplifyContexts();
Johannes Doerfert5210da52016-06-02 11:06:54 +00003275 if (!buildAliasChecks(AA))
3276 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003277
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003278 hoistInvariantLoads();
3279 verifyInvariantLoads();
Michael Kruse977d38b2016-07-22 17:31:17 +00003280 simplifySCoP(true);
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003281
3282 // Check late for a feasible runtime context because profitability did not
3283 // change.
Johannes Doerfertb1d66082016-12-01 11:12:14 +00003284 if (!hasFeasibleRuntimeContext())
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003285 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003286}
3287
3288Scop::~Scop() {
3289 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003290 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003291 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003292 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003293
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003294 for (auto &It : ParameterIds)
3295 isl_id_free(It.second);
3296
Johannes Doerfert96425c22015-08-30 21:13:53 +00003297 for (auto It : DomainMap)
3298 isl_set_free(It.second);
3299
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003300 for (auto &AS : RecordedAssumptions)
3301 isl_set_free(AS.Set);
3302
Johannes Doerfertb164c792014-09-18 11:17:17 +00003303 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003304 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003305 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003306 isl_pw_multi_aff_free(MMA.first);
3307 isl_pw_multi_aff_free(MMA.second);
3308 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003309 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003310 isl_pw_multi_aff_free(MMA.first);
3311 isl_pw_multi_aff_free(MMA.second);
3312 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003313 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003314
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003315 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003316 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003317
3318 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003319 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003320 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003321 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003322 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003323 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003324 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003325}
3326
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003327void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003328 // Check all array accesses for each base pointer and find a (virtual) element
3329 // size for the base pointer that divides all access functions.
3330 for (auto &Stmt : *this)
3331 for (auto *Access : Stmt) {
3332 if (!Access->isArrayKind())
3333 continue;
3334 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003335 MemoryKind::Array)];
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003336 if (SAI->getNumberOfDimensions() != 1)
3337 continue;
3338 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3339 auto *Subscript = Access->getSubscript(0);
3340 while (!isDivisible(Subscript, DivisibleSize, *SE))
3341 DivisibleSize /= 2;
3342 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3343 SAI->updateElementType(Ty);
3344 }
3345
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003346 for (auto &Stmt : *this)
3347 for (auto &Access : Stmt)
3348 Access->updateDimensionality();
3349}
3350
Tobias Grosser491b7992016-12-02 05:21:22 +00003351void Scop::foldAccessRelations() {
3352 for (auto &Stmt : *this)
3353 for (auto &Access : Stmt)
3354 Access->foldAccessRelation();
3355}
3356
3357void Scop::assumeNoOutOfBounds() {
3358 for (auto &Stmt : *this)
3359 for (auto &Access : Stmt)
3360 Access->assumeNoOutOfBound();
3361}
3362
Michael Kruse977d38b2016-07-22 17:31:17 +00003363void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003364 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3365 ScopStmt &Stmt = *StmtIt;
3366
Johannes Doerfert26404542016-05-10 12:19:47 +00003367 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003368 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003369 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003370
Johannes Doerferteca9e892015-11-03 16:54:49 +00003371 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003372 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003373 bool OnlyRead = true;
3374 for (MemoryAccess *MA : Stmt) {
3375 if (MA->isRead())
3376 continue;
3377
3378 OnlyRead = false;
3379 break;
3380 }
3381
3382 RemoveStmt = OnlyRead;
3383 }
3384
Johannes Doerfert26404542016-05-10 12:19:47 +00003385 if (!RemoveStmt) {
3386 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003387 continue;
3388 }
3389
Johannes Doerfert26404542016-05-10 12:19:47 +00003390 // Remove the statement because it is unnecessary.
3391 if (Stmt.isRegionStmt())
3392 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3393 StmtMap.erase(BB);
3394 else
3395 StmtMap.erase(Stmt.getBasicBlock());
3396
3397 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003398 }
3399}
3400
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003401InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003402 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3403 if (!LInst)
3404 return nullptr;
3405
3406 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3407 LInst = cast<LoadInst>(Rep);
3408
Johannes Doerfert96e54712016-02-07 17:30:13 +00003409 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003410 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003411 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003412 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003413 continue;
3414
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003415 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003416 for (auto *MA : MAs)
3417 if (MA->getAccessInstruction() == Val)
3418 return &IAClass;
3419 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003420
3421 return nullptr;
3422}
3423
Tobias Grosserc80d6972016-09-02 06:33:33 +00003424/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003425static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003426 bool MAInvalidCtxIsEmpty,
3427 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003428 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3429 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3430 // TODO: We can provide more information for better but more expensive
3431 // results.
3432 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3433 LInst->getAlignment(), DL))
3434 return false;
3435
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003436 // If the location might be overwritten we do not hoist it unconditionally.
3437 //
3438 // TODO: This is probably to conservative.
3439 if (!NonHoistableCtxIsEmpty)
3440 return false;
3441
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003442 // If a dereferencable load is in a statement that is modeled precisely we can
3443 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003444 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003445 return true;
3446
3447 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003448 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003449 // statement domain.
3450 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3451 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3452 return false;
3453 return true;
3454}
3455
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003456void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003457
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003458 if (InvMAs.empty())
3459 return;
3460
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003461 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003462 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003463
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003464 // Get the context under which the statement is executed but remove the error
3465 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003466 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003467 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003468
Michael Krusebc150122016-05-02 12:25:18 +00003469 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctionsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003470 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003471 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3472 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003473 for (auto &InvMA : InvMAs)
3474 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003475 return;
3476 }
3477
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003478 // Project out all parameters that relate to loads in the statement. Otherwise
3479 // we could have cyclic dependences on the constraints under which the
3480 // hoisted loads are executed and we could not determine an order in which to
3481 // pre-load them. This happens because not only lower bounds are part of the
3482 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003483 for (auto &InvMA : InvMAs) {
3484 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003485 Instruction *AccInst = MA->getAccessInstruction();
3486 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003487 SetVector<Value *> Values;
3488 for (const SCEV *Parameter : Parameters) {
3489 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003490 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003491 if (!Values.count(AccInst))
3492 continue;
3493
3494 if (isl_id *ParamId = getIdForParam(Parameter)) {
3495 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3496 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3497 isl_id_free(ParamId);
3498 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003499 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003500 }
3501 }
3502
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003503 for (auto &InvMA : InvMAs) {
3504 auto *MA = InvMA.MA;
3505 auto *NHCtx = InvMA.NonHoistableCtx;
3506
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003507 // Check for another invariant access that accesses the same location as
3508 // MA and if found consolidate them. Otherwise create a new equivalence
3509 // class at the end of InvariantEquivClasses.
3510 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003511 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003512 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3513
Johannes Doerfert85676e32016-04-23 14:32:34 +00003514 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003515 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003516 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3517
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003518 isl_set *MACtx;
3519 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003520 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3521 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003522 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003523 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003524 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003525 } else {
3526 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003527 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003528 MACtx = isl_set_gist_params(MACtx, getContext());
3529 }
3530
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003531 bool Consolidated = false;
3532 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003533 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003534 continue;
3535
Johannes Doerfertdf880232016-03-03 12:26:58 +00003536 // If the pointer and the type is equal check if the access function wrt.
3537 // to the domain is equal too. It can happen that the domain fixes
3538 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003539 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003540 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003541 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003542 if (!MAs.empty()) {
3543 auto *LastMA = MAs.front();
3544
3545 auto *AR = isl_map_range(MA->getAccessRelation());
3546 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3547 bool SameAR = isl_set_is_equal(AR, LastAR);
3548 isl_set_free(AR);
3549 isl_set_free(LastAR);
3550
3551 if (!SameAR)
3552 continue;
3553 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003554
3555 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003556 MAs.push_front(MA);
3557
Johannes Doerfertdf880232016-03-03 12:26:58 +00003558 Consolidated = true;
3559
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003560 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003561 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003562 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003563 IAClassDomainCtx =
3564 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003565 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003566 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003567 break;
3568 }
3569
3570 if (Consolidated)
3571 continue;
3572
3573 // If we did not consolidate MA, thus did not find an equivalence class
3574 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003575 InvariantEquivClasses.emplace_back(
3576 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003577 }
3578
3579 isl_set_free(DomainCtx);
3580}
3581
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003582__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3583 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003584 // TODO: Loads that are not loop carried, hence are in a statement with
3585 // zero iterators, are by construction invariant, though we
3586 // currently "hoist" them anyway. This is necessary because we allow
3587 // them to be treated as parameters (e.g., in conditions) and our code
3588 // generation would otherwise use the old value.
3589
3590 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003591 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003592
Johannes Doerfertc9765462016-11-17 22:11:56 +00003593 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3594 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003595 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003596
3597 // Skip accesses that have an invariant base pointer which is defined but
3598 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3599 // returns a pointer that is used as a base address. However, as we want
3600 // to hoist indirect pointers, we allow the base pointer to be defined in
3601 // the region if it is also a memory access. Each ScopArrayInfo object
3602 // that has a base pointer origin has a base pointer that is loaded and
3603 // that it is invariant, thus it will be hoisted too. However, if there is
3604 // no base pointer origin we check that the base pointer is defined
3605 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003606 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003607 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003608 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003609
3610 // Skip accesses in non-affine subregions as they might not be executed
3611 // under the same condition as the entry of the non-affine subregion.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003612 if (BB != LI->getParent())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003613 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003614
3615 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003616 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003617
3618 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3619 Stmt.getNumIterators())) {
3620 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003621 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003622 }
3623
3624 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3625 isl_set *AccessRange = isl_map_range(AccessRelation);
3626
3627 isl_union_map *Written = isl_union_map_intersect_range(
3628 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003629 auto *WrittenCtx = isl_union_map_params(Written);
3630 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003631
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003632 if (!IsWritten)
3633 return WrittenCtx;
3634
3635 WrittenCtx = isl_set_remove_divs(WrittenCtx);
3636 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctionsInDomain;
3637 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3638 isl_set_free(WrittenCtx);
3639 return nullptr;
3640 }
3641
3642 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3643 AS_RESTRICTION);
3644 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003645}
3646
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003647void Scop::verifyInvariantLoads() {
3648 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003649 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003650 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003651 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003652 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003653 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3654 return;
3655 }
3656 }
3657}
3658
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003659void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003660 if (!PollyInvariantLoadHoisting)
3661 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003662
Tobias Grosser0865e7752016-02-29 07:29:42 +00003663 isl_union_map *Writes = getWrites();
3664 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003665 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003666
Tobias Grosser0865e7752016-02-29 07:29:42 +00003667 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003668 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3669 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003670
3671 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003672 for (auto InvMA : InvariantAccesses)
3673 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003674 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003675 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003676 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003677}
3678
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003679const ScopArrayInfo *
3680Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
3681 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
3682 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00003683 assert((BasePtr || BaseName) &&
3684 "BasePtr and BaseName can not be nullptr at the same time.");
3685 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3686 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3687 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003688 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003689 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003690 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003691 DL, this, BaseName));
3692 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003693 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003694 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003695 // In case of mismatching array sizes, we bail out by setting the run-time
3696 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003697 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003698 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003699 }
Tobias Grosserab671442015-05-23 05:58:27 +00003700 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003701}
3702
Roman Gareevd7754a12016-07-30 09:25:51 +00003703const ScopArrayInfo *
3704Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3705 const std::vector<unsigned> &Sizes) {
3706 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3707 std::vector<const SCEV *> SCEVSizes;
3708
3709 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003710 if (size)
3711 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3712 else
3713 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003714
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003715 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3716 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00003717 return SAI;
3718}
3719
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003720const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003721 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003722 assert(SAI && "No ScopArrayInfo available for this base pointer");
3723 return SAI;
3724}
3725
Tobias Grosser74394f02013-01-14 22:40:23 +00003726std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003727
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003728std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003729 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003730 return stringFromIslObj(AssumedContext);
3731}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003732
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003733std::string Scop::getInvalidContextStr() const {
3734 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003735}
Tobias Grosser75805372011-04-29 06:27:02 +00003736
3737std::string Scop::getNameStr() const {
3738 std::string ExitName, EntryName;
3739 raw_string_ostream ExitStr(ExitName);
3740 raw_string_ostream EntryStr(EntryName);
3741
Tobias Grosserf240b482014-01-09 10:42:15 +00003742 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003743 EntryStr.str();
3744
3745 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003746 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003747 ExitStr.str();
3748 } else
3749 ExitName = "FunctionExit";
3750
3751 return EntryName + "---" + ExitName;
3752}
3753
Tobias Grosser74394f02013-01-14 22:40:23 +00003754__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003755__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003756 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003757}
3758
Tobias Grossere86109f2013-10-29 21:05:49 +00003759__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003760 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003761 return isl_set_copy(AssumedContext);
3762}
3763
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003764bool Scop::isProfitable() const {
3765 if (PollyProcessUnprofitable)
3766 return true;
3767
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003768 if (isEmpty())
3769 return false;
3770
3771 unsigned OptimizableStmtsOrLoops = 0;
3772 for (auto &Stmt : *this) {
3773 if (Stmt.getNumIterators() == 0)
3774 continue;
3775
3776 bool ContainsArrayAccs = false;
3777 bool ContainsScalarAccs = false;
3778 for (auto *MA : Stmt) {
3779 if (MA->isRead())
3780 continue;
3781 ContainsArrayAccs |= MA->isArrayKind();
3782 ContainsScalarAccs |= MA->isScalarKind();
3783 }
3784
Michael Kruse6ab44762016-10-04 17:33:39 +00003785 if (!UnprofitableScalarAccs || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003786 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3787 }
3788
3789 return OptimizableStmtsOrLoops > 1;
3790}
3791
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003792bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003793 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003794 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003795 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3796 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3797 isl_set_is_subset(PositiveContext, NegativeContext));
3798 isl_set_free(PositiveContext);
3799 if (!IsFeasible) {
3800 isl_set_free(NegativeContext);
3801 return false;
3802 }
3803
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003804 auto *DomainContext = isl_union_set_params(getDomains());
3805 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003806 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003807 isl_set_free(NegativeContext);
3808 isl_set_free(DomainContext);
3809
Johannes Doerfert43788c52015-08-20 05:58:56 +00003810 return IsFeasible;
3811}
3812
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003813static std::string toString(AssumptionKind Kind) {
3814 switch (Kind) {
3815 case ALIASING:
3816 return "No-aliasing";
3817 case INBOUNDS:
3818 return "Inbounds";
3819 case WRAPPING:
3820 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00003821 case UNSIGNED:
3822 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003823 case COMPLEXITY:
3824 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003825 case PROFITABLE:
3826 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003827 case ERRORBLOCK:
3828 return "No-error";
3829 case INFINITELOOP:
3830 return "Finite loop";
3831 case INVARIANTLOAD:
3832 return "Invariant load";
3833 case DELINEARIZATION:
3834 return "Delinearization";
3835 }
3836 llvm_unreachable("Unknown AssumptionKind!");
3837}
3838
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003839bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
3840 if (Sign == AS_ASSUMPTION) {
3841 if (isl_set_is_subset(Context, Set))
3842 return false;
3843
3844 if (isl_set_is_subset(AssumedContext, Set))
3845 return false;
3846 } else {
3847 if (isl_set_is_disjoint(Set, Context))
3848 return false;
3849
3850 if (isl_set_is_subset(Set, InvalidContext))
3851 return false;
3852 }
3853 return true;
3854}
3855
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003856bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3857 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003858 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
3859 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003860
Johannes Doerfertb3265a32016-11-17 22:08:40 +00003861 // Do never emit trivial assumptions as they only clutter the output.
3862 if (!PollyRemarksMinimal) {
3863 isl_set *Univ = nullptr;
3864 if (Sign == AS_ASSUMPTION)
3865 Univ = isl_set_universe(isl_set_get_space(Set));
3866
3867 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
3868 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
3869 isl_set_free(Univ);
3870
3871 if (IsTrivial)
3872 return false;
3873 }
3874
Johannes Doerfertcd195322016-11-17 21:41:08 +00003875 switch (Kind) {
3876 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003877 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003878 break;
3879 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003880 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003881 break;
3882 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003883 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003884 break;
3885 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003886 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003887 break;
3888 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003889 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003890 break;
3891 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003892 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003893 break;
3894 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003895 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003896 break;
3897 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003898 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003899 break;
3900 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003901 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003902 break;
3903 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003904 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003905 break;
3906 }
3907
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003908 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003909 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3910 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003911 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003912 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003913}
3914
3915void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003916 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003917 // Simplify the assumptions/restrictions first.
3918 Set = isl_set_gist_params(Set, getContext());
3919
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003920 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3921 isl_set_free(Set);
3922 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003923 }
3924
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003925 if (Sign == AS_ASSUMPTION) {
3926 AssumedContext = isl_set_intersect(AssumedContext, Set);
3927 AssumedContext = isl_set_coalesce(AssumedContext);
3928 } else {
3929 InvalidContext = isl_set_union(InvalidContext, Set);
3930 InvalidContext = isl_set_coalesce(InvalidContext);
3931 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003932}
3933
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003934void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003935 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00003936 assert((isl_set_is_params(Set) || BB) &&
3937 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003938 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003939}
3940
3941void Scop::addRecordedAssumptions() {
3942 while (!RecordedAssumptions.empty()) {
3943 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003944
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003945 if (!AS.BB) {
3946 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
3947 continue;
3948 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003949
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003950 // If the domain was deleted the assumptions are void.
3951 isl_set *Dom = getDomainConditions(AS.BB);
3952 if (!Dom) {
3953 isl_set_free(AS.Set);
3954 continue;
3955 }
3956
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003957 // If a basic block was given use its domain to simplify the assumption.
3958 // In case of restrictions we know they only have to hold on the domain,
3959 // thus we can intersect them with the domain of the block. However, for
3960 // assumptions the domain has to imply them, thus:
3961 // _ _____
3962 // Dom => S <==> A v B <==> A - B
3963 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003964 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003965 // assumption.
3966 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003967 if (AS.Sign == AS_RESTRICTION)
3968 S = isl_set_params(isl_set_intersect(S, Dom));
3969 else /* (AS.Sign == AS_ASSUMPTION) */
3970 S = isl_set_params(isl_set_subtract(Dom, S));
3971
3972 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003973 }
3974}
3975
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003976void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003977 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003978}
3979
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003980__isl_give isl_set *Scop::getInvalidContext() const {
3981 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003982}
3983
Tobias Grosser75805372011-04-29 06:27:02 +00003984void Scop::printContext(raw_ostream &OS) const {
3985 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003986 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003987
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003988 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003989 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003990
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003991 OS.indent(4) << "Invalid Context:\n";
3992 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003993
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003994 unsigned Dim = 0;
3995 for (const SCEV *Parameter : Parameters)
3996 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003997}
3998
Johannes Doerfertb164c792014-09-18 11:17:17 +00003999void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004000 int noOfGroups = 0;
4001 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004002 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004003 noOfGroups += 1;
4004 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004005 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004006 }
4007
Tobias Grosserbb853c22015-07-25 12:31:03 +00004008 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004009 if (MinMaxAliasGroups.empty()) {
4010 OS.indent(8) << "n/a\n";
4011 return;
4012 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004013
Tobias Grosserbb853c22015-07-25 12:31:03 +00004014 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004015
4016 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004017 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004018 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004019 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004020 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4021 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004022 }
4023 OS << " ]]\n";
4024 }
4025
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004026 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004027 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004028 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004029 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004030 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4031 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004032 }
4033 OS << " ]]\n";
4034 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004035 }
4036}
4037
Tobias Grosser75805372011-04-29 06:27:02 +00004038void Scop::printStatements(raw_ostream &OS) const {
4039 OS << "Statements {\n";
4040
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004041 for (const ScopStmt &Stmt : *this)
4042 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00004043
4044 OS.indent(4) << "}\n";
4045}
4046
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004047void Scop::printArrayInfo(raw_ostream &OS) const {
4048 OS << "Arrays {\n";
4049
Tobias Grosserab671442015-05-23 05:58:27 +00004050 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004051 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004052
4053 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004054
4055 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4056
4057 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004058 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004059
4060 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004061}
4062
Tobias Grosser75805372011-04-29 06:27:02 +00004063void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004064 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004065 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004066 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004067 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004068 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004069 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004070 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004071 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004072 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004073 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004074 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4075 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004076 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004077 }
4078 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004079 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004080 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004081 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00004082 printStatements(OS.indent(4));
4083}
4084
4085void Scop::dump() const { print(dbgs()); }
4086
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004087isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004088
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004089__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4090 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004091 // First try to use the SCEVAffinator to generate a piecewise defined
4092 // affine function from @p E in the context of @p BB. If that tasks becomes to
4093 // complex the affinator might return a nullptr. In such a case we invalidate
4094 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004095 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004096 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004097 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004098 // TODO: We could use a heuristic and either use:
4099 // SCEVAffinator::takeNonNegativeAssumption
4100 // or
4101 // SCEVAffinator::interpretAsUnsigned
4102 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004103 if (NonNegative)
4104 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004105 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004106 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004107
4108 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
4109 invalidate(COMPLEXITY, DL);
4110 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004111}
4112
Tobias Grosser808cd692015-07-14 09:33:13 +00004113__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004114 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004115
Tobias Grosser808cd692015-07-14 09:33:13 +00004116 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004117 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004118
4119 return Domain;
4120}
4121
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004122__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4123 PWACtx PWAC = getPwAff(E, BB);
4124 isl_set_free(PWAC.second);
4125 return PWAC.first;
4126}
4127
Tobias Grossere5a35142015-11-12 14:07:09 +00004128__isl_give isl_union_map *
4129Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4130 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004131
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004132 for (ScopStmt &Stmt : *this) {
4133 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004134 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004135 continue;
4136
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004137 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004138 isl_map *AccessDomain = MA->getAccessRelation();
4139 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004140 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004141 }
4142 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004143 return isl_union_map_coalesce(Accesses);
4144}
4145
4146__isl_give isl_union_map *Scop::getMustWrites() {
4147 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004148}
4149
4150__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004151 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004152}
4153
Tobias Grosser37eb4222014-02-20 21:43:54 +00004154__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004155 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004156}
4157
4158__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004159 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004160}
4161
Tobias Grosser2ac23382015-11-12 14:07:13 +00004162__isl_give isl_union_map *Scop::getAccesses() {
4163 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4164}
4165
Roman Gareevb3224ad2016-09-14 06:26:09 +00004166// Check whether @p Node is an extension node.
4167//
4168// @return true if @p Node is an extension node.
4169isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4170 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4171 return isl_bool_error;
4172 else
4173 return isl_bool_true;
4174}
4175
4176bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4177 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4178 nullptr) == isl_stat_error;
4179}
4180
Tobias Grosser808cd692015-07-14 09:33:13 +00004181__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004182 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004183 if (containsExtensionNode(Tree)) {
4184 isl_schedule_free(Tree);
4185 return nullptr;
4186 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004187 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004188 isl_schedule_free(Tree);
4189 return S;
4190}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004191
Tobias Grosser808cd692015-07-14 09:33:13 +00004192__isl_give isl_schedule *Scop::getScheduleTree() const {
4193 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4194 getDomains());
4195}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004196
Tobias Grosser808cd692015-07-14 09:33:13 +00004197void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4198 auto *S = isl_schedule_from_domain(getDomains());
4199 S = isl_schedule_insert_partial_schedule(
4200 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4201 isl_schedule_free(Schedule);
4202 Schedule = S;
4203}
4204
4205void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4206 isl_schedule_free(Schedule);
4207 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004208}
4209
4210bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4211 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004212 for (ScopStmt &Stmt : *this) {
4213 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004214 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4215 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4216
4217 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4218 isl_union_set_free(StmtDomain);
4219 isl_union_set_free(NewStmtDomain);
4220 continue;
4221 }
4222
4223 Changed = true;
4224
4225 isl_union_set_free(StmtDomain);
4226 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4227
4228 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004229 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004230 isl_union_set_free(NewStmtDomain);
4231 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004232 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004233 }
4234 isl_union_set_free(Domain);
4235 return Changed;
4236}
4237
Tobias Grosser75805372011-04-29 06:27:02 +00004238ScalarEvolution *Scop::getSE() const { return SE; }
4239
Tobias Grosser808cd692015-07-14 09:33:13 +00004240struct MapToDimensionDataTy {
4241 int N;
4242 isl_union_pw_multi_aff *Res;
4243};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004244
Tobias Grosserc80d6972016-09-02 06:33:33 +00004245// Create a function that maps the elements of 'Set' to its N-th dimension and
4246// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004247//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004248// @param Set The input set.
4249// @param User->N The dimension to map to.
4250// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004251//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004252// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004253static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4254 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4255 int Dim;
4256 isl_space *Space;
4257 isl_pw_multi_aff *PMA;
4258
4259 Dim = isl_set_dim(Set, isl_dim_set);
4260 Space = isl_set_get_space(Set);
4261 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4262 Dim - Data->N);
4263 if (Data->N > 1)
4264 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4265 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4266
4267 isl_set_free(Set);
4268
4269 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004270}
4271
Tobias Grosserc80d6972016-09-02 06:33:33 +00004272// Create an isl_multi_union_aff that defines an identity mapping from the
4273// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004274//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004275// # Example:
4276//
4277// Domain: { A[i,j]; B[i,j,k] }
4278// N: 1
4279//
4280// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4281//
4282// @param USet A union set describing the elements for which to generate a
4283// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004284// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004285// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004286static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004287mapToDimension(__isl_take isl_union_set *USet, int N) {
4288 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004289 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004290 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004291
Tobias Grosser808cd692015-07-14 09:33:13 +00004292 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004293
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004294 auto *Space = isl_union_set_get_space(USet);
4295 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004296
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004297 Data = {N, PwAff};
4298
4299 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004300 (void)Res;
4301
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004302 assert(Res == isl_stat_ok);
4303
4304 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004305 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4306}
4307
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004308void Scop::addScopStmt(BasicBlock *BB) {
4309 assert(BB && "Unexpected nullptr!");
4310 Stmts.emplace_back(*this, *BB);
4311 auto *Stmt = &Stmts.back();
4312 StmtMap[BB] = Stmt;
4313}
4314
4315void Scop::addScopStmt(Region *R) {
4316 assert(R && "Unexpected nullptr!");
4317 Stmts.emplace_back(*this, *R);
4318 auto *Stmt = &Stmts.back();
4319 for (BasicBlock *BB : R->blocks())
Tobias Grosser808cd692015-07-14 09:33:13 +00004320 StmtMap[BB] = Stmt;
Tobias Grosser808cd692015-07-14 09:33:13 +00004321}
4322
Roman Gareevb3224ad2016-09-14 06:26:09 +00004323ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4324 __isl_take isl_map *TargetRel,
4325 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004326#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004327 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4328 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4329 assert(isl_set_is_subset(Domain, TargetDomain) &&
4330 "Target access not defined for complete statement domain");
4331 assert(isl_set_is_subset(Domain, SourceDomain) &&
4332 "Source access not defined for complete statement domain");
4333 isl_set_free(SourceDomain);
4334 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004335#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004336 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4337 CopyStmtsNum++;
4338 return &(Stmts.back());
4339}
4340
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004341void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004342 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004343 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004344 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004345 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4346 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004347}
4348
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004349/// To generate a schedule for the elements in a Region we traverse the Region
4350/// in reverse-post-order and add the contained RegionNodes in traversal order
4351/// to the schedule of the loop that is currently at the top of the LoopStack.
4352/// For loop-free codes, this results in a correct sequential ordering.
4353///
4354/// Example:
4355/// bb1(0)
4356/// / \.
4357/// bb2(1) bb3(2)
4358/// \ / \.
4359/// bb4(3) bb5(4)
4360/// \ /
4361/// bb6(5)
4362///
4363/// Including loops requires additional processing. Whenever a loop header is
4364/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4365/// from an empty schedule, we first process all RegionNodes that are within
4366/// this loop and complete the sequential schedule at this loop-level before
4367/// processing about any other nodes. To implement this
4368/// loop-nodes-first-processing, the reverse post-order traversal is
4369/// insufficient. Hence, we additionally check if the traversal yields
4370/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4371/// These region-nodes are then queue and only traverse after the all nodes
4372/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004373void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004374 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004375
4376 ReversePostOrderTraversal<Region *> RTraversal(R);
4377 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4378 std::deque<RegionNode *> DelayList;
4379 bool LastRNWaiting = false;
4380
4381 // Iterate over the region @p R in reverse post-order but queue
4382 // sub-regions/blocks iff they are not part of the last encountered but not
4383 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4384 // that we queued the last sub-region/block from the reverse post-order
4385 // iterator. If it is set we have to explore the next sub-region/block from
4386 // the iterator (if any) to guarantee progress. If it is not set we first try
4387 // the next queued sub-region/blocks.
4388 while (!WorkList.empty() || !DelayList.empty()) {
4389 RegionNode *RN;
4390
4391 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4392 RN = WorkList.front();
4393 WorkList.pop_front();
4394 LastRNWaiting = false;
4395 } else {
4396 RN = DelayList.front();
4397 DelayList.pop_front();
4398 }
4399
4400 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004401 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004402 L = OuterScopLoop;
4403
Tobias Grosser151ae322016-04-03 19:36:52 +00004404 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004405 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004406 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004407 LastRNWaiting = true;
4408 DelayList.push_back(RN);
4409 continue;
4410 }
4411 LoopStack.push_back({L, nullptr, 0});
4412 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004413 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004414 }
4415
4416 return;
4417}
4418
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004419void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004420
Tobias Grosser8362c262016-01-06 15:30:06 +00004421 if (RN->isSubRegion()) {
4422 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004423 if (!isNonAffineSubRegion(LocalRegion)) {
4424 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004425 return;
4426 }
4427 }
Michael Kruse046dde42015-08-10 13:01:57 +00004428
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004429 auto &LoopData = LoopStack.back();
4430 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004431
Michael Kruse6f7721f2016-02-24 22:08:19 +00004432 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004433 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4434 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004435 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004436 }
4437
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004438 // Check if we just processed the last node in this loop. If we did, finalize
4439 // the loop by:
4440 //
4441 // - adding new schedule dimensions
4442 // - folding the resulting schedule into the parent loop schedule
4443 // - dropping the loop schedule from the LoopStack.
4444 //
4445 // Then continue to check surrounding loops, which might also have been
4446 // completed by this node.
4447 while (LoopData.L &&
4448 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004449 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004450 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004451
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004452 LoopStack.pop_back();
4453 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004454
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004455 if (Schedule) {
4456 auto *Domain = isl_schedule_get_domain(Schedule);
4457 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4458 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4459 NextLoopData.Schedule =
4460 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004461 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004462
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004463 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4464 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004465 }
Tobias Grosser75805372011-04-29 06:27:02 +00004466}
4467
Michael Kruse6f7721f2016-02-24 22:08:19 +00004468ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004469 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004470 if (StmtMapIt == StmtMap.end())
4471 return nullptr;
4472 return StmtMapIt->second;
4473}
4474
Michael Kruse6f7721f2016-02-24 22:08:19 +00004475ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4476 if (RN->isSubRegion())
4477 return getStmtFor(RN->getNodeAs<Region>());
4478 return getStmtFor(RN->getNodeAs<BasicBlock>());
4479}
4480
4481ScopStmt *Scop::getStmtFor(Region *R) const {
4482 ScopStmt *Stmt = getStmtFor(R->getEntry());
4483 assert(!Stmt || Stmt->getRegion() == R);
4484 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004485}
4486
Johannes Doerfert96425c22015-08-30 21:13:53 +00004487int Scop::getRelativeLoopDepth(const Loop *L) const {
4488 Loop *OuterLoop =
4489 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4490 if (!OuterLoop)
4491 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004492 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4493}
4494
Roman Gareevd7754a12016-07-30 09:25:51 +00004495ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4496 for (auto &SAI : arrays()) {
4497 if (SAI->getName() == BaseName)
4498 return SAI;
4499 }
4500 return nullptr;
4501}
4502
Johannes Doerfert99191c72016-05-31 09:41:04 +00004503//===----------------------------------------------------------------------===//
4504void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4505 AU.addRequired<LoopInfoWrapperPass>();
4506 AU.addRequired<RegionInfoPass>();
4507 AU.addRequired<DominatorTreeWrapperPass>();
4508 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4509 AU.addRequiredTransitive<ScopDetection>();
4510 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004511 AU.setPreservesAll();
4512}
4513
4514bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4515 auto &SD = getAnalysis<ScopDetection>();
4516
4517 if (!SD.isMaxRegionInScop(*R))
4518 return false;
4519
4520 Function *F = R->getEntry()->getParent();
4521 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4522 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4523 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4524 auto const &DL = F->getParent()->getDataLayout();
4525 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004526
Michael Kruse7037fde2016-12-15 09:25:14 +00004527 ScopBuilder SB(R, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004528 S = SB.getScop(); // take ownership of scop object
Tobias Grosser75805372011-04-29 06:27:02 +00004529 return false;
4530}
4531
Johannes Doerfert99191c72016-05-31 09:41:04 +00004532void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004533 if (S)
4534 S->print(OS);
4535 else
4536 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004537}
Tobias Grosser75805372011-04-29 06:27:02 +00004538
Johannes Doerfert99191c72016-05-31 09:41:04 +00004539char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004540
Johannes Doerfert99191c72016-05-31 09:41:04 +00004541Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4542
4543INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004544 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004545 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004546INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00004547INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004548INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004549INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004550INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004551INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004552INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004553 "Polly - Create polyhedral description of Scops", false,
4554 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004555
4556//===----------------------------------------------------------------------===//
4557void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4558 AU.addRequired<LoopInfoWrapperPass>();
4559 AU.addRequired<RegionInfoPass>();
4560 AU.addRequired<DominatorTreeWrapperPass>();
4561 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4562 AU.addRequiredTransitive<ScopDetection>();
4563 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004564 AU.setPreservesAll();
4565}
4566
4567bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4568 auto &SD = getAnalysis<ScopDetection>();
4569
4570 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4571 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4572 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4573 auto const &DL = F.getParent()->getDataLayout();
4574 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004575
4576 /// Create polyhedral descripton of scops for all the valid regions of a
4577 /// function.
4578 for (auto &It : SD) {
4579 Region *R = const_cast<Region *>(It);
4580 if (!SD.isMaxRegionInScop(*R))
4581 continue;
4582
Michael Kruse7037fde2016-12-15 09:25:14 +00004583 ScopBuilder SB(R, AA, DL, DT, LI, SD, SE);
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004584 std::unique_ptr<Scop> S = SB.getScop();
4585 if (!S)
4586 continue;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004587 bool Inserted =
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004588 RegionToScopMap.insert(std::make_pair(R, std::move(S))).second;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004589 assert(Inserted && "Building Scop for the same region twice!");
4590 (void)Inserted;
4591 }
4592 return false;
4593}
4594
4595void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4596 for (auto &It : RegionToScopMap) {
4597 if (It.second)
4598 It.second->print(OS);
4599 else
4600 OS << "Invalid Scop!\n";
4601 }
4602}
4603
4604char ScopInfoWrapperPass::ID = 0;
4605
4606Pass *polly::createScopInfoWrapperPassPass() {
4607 return new ScopInfoWrapperPass();
4608}
4609
4610INITIALIZE_PASS_BEGIN(
4611 ScopInfoWrapperPass, "polly-function-scops",
4612 "Polly - Create polyhedral description of all Scops of a function", false,
4613 false);
4614INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004615INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4616INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4617INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4618INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4619INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4620INITIALIZE_PASS_END(
4621 ScopInfoWrapperPass, "polly-function-scops",
4622 "Polly - Create polyhedral description of all Scops of a function", false,
4623 false)