blob: 473eee23a0011afdd7ed7cf82bc45d365e484201 [file] [log] [blame]
Michael Kruse2133cb92016-06-28 01:37:20 +00001//===--------- ScopInfo.cpp ----------------------------------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser5624d3c2015-12-21 12:38:56 +000020#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000021#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000022#include "polly/Options.h"
Michael Kruse73fa33b2016-06-28 01:37:28 +000023#include "polly/ScopBuilder.h"
Tobias Grosser75805372011-04-29 06:27:02 +000024#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000025#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000026#include "polly/Support/ScopHelper.h"
Tobias Grosser9737c7b2015-11-22 11:06:51 +000027#include "llvm/ADT/DepthFirstIterator.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000028#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000029#include "llvm/ADT/PostOrderIterator.h"
30#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000031#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000032#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000033#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000034#include "llvm/Analysis/AliasAnalysis.h"
Johannes Doerfert2af10e22015-11-12 03:25:01 +000035#include "llvm/Analysis/AssumptionCache.h"
Johannes Doerfert1dc12af2016-04-23 12:59:18 +000036#include "llvm/Analysis/Loads.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000037#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000038#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000039#include "llvm/Analysis/RegionIterator.h"
40#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000041#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000042#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000043#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000045#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000047#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000048#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000049#include "isl/schedule.h"
50#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000051#include "isl/set.h"
52#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000053#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000054#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000055#include <sstream>
56#include <string>
57#include <vector>
58
59using namespace llvm;
60using namespace polly;
61
Chandler Carruth95fef942014-04-22 03:30:19 +000062#define DEBUG_TYPE "polly-scops"
63
Tobias Grosser75dc40c2015-12-20 13:31:48 +000064// The maximal number of basic sets we allow during domain construction to
65// be created. More complex scops will result in very high compile time and
66// are also unlikely to result in good code
Michael Krusebc150122016-05-02 12:25:18 +000067static int const MaxDisjunctionsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +000068
Johannes Doerfert2f705842016-04-12 16:09:44 +000069static cl::opt<bool> PollyRemarksMinimal(
70 "polly-remarks-minimal",
71 cl::desc("Do not emit remarks about assumptions that are known"),
72 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
73
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000074// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000075// operations can overflow easily. Additive reductions and bit operations
76// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000077static cl::opt<bool> DisableMultiplicativeReductions(
78 "polly-disable-multiplicative-reductions",
79 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
80 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000081
Johannes Doerfert9143d672014-09-27 11:02:39 +000082static cl::opt<unsigned> RunTimeChecksMaxParameters(
83 "polly-rtc-max-parameters",
84 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
85 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
86
Tobias Grosser71500722015-03-28 15:11:14 +000087static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
88 "polly-rtc-max-arrays-per-group",
89 cl::desc("The maximal number of arrays to compare in each alias group."),
90 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +000091
Tobias Grosser8a9c2352015-08-16 10:19:29 +000092static cl::opt<std::string> UserContextStr(
93 "polly-context", cl::value_desc("isl parameter set"),
94 cl::desc("Provide additional constraints on the context parameters"),
95 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000096
Tobias Grosserd83b8a82015-08-20 19:08:11 +000097static cl::opt<bool> DetectReductions("polly-detect-reductions",
98 cl::desc("Detect and exploit reductions"),
99 cl::Hidden, cl::ZeroOrMore,
100 cl::init(true), cl::cat(PollyCategory));
101
Tobias Grosser2937b592016-04-29 11:43:20 +0000102static cl::opt<bool>
103 IslOnErrorAbort("polly-on-isl-error-abort",
104 cl::desc("Abort if an isl error is encountered"),
105 cl::init(true), cl::cat(PollyCategory));
106
Michael Kruse6ab44762016-10-04 17:33:39 +0000107static cl::opt<bool> UnprofitableScalarAccs(
108 "polly-unprofitable-scalar-accs",
109 cl::desc("Count statements with scalar accesses as not optimizable"),
110 cl::Hidden, cl::init(true), cl::cat(PollyCategory));
111
Michael Kruse7bf39442015-09-10 12:46:52 +0000112//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000113
Michael Kruse046dde42015-08-10 13:01:57 +0000114// Create a sequence of two schedules. Either argument may be null and is
115// interpreted as the empty schedule. Can also return null if both schedules are
116// empty.
117static __isl_give isl_schedule *
118combineInSequence(__isl_take isl_schedule *Prev,
119 __isl_take isl_schedule *Succ) {
120 if (!Prev)
121 return Succ;
122 if (!Succ)
123 return Prev;
124
125 return isl_schedule_sequence(Prev, Succ);
126}
127
Johannes Doerferte7044942015-02-24 11:58:30 +0000128static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
129 const ConstantRange &Range,
130 int dim,
131 enum isl_dim_type type) {
132 isl_val *V;
133 isl_ctx *ctx = isl_set_get_ctx(S);
134
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000135 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
136 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000137 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000138 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
139
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000140 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000141 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000142 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000143 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000144 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
145
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000146 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000147 return isl_set_union(SLB, SUB);
148 else
149 return isl_set_intersect(SLB, SUB);
150}
151
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000152static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
153 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
154 if (!BasePtrLI)
155 return nullptr;
156
Johannes Doerfert952b5302016-05-23 12:40:48 +0000157 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000158 return nullptr;
159
160 ScalarEvolution &SE = *S->getSE();
161
162 auto *OriginBaseSCEV =
163 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
164 if (!OriginBaseSCEV)
165 return nullptr;
166
167 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
168 if (!OriginBaseSCEVUnknown)
169 return nullptr;
170
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000171 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000172 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000173}
174
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000175ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000176 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000177 const DataLayout &DL, Scop *S,
178 const char *BaseName)
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000179 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000180 std::string BasePtrName =
Roman Gareevd7754a12016-07-30 09:25:51 +0000181 BaseName ? BaseName : getIslCompatibleName("MemRef_", BasePtr,
182 Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000183 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000184
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000185 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000186
Michael Kruseca7cbcc2016-10-04 17:33:34 +0000187 if (!BasePtr || Kind != MK_Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000188 BasePtrOriginSAI = nullptr;
189 return;
190 }
191
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000192 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
193 if (BasePtrOriginSAI)
194 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000195}
196
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000197__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000198 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000199 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
200 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
201 return Space;
202}
203
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000204bool ScopArrayInfo::isReadOnly() {
205 isl_union_set *WriteSet = isl_union_map_range(S.getWrites());
206 isl_space *Space = getSpace();
207 WriteSet = isl_union_set_intersect(
208 WriteSet, isl_union_set_from_set(isl_set_universe(Space)));
209
210 bool IsReadOnly = isl_union_set_is_empty(WriteSet);
211 isl_union_set_free(WriteSet);
212
213 return IsReadOnly;
214}
215
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000216void ScopArrayInfo::updateElementType(Type *NewElementType) {
217 if (NewElementType == ElementType)
218 return;
219
Tobias Grosserd840fc72016-02-04 13:18:42 +0000220 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
221 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
222
Johannes Doerferta7920982016-02-25 14:08:48 +0000223 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000224 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000225
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000226 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
227 ElementType = NewElementType;
228 } else {
229 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
230 ElementType = IntegerType::get(ElementType->getContext(), GCD);
231 }
232}
233
234bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000235 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
236 int ExtraDimsNew = NewSizes.size() - SharedDims;
237 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000238
239 for (int i = 0; i < SharedDims; i++) {
Michael Kruse19c9d992016-09-13 09:56:05 +0000240 auto *NewSize = NewSizes[i + ExtraDimsNew];
241 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
Roman Gareevf5aff702016-09-12 17:08:31 +0000242 if (NewSize && KnownSize && NewSize != KnownSize)
Tobias Grosser8286b832015-11-02 11:29:32 +0000243 return false;
Roman Gareevf5aff702016-09-12 17:08:31 +0000244 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000245
246 if (DimensionSizes.size() >= NewSizes.size())
247 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000248
249 DimensionSizes.clear();
250 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
251 NewSizes.end());
252 for (isl_pw_aff *Size : DimensionSizesPw)
253 isl_pw_aff_free(Size);
254 DimensionSizesPw.clear();
255 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000256 if (!Expr) {
257 DimensionSizesPw.push_back(nullptr);
258 continue;
259 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000260 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000261 DimensionSizesPw.push_back(Size);
262 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000263 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000264}
265
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000266ScopArrayInfo::~ScopArrayInfo() {
267 isl_id_free(Id);
268 for (isl_pw_aff *Size : DimensionSizesPw)
269 isl_pw_aff_free(Size);
270}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000271
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000272std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
273
274int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000275 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000276}
277
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000278__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
279 return isl_id_copy(Id);
280}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000281
282void ScopArrayInfo::dump() const { print(errs()); }
283
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000284void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000285 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000286 unsigned u = 0;
287 if (getNumberOfDimensions() > 0 && !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000288 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000289 u++;
290 }
291 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000292 OS << "[";
293
Tobias Grosser26253842015-11-10 14:24:21 +0000294 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000295 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000296 OS << " " << Size << " ";
297 isl_pw_aff_free(Size);
298 } else {
299 OS << *getDimensionSize(u);
300 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000301
302 OS << "]";
303 }
304
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000305 OS << ";";
306
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000307 if (BasePtrOriginSAI)
308 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
309
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000310 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000311}
312
313const ScopArrayInfo *
314ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
315 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
316 assert(Id && "Output dimension didn't have an ID");
317 return getFromId(Id);
318}
319
Michael Krused56b90a2016-09-01 09:03:27 +0000320const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000321 void *User = isl_id_get_user(Id);
322 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
323 isl_id_free(Id);
324 return SAI;
325}
326
Michael Kruse3b425ff2016-04-11 14:34:08 +0000327void MemoryAccess::wrapConstantDimensions() {
328 auto *SAI = getScopArrayInfo();
329 auto *ArraySpace = SAI->getSpace();
330 auto *Ctx = isl_space_get_ctx(ArraySpace);
331 unsigned DimsArray = SAI->getNumberOfDimensions();
332
333 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
334 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
335 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
336
337 // Begin with last dimension, to iteratively carry into higher dimensions.
338 for (int i = DimsArray - 1; i > 0; i--) {
339 auto *DimSize = SAI->getDimensionSize(i);
340 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
341
342 // This transformation is not applicable to dimensions with dynamic size.
343 if (!DimSizeCst)
344 continue;
345
346 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
347 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
348 isl_dim_set, i);
349 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
350 isl_dim_set, i - 1);
351
352 // Compute: index % size
353 // Modulo must apply in the divide of the previous iteration, if any.
354 auto *Modulo = isl_aff_copy(Var);
355 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
356 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
357
358 // Compute: floor(index / size)
359 auto *Divide = Var;
360 Divide = isl_aff_div(
361 Divide,
362 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
363 Divide = isl_aff_floor(Divide);
364 Divide = isl_aff_add(Divide, PrevVar);
365 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
366
367 // Apply Modulo and Divide.
368 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
369 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
370 }
371
372 // Apply all modulo/divides on the accesses.
373 AccessRelation =
374 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
375 AccessRelation = isl_map_detect_equalities(AccessRelation);
376 isl_local_space_free(LArraySpace);
377}
378
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000379void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000380 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000381 auto *ArraySpace = SAI->getSpace();
382 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000383 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000384
385 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
386 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
387 auto DimsMissing = DimsArray - DimsAccess;
388
Michael Kruse375cb5f2016-02-24 22:08:24 +0000389 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000390 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000391 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000392 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000393
Johannes Doerferta90943d2016-02-21 16:37:25 +0000394 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000395 isl_set_universe(AccessSpace),
396 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000397
398 for (unsigned i = 0; i < DimsMissing; i++)
399 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
400
401 for (unsigned i = DimsMissing; i < DimsArray; i++)
402 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
403
404 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000405
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000406 // For the non delinearized arrays, divide the access function of the last
407 // subscript by the size of the elements in the array.
408 //
409 // A stride one array access in C expressed as A[i] is expressed in
410 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
411 // two subsequent values of 'i' index two values that are stored next to
412 // each other in memory. By this division we make this characteristic
413 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000414 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000415 // that divides the offsets of all accesses to this base pointer.
416 if (DimsAccess == 1) {
417 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
418 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
419 }
420
Michael Kruse3b425ff2016-04-11 14:34:08 +0000421 // We currently do this only if we added at least one dimension, which means
422 // some dimension's indices have not been specified, an indicator that some
423 // index values have been added together.
424 // TODO: Investigate general usefulness; Effect on unit tests is to make index
425 // expressions more complicated.
426 if (DimsMissing)
427 wrapConstantDimensions();
428
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000429 if (!isAffine())
430 computeBoundsOnAccessRelation(ArrayElemSize);
431
Tobias Grosserd840fc72016-02-04 13:18:42 +0000432 // Introduce multi-element accesses in case the type loaded by this memory
433 // access is larger than the canonical element type of the array.
434 //
435 // An access ((float *)A)[i] to an array char *A is modeled as
436 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000437 if (ElemBytes > ArrayElemSize) {
438 assert(ElemBytes % ArrayElemSize == 0 &&
439 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000440 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000441 isl_set_universe(isl_space_copy(ArraySpace)),
442 isl_set_universe(isl_space_copy(ArraySpace)));
443 for (unsigned i = 0; i < DimsArray - 1; i++)
444 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
445
Tobias Grosserd840fc72016-02-04 13:18:42 +0000446 isl_constraint *C;
447 isl_local_space *LS;
448
449 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000450 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
451
452 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
453 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000454 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000455 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
456 Map = isl_map_add_constraint(Map, C);
457
458 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000459 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000460 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
461 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
462 Map = isl_map_add_constraint(Map, C);
463 AccessRelation = isl_map_apply_range(AccessRelation, Map);
464 }
465
466 isl_space_free(ArraySpace);
467
Roman Gareev10595a12016-01-08 14:01:59 +0000468 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000469}
470
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000471const std::string
472MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
473 switch (RT) {
474 case MemoryAccess::RT_NONE:
475 llvm_unreachable("Requested a reduction operator string for a memory "
476 "access which isn't a reduction");
477 case MemoryAccess::RT_ADD:
478 return "+";
479 case MemoryAccess::RT_MUL:
480 return "*";
481 case MemoryAccess::RT_BOR:
482 return "|";
483 case MemoryAccess::RT_BXOR:
484 return "^";
485 case MemoryAccess::RT_BAND:
486 return "&";
487 }
488 llvm_unreachable("Unknown reduction type");
489 return "";
490}
491
Tobias Grosserc80d6972016-09-02 06:33:33 +0000492/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000493static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
494 const Instruction *Load) {
495 if (!BinOp)
496 return MemoryAccess::RT_NONE;
497 switch (BinOp->getOpcode()) {
498 case Instruction::FAdd:
499 if (!BinOp->hasUnsafeAlgebra())
500 return MemoryAccess::RT_NONE;
501 // Fall through
502 case Instruction::Add:
503 return MemoryAccess::RT_ADD;
504 case Instruction::Or:
505 return MemoryAccess::RT_BOR;
506 case Instruction::Xor:
507 return MemoryAccess::RT_BXOR;
508 case Instruction::And:
509 return MemoryAccess::RT_BAND;
510 case Instruction::FMul:
511 if (!BinOp->hasUnsafeAlgebra())
512 return MemoryAccess::RT_NONE;
513 // Fall through
514 case Instruction::Mul:
515 if (DisableMultiplicativeReductions)
516 return MemoryAccess::RT_NONE;
517 return MemoryAccess::RT_MUL;
518 default:
519 return MemoryAccess::RT_NONE;
520 }
521}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000522
Tobias Grosser75805372011-04-29 06:27:02 +0000523MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000524 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000525 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000526 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000527 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000528}
529
Michael Kruse2fa35192016-09-01 19:53:31 +0000530const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000531 isl_id *ArrayId = getArrayId();
532 void *User = isl_id_get_user(ArrayId);
533 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
534 isl_id_free(ArrayId);
535 return SAI;
536}
537
Michael Kruse2fa35192016-09-01 19:53:31 +0000538const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
539 isl_id *ArrayId = getLatestArrayId();
540 void *User = isl_id_get_user(ArrayId);
541 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
542 isl_id_free(ArrayId);
543 return SAI;
544}
545
546__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000547 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
548}
549
Michael Kruse2fa35192016-09-01 19:53:31 +0000550__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
551 if (!hasNewAccessRelation())
552 return getOriginalArrayId();
553 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
554}
555
Tobias Grosserd840fc72016-02-04 13:18:42 +0000556__isl_give isl_map *MemoryAccess::getAddressFunction() const {
557 return isl_map_lexmin(getAccessRelation());
558}
559
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000560__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
561 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000562 isl_map *Schedule, *ScheduledAccRel;
563 isl_union_set *UDomain;
564
565 UDomain = isl_union_set_from_set(getStatement()->getDomain());
566 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
567 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000568 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000569 return isl_pw_multi_aff_from_map(ScheduledAccRel);
570}
571
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000572__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000573 return isl_map_copy(AccessRelation);
574}
575
Johannes Doerferta99130f2014-10-13 12:58:03 +0000576std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000577 return stringFromIslObj(AccessRelation);
578}
579
Johannes Doerferta99130f2014-10-13 12:58:03 +0000580__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000581 return isl_map_get_space(AccessRelation);
582}
583
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000584__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000585 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000586}
587
Tobias Grosser6f730082015-09-05 07:46:47 +0000588std::string MemoryAccess::getNewAccessRelationStr() const {
589 return stringFromIslObj(NewAccessRelation);
590}
591
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000592__isl_give isl_basic_map *
593MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000594 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000595 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000596
Tobias Grosser084d8f72012-05-29 09:29:44 +0000597 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000598 isl_basic_set_universe(Statement->getDomainSpace()),
599 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000600}
601
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000602// Formalize no out-of-bound access assumption
603//
604// When delinearizing array accesses we optimistically assume that the
605// delinearized accesses do not access out of bound locations (the subscript
606// expression of each array evaluates for each statement instance that is
607// executed to a value that is larger than zero and strictly smaller than the
608// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000609// dimension for which we do not need to assume any upper bound. At this point
610// we formalize this assumption to ensure that at code generation time the
611// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000612//
613// To find the set of constraints necessary to avoid out of bound accesses, we
614// first build the set of data locations that are not within array bounds. We
615// then apply the reverse access relation to obtain the set of iterations that
616// may contain invalid accesses and reduce this set of iterations to the ones
617// that are actually executed by intersecting them with the domain of the
618// statement. If we now project out all loop dimensions, we obtain a set of
619// parameters that may cause statement instances to be executed that may
620// possibly yield out of bound memory accesses. The complement of these
621// constraints is the set of constraints that needs to be assumed to ensure such
622// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000623void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000624 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000625 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000626 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000627 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000628 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
629 isl_pw_aff *Var =
630 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
631 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
632
633 isl_set *DimOutside;
634
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000635 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000636 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000637 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
638 isl_space_dim(Space, isl_dim_set));
639 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
640 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000641
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000642 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000643
644 Outside = isl_set_union(Outside, DimOutside);
645 }
646
647 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
648 Outside = isl_set_intersect(Outside, Statement->getDomain());
649 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000650
651 // Remove divs to avoid the construction of overly complicated assumptions.
652 // Doing so increases the set of parameter combinations that are assumed to
653 // not appear. This is always save, but may make the resulting run-time check
654 // bail out more often than strictly necessary.
655 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000656 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000657 const auto &Loc = getAccessInstruction()
658 ? getAccessInstruction()->getDebugLoc()
659 : DebugLoc();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000660 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
661 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000662 isl_space_free(Space);
663}
664
Johannes Doerfertcea61932016-02-21 19:13:19 +0000665void MemoryAccess::buildMemIntrinsicAccessRelation() {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000666 assert(isa<MemIntrinsic>(getAccessInstruction()));
Roman Gareevf5aff702016-09-12 17:08:31 +0000667 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000668
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000669 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000670 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000671
672 isl_map *LengthMap;
673 if (Subscripts[1] == nullptr) {
674 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
675 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000676 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000677 LengthMap = isl_map_from_pw_aff(LengthPWA);
678 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
679 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
680 }
681 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
682 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000683 SubscriptMap =
684 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000685 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
686 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
687 getStatement()->getDomainId());
688}
689
Johannes Doerferte7044942015-02-24 11:58:30 +0000690void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
691 ScalarEvolution *SE = Statement->getParent()->getSE();
692
Johannes Doerfertcea61932016-02-21 19:13:19 +0000693 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000694 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000695 return;
696
697 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000698 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
699 return;
700
701 auto *PtrSCEV = SE->getSCEV(Ptr);
702 if (isa<SCEVCouldNotCompute>(PtrSCEV))
703 return;
704
705 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
706 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
707 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
708
709 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
710 if (Range.isFullSet())
711 return;
712
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000713 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000714 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000715 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000716 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000717 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000718
719 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000720 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000721
722 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
723 AccessRange =
724 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
725 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
726}
727
Michael Krusee2bccbb2015-09-18 19:59:43 +0000728__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000729 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000730 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000731
732 for (int i = Size - 2; i >= 0; --i) {
733 isl_space *Space;
734 isl_map *MapOne, *MapTwo;
Roman Gareevf5aff702016-09-12 17:08:31 +0000735 isl_pw_aff *DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000736
737 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
738 isl_pw_aff_free(DimSize);
739 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
740
741 Space = isl_map_get_space(AccessRelation);
742 Space = isl_space_map_from_set(isl_space_range(Space));
743 Space = isl_space_align_params(Space, SpaceSize);
744
745 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
746 isl_id_free(ParamId);
747
748 MapOne = isl_map_universe(isl_space_copy(Space));
749 for (int j = 0; j < Size; ++j)
750 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
751 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
752
753 MapTwo = isl_map_universe(isl_space_copy(Space));
754 for (int j = 0; j < Size; ++j)
755 if (j < i || j > i + 1)
756 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
757
758 isl_local_space *LS = isl_local_space_from_space(Space);
759 isl_constraint *C;
760 C = isl_equality_alloc(isl_local_space_copy(LS));
761 C = isl_constraint_set_constant_si(C, -1);
762 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
763 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
764 MapTwo = isl_map_add_constraint(MapTwo, C);
765 C = isl_equality_alloc(LS);
766 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
767 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
768 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
769 MapTwo = isl_map_add_constraint(MapTwo, C);
770 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
771
772 MapOne = isl_map_union(MapOne, MapTwo);
773 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
774 }
775 return AccessRelation;
776}
777
Tobias Grosserc80d6972016-09-02 06:33:33 +0000778/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000779static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000780 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000781 if (Size == 1)
782 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000783
784 // Only one factor needs to be divisible.
785 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
786 for (auto *FactorExpr : MulExpr->operands())
787 if (isDivisible(FactorExpr, Size, SE))
788 return true;
789 return false;
790 }
791
792 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
793 // to be divisble.
794 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
795 for (auto *OpExpr : NAryExpr->operands())
796 if (!isDivisible(OpExpr, Size, SE))
797 return false;
798 return true;
799 }
800
801 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
802 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
803 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
804 return MulSCEV == Expr;
805}
806
Michael Krusee2bccbb2015-09-18 19:59:43 +0000807void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
808 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000809
Johannes Doerfert85676e32016-04-23 14:32:34 +0000810 // Initialize the invalid domain which describes all iterations for which the
811 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000812 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
813 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
814 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000815
Michael Krusee2bccbb2015-09-18 19:59:43 +0000816 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000817 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000818
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000819 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
820 buildMemIntrinsicAccessRelation();
821 AccessRelation =
822 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
823 return;
824 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000825
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000826 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000827 // We overapproximate non-affine accesses with a possible access to the
828 // whole array. For read accesses it does not make a difference, if an
829 // access must or may happen. However, for write accesses it is important to
830 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000831 if (!AccessRelation)
832 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
833
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000834 AccessRelation =
835 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000836 return;
837 }
838
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000839 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000840 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000841
Michael Krusee2bccbb2015-09-18 19:59:43 +0000842 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000843 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000844 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000845 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000846 }
847
Roman Gareevf5aff702016-09-12 17:08:31 +0000848 if (Sizes.size() >= 2 && !isa<SCEVConstant>(Sizes[1]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000849 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000850
Tobias Grosser79baa212014-04-10 08:38:02 +0000851 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000852 AccessRelation = isl_map_set_tuple_id(
853 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000854 AccessRelation =
855 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
856
Tobias Grosseraa660a92015-03-30 00:07:50 +0000857 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000858 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000859}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000860
Michael Krusecac948e2015-10-02 13:53:07 +0000861MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000862 AccessType AccType, Value *BaseAddress,
863 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000864 ArrayRef<const SCEV *> Subscripts,
865 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000866 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000867 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Johannes Doerfert85676e32016-04-23 14:32:34 +0000868 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
869 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()),
870 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000871 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000872 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000873 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000874 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000875
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000876 std::string IdName =
877 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000878 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
879}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000880
Roman Gareevb3224ad2016-09-14 06:26:09 +0000881MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
882 __isl_take isl_map *AccRel)
883 : Kind(ScopArrayInfo::MemoryKind::MK_Array), AccType(AccType),
884 RedType(RT_NONE), Statement(Stmt), InvalidDomain(nullptr),
885 AccessInstruction(nullptr), IsAffine(true), AccessRelation(nullptr),
886 NewAccessRelation(AccRel) {
887 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
888 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
889 Sizes.push_back(nullptr);
890 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
891 Sizes.push_back(SAI->getDimensionSize(i));
892 ElementType = SAI->getElementType();
893 BaseAddr = SAI->getBasePtr();
894 BaseName = SAI->getName();
895 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
896 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
897
898 std::string IdName =
899 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
900 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
901}
902
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000903void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +0000904 auto *Ctx = Statement->getParent()->getContext();
905 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
906 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +0000907}
908
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000909const std::string MemoryAccess::getReductionOperatorStr() const {
910 return MemoryAccess::getReductionOperatorStr(getReductionType());
911}
912
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000913__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
914
Johannes Doerfertf6183392014-07-01 20:52:51 +0000915raw_ostream &polly::operator<<(raw_ostream &OS,
916 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000917 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000918 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000919 else
920 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000921 return OS;
922}
923
Tobias Grosser75805372011-04-29 06:27:02 +0000924void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000925 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000926 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000927 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000928 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000929 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000930 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000931 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000932 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000933 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000934 break;
935 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000936 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000937 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000938 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000939 if (hasNewAccessRelation())
940 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000941}
942
Tobias Grosser74394f02013-01-14 22:40:23 +0000943void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000944
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000945__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
946 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000947 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +0000948 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
949 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
950 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000951 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000952}
953
Tobias Grosser75805372011-04-29 06:27:02 +0000954// Create a map in the size of the provided set domain, that maps from the
955// one element of the provided set domain to another element of the provided
956// set domain.
957// The mapping is limited to all points that are equal in all but the last
958// dimension and for which the last dimension of the input is strict smaller
959// than the last dimension of the output.
960//
961// getEqualAndLarger(set[i0, i1, ..., iX]):
962//
963// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
964// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
965//
Tobias Grosser2a526fe2016-09-08 11:18:56 +0000966static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000967 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000968 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000969 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000970
971 // Set all but the last dimension to be equal for the input and output
972 //
973 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
974 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000975 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000976 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000977
978 // Set the last dimension of the input to be strict smaller than the
979 // last dimension of the output.
980 //
981 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000982 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
983 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000984 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000985}
986
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000987__isl_give isl_set *
988MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000989 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000990 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000991 isl_space *Space = isl_space_range(isl_map_get_space(S));
992 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000993
Sebastian Popa00a0292012-12-18 07:46:06 +0000994 S = isl_map_reverse(S);
995 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000996
Sebastian Popa00a0292012-12-18 07:46:06 +0000997 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
998 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
999 NextScatt = isl_map_apply_domain(NextScatt, S);
1000 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001001
Sebastian Popa00a0292012-12-18 07:46:06 +00001002 isl_set *Deltas = isl_map_deltas(NextScatt);
1003 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001004}
1005
Sebastian Popa00a0292012-12-18 07:46:06 +00001006bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001007 int StrideWidth) const {
1008 isl_set *Stride, *StrideX;
1009 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001010
Sebastian Popa00a0292012-12-18 07:46:06 +00001011 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001012 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001013 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1014 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1015 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1016 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001017 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001018
Tobias Grosser28dd4862012-01-24 16:42:16 +00001019 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001020 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001021
Tobias Grosser28dd4862012-01-24 16:42:16 +00001022 return IsStrideX;
1023}
1024
Michael Krused56b90a2016-09-01 09:03:27 +00001025bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001026 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001027}
1028
Michael Krused56b90a2016-09-01 09:03:27 +00001029bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001030 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001031}
1032
Michael Krused56b90a2016-09-01 09:03:27 +00001033void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001034 assert(NewAccess);
1035
1036#ifndef NDEBUG
1037 // Check domain space compatibility.
1038 auto *NewSpace = isl_map_get_space(NewAccess);
1039 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1040 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1041 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1042 isl_space_free(NewDomainSpace);
1043 isl_space_free(OriginalDomainSpace);
1044
1045 // Check whether there is an access for every statement instance.
1046 auto *StmtDomain = getStatement()->getDomain();
1047 StmtDomain = isl_set_intersect_params(
1048 StmtDomain, getStatement()->getParent()->getContext());
1049 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1050 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1051 "Partial accesses not supported");
1052 isl_set_free(NewDomain);
1053 isl_set_free(StmtDomain);
1054
1055 // Check whether access dimensions correspond to number of dimensions of the
1056 // accesses array.
1057 auto *NewAccessSpace = isl_space_range(NewSpace);
1058 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1059 "Must specify the array that is accessed");
1060 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1061 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1062 assert(SAI && "Must set a ScopArrayInfo");
1063 assert(!SAI->getBasePtrOriginSAI() &&
1064 "Indirect array not supported by codegen");
1065 auto Dims = SAI->getNumberOfDimensions();
1066 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1067 "Access dims must match array dims");
1068 isl_space_free(NewAccessSpace);
1069 isl_id_free(NewArrayId);
1070#endif
1071
Tobias Grosser166c4222015-09-05 07:46:40 +00001072 isl_map_free(NewAccessRelation);
1073 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001074}
Tobias Grosser75805372011-04-29 06:27:02 +00001075
1076//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001077
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001078__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001079 isl_set *Domain = getDomain();
1080 if (isl_set_is_empty(Domain)) {
1081 isl_set_free(Domain);
1082 return isl_map_from_aff(
1083 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1084 }
1085 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001086 if (!Schedule) {
1087 isl_set_free(Domain);
1088 return nullptr;
1089 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001090 Schedule = isl_union_map_intersect_domain(
1091 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1092 if (isl_union_map_is_empty(Schedule)) {
1093 isl_set_free(Domain);
1094 isl_union_map_free(Schedule);
1095 return isl_map_from_aff(
1096 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1097 }
1098 auto *M = isl_map_from_union_map(Schedule);
1099 M = isl_map_coalesce(M);
1100 M = isl_map_gist_domain(M, Domain);
1101 M = isl_map_coalesce(M);
1102 return M;
1103}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001104
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001105__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1106 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001107 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1108 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001109}
1110
Tobias Grosser37eb4222014-02-20 21:43:54 +00001111void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1112 assert(isl_set_is_subset(NewDomain, Domain) &&
1113 "New domain is not a subset of old domain!");
1114 isl_set_free(Domain);
1115 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001116}
1117
Michael Krusecac948e2015-10-02 13:53:07 +00001118void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001119 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001120 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001121 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001122
Tobias Grossera535dff2015-12-13 19:59:01 +00001123 ScopArrayInfo::MemoryKind Ty;
1124 if (Access->isPHIKind())
1125 Ty = ScopArrayInfo::MK_PHI;
1126 else if (Access->isExitPHIKind())
1127 Ty = ScopArrayInfo::MK_ExitPHI;
1128 else if (Access->isValueKind())
1129 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001130 else
Tobias Grossera535dff2015-12-13 19:59:01 +00001131 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001132
Johannes Doerfertadeab372016-02-07 13:57:32 +00001133 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1134 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001135 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001136 }
1137}
1138
Michael Krusecac948e2015-10-02 13:53:07 +00001139void ScopStmt::addAccess(MemoryAccess *Access) {
1140 Instruction *AccessInst = Access->getAccessInstruction();
1141
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001142 if (Access->isArrayKind()) {
1143 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1144 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001145 } else if (Access->isValueKind() && Access->isWrite()) {
1146 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001147 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001148 assert(!ValueWrites.lookup(AccessVal));
1149
1150 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001151 } else if (Access->isValueKind() && Access->isRead()) {
1152 Value *AccessVal = Access->getAccessValue();
1153 assert(!ValueReads.lookup(AccessVal));
1154
1155 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001156 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1157 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1158 assert(!PHIWrites.lookup(PHI));
1159
1160 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001161 }
1162
1163 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001164}
1165
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001166void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001167 for (MemoryAccess *MA : *this)
1168 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001169
Johannes Doerferta60ad842016-05-10 12:18:22 +00001170 auto *Ctx = Parent.getContext();
1171 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1172 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001173}
1174
Tobias Grosserc80d6972016-09-02 06:33:33 +00001175/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001176static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1177 void *User) {
1178 isl_set **BoundedParts = static_cast<isl_set **>(User);
1179 if (isl_basic_set_is_bounded(BSet))
1180 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1181 else
1182 isl_basic_set_free(BSet);
1183 return isl_stat_ok;
1184}
1185
Tobias Grosserc80d6972016-09-02 06:33:33 +00001186/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001187static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1188 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1189 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1190 isl_set_free(S);
1191 return BoundedParts;
1192}
1193
Tobias Grosserc80d6972016-09-02 06:33:33 +00001194/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001195///
1196/// @returns A separation of @p S into first an unbounded then a bounded subset,
1197/// both with regards to the dimension @p Dim.
1198static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1199partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1200
1201 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001202 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001203
1204 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001205 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001206
1207 // Remove dimensions that are greater than Dim as they are not interesting.
1208 assert(NumDimsS >= Dim + 1);
1209 OnlyDimS =
1210 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1211
1212 // Create artificial parametric upper bounds for dimensions smaller than Dim
1213 // as we are not interested in them.
1214 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1215 for (unsigned u = 0; u < Dim; u++) {
1216 isl_constraint *C = isl_inequality_alloc(
1217 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1218 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1219 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1220 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1221 }
1222
1223 // Collect all bounded parts of OnlyDimS.
1224 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1225
1226 // Create the dimensions greater than Dim again.
1227 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1228 NumDimsS - Dim - 1);
1229
1230 // Remove the artificial upper bound parameters again.
1231 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1232
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001233 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001234 return std::make_pair(UnboundedParts, BoundedParts);
1235}
1236
Tobias Grosserc80d6972016-09-02 06:33:33 +00001237/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001238static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1239 __isl_take isl_set *To) {
1240 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1241 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1242 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1243 }
1244 return To;
1245}
1246
Tobias Grosserc80d6972016-09-02 06:33:33 +00001247/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001248static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001249 __isl_take isl_pw_aff *L,
1250 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001251 switch (Pred) {
1252 case ICmpInst::ICMP_EQ:
1253 return isl_pw_aff_eq_set(L, R);
1254 case ICmpInst::ICMP_NE:
1255 return isl_pw_aff_ne_set(L, R);
1256 case ICmpInst::ICMP_SLT:
1257 return isl_pw_aff_lt_set(L, R);
1258 case ICmpInst::ICMP_SLE:
1259 return isl_pw_aff_le_set(L, R);
1260 case ICmpInst::ICMP_SGT:
1261 return isl_pw_aff_gt_set(L, R);
1262 case ICmpInst::ICMP_SGE:
1263 return isl_pw_aff_ge_set(L, R);
1264 case ICmpInst::ICMP_ULT:
1265 return isl_pw_aff_lt_set(L, R);
1266 case ICmpInst::ICMP_UGT:
1267 return isl_pw_aff_gt_set(L, R);
1268 case ICmpInst::ICMP_ULE:
1269 return isl_pw_aff_le_set(L, R);
1270 case ICmpInst::ICMP_UGE:
1271 return isl_pw_aff_ge_set(L, R);
1272 default:
1273 llvm_unreachable("Non integer predicate not supported");
1274 }
1275}
1276
Tobias Grosserc80d6972016-09-02 06:33:33 +00001277/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001278///
1279/// Helper function that will make sure the dimensions of the result have the
1280/// same isl_id's as the @p Domain.
1281static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1282 __isl_take isl_pw_aff *L,
1283 __isl_take isl_pw_aff *R,
1284 __isl_keep isl_set *Domain) {
1285 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1286 return setDimensionIds(Domain, ConsequenceCondSet);
1287}
1288
Tobias Grosserc80d6972016-09-02 06:33:33 +00001289/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001290///
1291/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001292/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1293/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001294static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001295buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1296 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001297 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1298
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001299 Value *Condition = getConditionFromTerminator(SI);
1300 assert(Condition && "No condition for switch");
1301
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001302 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001303 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001304 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001305 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001306
1307 unsigned NumSuccessors = SI->getNumSuccessors();
1308 ConditionSets.resize(NumSuccessors);
1309 for (auto &Case : SI->cases()) {
1310 unsigned Idx = Case.getSuccessorIndex();
1311 ConstantInt *CaseValue = Case.getCaseValue();
1312
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001313 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001314 isl_set *CaseConditionSet =
1315 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1316 ConditionSets[Idx] = isl_set_coalesce(
1317 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1318 }
1319
1320 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1321 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1322 for (unsigned u = 2; u < NumSuccessors; u++)
1323 ConditionSetUnion =
1324 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1325 ConditionSets[0] = setDimensionIds(
1326 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1327
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001328 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001329
1330 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001331}
1332
Tobias Grosserc80d6972016-09-02 06:33:33 +00001333/// Build the conditions sets for the branch condition @p Condition in
1334/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001335///
1336/// This will fill @p ConditionSets with the conditions under which control
1337/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001338/// have as many elements as @p TI has successors. If @p TI is nullptr the
1339/// context under which @p Condition is true/false will be returned as the
1340/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001341static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001342buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1343 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001344 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1345
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001346 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001347 isl_set *ConsequenceCondSet = nullptr;
1348 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1349 if (CCond->isZero())
1350 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1351 else
1352 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1353 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1354 auto Opcode = BinOp->getOpcode();
1355 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1356
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001357 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1358 ConditionSets) &&
1359 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1360 ConditionSets);
1361 if (!Valid) {
1362 while (!ConditionSets.empty())
1363 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001364 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001365 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001366
1367 isl_set_free(ConditionSets.pop_back_val());
1368 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1369 isl_set_free(ConditionSets.pop_back_val());
1370 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1371
1372 if (Opcode == Instruction::And)
1373 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1374 else
1375 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1376 } else {
1377 auto *ICond = dyn_cast<ICmpInst>(Condition);
1378 assert(ICond &&
1379 "Condition of exiting branch was neither constant nor ICmp!");
1380
1381 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001382 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001383 // For unsigned comparisons we assumed the signed bit of neither operand
1384 // to be set. The comparison is equal to a signed comparison under this
1385 // assumption.
1386 bool NonNeg = ICond->isUnsigned();
1387 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1388 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001389 ConsequenceCondSet =
1390 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1391 }
1392
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001393 // If no terminator was given we are only looking for parameter constraints
1394 // under which @p Condition is true/false.
1395 if (!TI)
1396 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001397 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001398 ConsequenceCondSet = isl_set_coalesce(
1399 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001400
Johannes Doerfertb2885792016-04-26 09:20:41 +00001401 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001402 bool TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001403 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001404
Michael Krusef7a4a942016-05-02 12:25:36 +00001405 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001406 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1407 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001408 TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001409 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001410 }
1411
Michael Krusef7a4a942016-05-02 12:25:36 +00001412 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001413 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001414 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001415 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001416 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001417 }
1418
1419 ConditionSets.push_back(ConsequenceCondSet);
1420 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001421
1422 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001423}
1424
Tobias Grosserc80d6972016-09-02 06:33:33 +00001425/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001426///
1427/// This will fill @p ConditionSets with the conditions under which control
1428/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1429/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001430static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001431buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001432 __isl_keep isl_set *Domain,
1433 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1434
1435 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001436 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001437
1438 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1439
1440 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001441 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001442 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001443 }
1444
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001445 Value *Condition = getConditionFromTerminator(TI);
1446 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001447
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001448 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001449}
1450
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001451void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001452 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001453
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001454 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001455 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001456}
1457
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001458void ScopStmt::collectSurroundingLoops() {
1459 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1460 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1461 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1462 isl_id_free(DimId);
1463 }
1464}
1465
Michael Kruse9d080092015-09-11 21:41:48 +00001466ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerferta3519512016-04-23 13:02:23 +00001467 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1468 R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001469
Tobias Grosser16c44032015-07-09 07:31:45 +00001470 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001471}
1472
Michael Kruse9d080092015-09-11 21:41:48 +00001473ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerferta3519512016-04-23 13:02:23 +00001474 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1475 R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001476
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001477 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001478}
1479
Roman Gareevb3224ad2016-09-14 06:26:09 +00001480ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1481 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1482 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1483 R(nullptr), Build(nullptr) {
1484 BaseName = getIslCompatibleName("CopyStmt_", "",
1485 std::to_string(parent.getCopyStmtsNum()));
1486 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1487 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1488 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1489 auto *Access =
1490 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1491 parent.addAccessFunction(Access);
1492 addAccess(Access);
1493 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1494 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1495 parent.addAccessFunction(Access);
1496 addAccess(Access);
1497}
1498
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001499void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001500 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001501
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001502 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001503 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001504 buildAccessRelations();
1505
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001506 if (DetectReductions)
1507 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001508}
1509
Tobias Grosserc80d6972016-09-02 06:33:33 +00001510/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001511///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001512/// Check if the stored value for @p StoreMA is a binary operator with one or
1513/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001514/// used only once (by @p StoreMA) and its load operands are also used only
1515/// once, we have found a possible reduction chain. It starts at an operand
1516/// load and includes the binary operator and @p StoreMA.
1517///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001518/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001519/// escape this block or into any other store except @p StoreMA.
1520void ScopStmt::collectCandiateReductionLoads(
1521 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1522 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1523 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001524 return;
1525
1526 // Skip if there is not one binary operator between the load and the store
1527 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001528 if (!BinOp)
1529 return;
1530
1531 // Skip if the binary operators has multiple uses
1532 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001533 return;
1534
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001535 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001536 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1537 return;
1538
Johannes Doerfert9890a052014-07-01 00:32:29 +00001539 // Skip if the binary operator is outside the current SCoP
1540 if (BinOp->getParent() != Store->getParent())
1541 return;
1542
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001543 // Skip if it is a multiplicative reduction and we disabled them
1544 if (DisableMultiplicativeReductions &&
1545 (BinOp->getOpcode() == Instruction::Mul ||
1546 BinOp->getOpcode() == Instruction::FMul))
1547 return;
1548
Johannes Doerferte58a0122014-06-27 20:31:28 +00001549 // Check the binary operator operands for a candidate load
1550 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1551 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1552 if (!PossibleLoad0 && !PossibleLoad1)
1553 return;
1554
1555 // A load is only a candidate if it cannot escape (thus has only this use)
1556 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001557 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001558 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001559 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001560 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001561 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001562}
1563
Tobias Grosserc80d6972016-09-02 06:33:33 +00001564/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001565///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001566/// Iterate over all store memory accesses and check for valid binary reduction
1567/// like chains. For all candidates we check if they have the same base address
1568/// and there are no other accesses which overlap with them. The base address
1569/// check rules out impossible reductions candidates early. The overlap check,
1570/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001571/// guarantees that none of the intermediate results will escape during
1572/// execution of the loop nest. We basically check here that no other memory
1573/// access can access the same memory as the potential reduction.
1574void ScopStmt::checkForReductions() {
1575 SmallVector<MemoryAccess *, 2> Loads;
1576 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1577
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001578 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001579 // stores and collecting possible reduction loads.
1580 for (MemoryAccess *StoreMA : MemAccs) {
1581 if (StoreMA->isRead())
1582 continue;
1583
1584 Loads.clear();
1585 collectCandiateReductionLoads(StoreMA, Loads);
1586 for (MemoryAccess *LoadMA : Loads)
1587 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1588 }
1589
1590 // Then check each possible candidate pair.
1591 for (const auto &CandidatePair : Candidates) {
1592 bool Valid = true;
1593 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1594 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1595
1596 // Skip those with obviously unequal base addresses.
1597 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1598 isl_map_free(LoadAccs);
1599 isl_map_free(StoreAccs);
1600 continue;
1601 }
1602
1603 // And check if the remaining for overlap with other memory accesses.
1604 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1605 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1606 isl_set *AllAccs = isl_map_range(AllAccsRel);
1607
1608 for (MemoryAccess *MA : MemAccs) {
1609 if (MA == CandidatePair.first || MA == CandidatePair.second)
1610 continue;
1611
1612 isl_map *AccRel =
1613 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1614 isl_set *Accs = isl_map_range(AccRel);
1615
Tobias Grosser55a7af72016-09-08 14:08:07 +00001616 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001617 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1618 Valid = Valid && isl_set_is_empty(OverlapAccs);
1619 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001620 } else {
1621 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001622 }
1623 }
1624
1625 isl_set_free(AllAccs);
1626 if (!Valid)
1627 continue;
1628
Johannes Doerfertf6183392014-07-01 20:52:51 +00001629 const LoadInst *Load =
1630 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1631 MemoryAccess::ReductionType RT =
1632 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1633
Johannes Doerferte58a0122014-06-27 20:31:28 +00001634 // If no overlapping access was found we mark the load and store as
1635 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001636 CandidatePair.first->markAsReductionLike(RT);
1637 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001638 }
Tobias Grosser75805372011-04-29 06:27:02 +00001639}
1640
Tobias Grosser74394f02013-01-14 22:40:23 +00001641std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001642
Tobias Grosser54839312015-04-21 11:37:25 +00001643std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001644 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001645 if (!S)
1646 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001647 auto Str = stringFromIslObj(S);
1648 isl_map_free(S);
1649 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001650}
1651
Johannes Doerferta3519512016-04-23 13:02:23 +00001652void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1653 isl_set_free(InvalidDomain);
1654 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001655}
1656
Michael Kruse375cb5f2016-02-24 22:08:24 +00001657BasicBlock *ScopStmt::getEntryBlock() const {
1658 if (isBlockStmt())
1659 return getBasicBlock();
1660 return getRegion()->getEntry();
1661}
1662
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001663unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001664
Tobias Grosser75805372011-04-29 06:27:02 +00001665const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1666
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001667Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001668 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001669}
1670
Tobias Grosser74394f02013-01-14 22:40:23 +00001671isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001672
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001673__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001674
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001675__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001676 return isl_set_get_space(Domain);
1677}
1678
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001679__isl_give isl_id *ScopStmt::getDomainId() const {
1680 return isl_set_get_tuple_id(Domain);
1681}
Tobias Grossercd95b772012-08-30 11:49:38 +00001682
Johannes Doerfert7c013572016-04-12 09:57:34 +00001683ScopStmt::~ScopStmt() {
1684 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001685 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001686}
Tobias Grosser75805372011-04-29 06:27:02 +00001687
1688void ScopStmt::print(raw_ostream &OS) const {
1689 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001690 OS.indent(12) << "Domain :=\n";
1691
1692 if (Domain) {
1693 OS.indent(16) << getDomainStr() << ";\n";
1694 } else
1695 OS.indent(16) << "n/a\n";
1696
Tobias Grosser54839312015-04-21 11:37:25 +00001697 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001698
1699 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001700 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001701 } else
1702 OS.indent(16) << "n/a\n";
1703
Tobias Grosser083d3d32014-06-28 08:59:45 +00001704 for (MemoryAccess *Access : MemAccs)
1705 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001706}
1707
1708void ScopStmt::dump() const { print(dbgs()); }
1709
Michael Kruse10071822016-05-23 14:45:58 +00001710void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
1711 // Remove the memory accesses from this statement
1712 // together with all scalar accesses that were caused by it.
Michael Krusead28e5a2016-01-26 13:33:15 +00001713 // MK_Value READs have no access instruction, hence would not be removed by
1714 // this function. However, it is only used for invariant LoadInst accesses,
1715 // its arguments are always affine, hence synthesizable, and therefore there
1716 // are no MK_Value READ accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001717 auto Predicate = [&](MemoryAccess *Acc) {
1718 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1719 };
1720 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1721 MemAccs.end());
1722 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001723}
1724
Tobias Grosser75805372011-04-29 06:27:02 +00001725//===----------------------------------------------------------------------===//
1726/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001727
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001728void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001729 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1730 isl_set_free(Context);
1731 Context = NewContext;
1732}
1733
Tobias Grosserc80d6972016-09-02 06:33:33 +00001734/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001735struct SCEVSensitiveParameterRewriter
1736 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1737 ValueToValueMap &VMap;
1738 ScalarEvolution &SE;
1739
1740public:
1741 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1742 : VMap(VMap), SE(SE) {}
1743
1744 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1745 ValueToValueMap &VMap) {
1746 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1747 return SSPR.visit(E);
1748 }
1749
1750 const SCEV *visit(const SCEV *E) {
1751 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1752 }
1753
1754 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1755
1756 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1757 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1758 }
1759
1760 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1761 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1762 }
1763
1764 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1765 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1766 }
1767
1768 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1769 SmallVector<const SCEV *, 4> Operands;
1770 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1771 Operands.push_back(visit(E->getOperand(i)));
1772 return SE.getAddExpr(Operands);
1773 }
1774
1775 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1776 SmallVector<const SCEV *, 4> Operands;
1777 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1778 Operands.push_back(visit(E->getOperand(i)));
1779 return SE.getMulExpr(Operands);
1780 }
1781
1782 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1783 SmallVector<const SCEV *, 4> Operands;
1784 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1785 Operands.push_back(visit(E->getOperand(i)));
1786 return SE.getSMaxExpr(Operands);
1787 }
1788
1789 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1790 SmallVector<const SCEV *, 4> Operands;
1791 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1792 Operands.push_back(visit(E->getOperand(i)));
1793 return SE.getUMaxExpr(Operands);
1794 }
1795
1796 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1797 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1798 }
1799
1800 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1801 auto *Start = visit(E->getStart());
1802 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1803 visit(E->getStepRecurrence(SE)),
1804 E->getLoop(), SCEV::FlagAnyWrap);
1805 return SE.getAddExpr(Start, AddRec);
1806 }
1807
1808 const SCEV *visitUnknown(const SCEVUnknown *E) {
1809 if (auto *NewValue = VMap.lookup(E->getValue()))
1810 return SE.getUnknown(NewValue);
1811 return E;
1812 }
1813};
1814
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001815const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001816 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001817}
1818
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001819void Scop::createParameterId(const SCEV *Parameter) {
1820 assert(Parameters.count(Parameter));
1821 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001822
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001823 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001824
Tobias Grosser8f99c162011-11-15 11:38:55 +00001825 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1826 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001827
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001828 // If this parameter references a specific Value and this value has a name
1829 // we use this name as it is likely to be unique and more useful than just
1830 // a number.
1831 if (Val->hasName())
1832 ParameterName = Val->getName();
1833 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001834 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001835 if (LoadOrigin->hasName()) {
1836 ParameterName += "_loaded_from_";
1837 ParameterName +=
1838 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1839 }
1840 }
1841 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001842
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001843 ParameterName = getIslCompatibleName("", ParameterName, "");
1844
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001845 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1846 const_cast<void *>((const void *)Parameter));
1847 ParameterIds[Parameter] = Id;
1848}
1849
1850void Scop::addParams(const ParameterSetTy &NewParameters) {
1851 for (const SCEV *Parameter : NewParameters) {
1852 // Normalize the SCEV to get the representing element for an invariant load.
1853 Parameter = extractConstantFactor(Parameter, *SE).second;
1854 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1855
1856 if (Parameters.insert(Parameter))
1857 createParameterId(Parameter);
1858 }
1859}
1860
1861__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1862 // Normalize the SCEV to get the representing element for an invariant load.
1863 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1864 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001865}
Tobias Grosser75805372011-04-29 06:27:02 +00001866
Michael Krused56b90a2016-09-01 09:03:27 +00001867__isl_give isl_set *
1868Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001869 isl_set *DomainContext = isl_union_set_params(getDomains());
1870 return isl_set_intersect_params(C, DomainContext);
1871}
1872
Johannes Doerferte0b08072016-05-23 12:43:44 +00001873bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1874 return DT.dominates(BB, getEntry());
1875}
1876
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001877void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1878 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001879 auto &F = getFunction();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001880 for (auto &Assumption : AC.assumptions()) {
1881 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1882 if (!CI || CI->getNumArgOperands() != 1)
1883 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001884
Johannes Doerfert952b5302016-05-23 12:40:48 +00001885 bool InScop = contains(CI);
Johannes Doerferte0b08072016-05-23 12:43:44 +00001886 if (!InScop && !isDominatedBy(DT, CI->getParent()))
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001887 continue;
1888
Michael Kruse09eb4452016-03-03 22:10:47 +00001889 auto *L = LI.getLoopFor(CI->getParent());
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001890 auto *Val = CI->getArgOperand(0);
Johannes Doerfertf560b3d2016-04-25 13:33:07 +00001891 ParameterSetTy DetectedParams;
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001892 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001893 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1894 CI->getDebugLoc(),
1895 "Non-affine user assumption ignored.");
1896 continue;
1897 }
1898
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001899 // Collect all newly introduced parameters.
1900 ParameterSetTy NewParams;
1901 for (auto *Param : DetectedParams) {
1902 Param = extractConstantFactor(Param, *SE).second;
1903 Param = getRepresentingInvariantLoadSCEV(Param);
1904 if (Parameters.count(Param))
1905 continue;
1906 NewParams.insert(Param);
1907 }
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001908
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001909 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001910 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
1911 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
1912 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001913 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
1914 isl_set_free(Dom);
1915
1916 if (!Valid)
Johannes Doerfert297c7202016-05-10 13:06:42 +00001917 continue;
1918
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001919 isl_set *AssumptionCtx = nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001920 if (InScop) {
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001921 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
1922 isl_set_free(ConditionSets[0]);
1923 } else {
1924 AssumptionCtx = isl_set_complement(ConditionSets[1]);
1925 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
1926 }
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001927
1928 // Project out newly introduced parameters as they are not otherwise useful.
1929 if (!NewParams.empty()) {
1930 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
1931 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
1932 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
1933 isl_id_free(Id);
1934
1935 if (!NewParams.count(Param))
1936 continue;
1937
1938 AssumptionCtx =
1939 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
1940 }
1941 }
1942
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001943 emitOptimizationRemarkAnalysis(
1944 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1945 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1946 Context = isl_set_intersect(Context, AssumptionCtx);
1947 }
1948}
1949
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001950void Scop::addUserContext() {
1951 if (UserContextStr.empty())
1952 return;
1953
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001954 isl_set *UserContext =
1955 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001956 isl_space *Space = getParamSpace();
1957 if (isl_space_dim(Space, isl_dim_param) !=
1958 isl_set_dim(UserContext, isl_dim_param)) {
1959 auto SpaceStr = isl_space_to_str(Space);
1960 errs() << "Error: the context provided in -polly-context has not the same "
1961 << "number of dimensions than the computed context. Due to this "
1962 << "mismatch, the -polly-context option is ignored. Please provide "
1963 << "the context in the parameter space: " << SpaceStr << ".\n";
1964 free(SpaceStr);
1965 isl_set_free(UserContext);
1966 isl_space_free(Space);
1967 return;
1968 }
1969
1970 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001971 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1972 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001973
1974 if (strcmp(NameContext, NameUserContext) != 0) {
1975 auto SpaceStr = isl_space_to_str(Space);
1976 errs() << "Error: the name of dimension " << i
1977 << " provided in -polly-context "
1978 << "is '" << NameUserContext << "', but the name in the computed "
1979 << "context is '" << NameContext
1980 << "'. Due to this name mismatch, "
1981 << "the -polly-context option is ignored. Please provide "
1982 << "the context in the parameter space: " << SpaceStr << ".\n";
1983 free(SpaceStr);
1984 isl_set_free(UserContext);
1985 isl_space_free(Space);
1986 return;
1987 }
1988
1989 UserContext =
1990 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1991 isl_space_get_dim_id(Space, isl_dim_param, i));
1992 }
1993
1994 Context = isl_set_intersect(Context, UserContext);
1995 isl_space_free(Space);
1996}
1997
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001998void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001999 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002000
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002001 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002002 for (LoadInst *LInst : RIL) {
2003 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2004
Johannes Doerfert96e54712016-02-07 17:30:13 +00002005 Type *Ty = LInst->getType();
2006 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002007 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002008 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002009 continue;
2010 }
2011
2012 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002013 InvariantEquivClasses.emplace_back(
2014 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002015 }
2016}
2017
Tobias Grosser6be480c2011-11-08 15:41:13 +00002018void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002019 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002020 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002021 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002022 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002023}
2024
Tobias Grosser18daaca2012-05-22 10:47:27 +00002025void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002026 unsigned PDim = 0;
2027 for (auto *Parameter : Parameters) {
2028 ConstantRange SRange = SE->getSignedRange(Parameter);
2029 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002030 }
2031}
2032
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002033void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002034 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002035 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002036
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002037 unsigned PDim = 0;
2038 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002039 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002040 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002041 }
2042
2043 // Align the parameters of all data structures to the model.
2044 Context = isl_set_align_params(Context, Space);
2045
Johannes Doerferta60ad842016-05-10 12:18:22 +00002046 // As all parameters are known add bounds to them.
2047 addParameterBounds();
2048
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002049 for (ScopStmt &Stmt : *this)
2050 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002051
2052 // Simplify the schedule according to the context too.
2053 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002054}
2055
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002056static __isl_give isl_set *
2057simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2058 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002059 // If we modelt all blocks in the SCoP that have side effects we can simplify
2060 // the context with the constraints that are needed for anything to be
2061 // executed at all. However, if we have error blocks in the SCoP we already
2062 // assumed some parameter combinations cannot occure and removed them from the
2063 // domains, thus we cannot use the remaining domain to simplify the
2064 // assumptions.
2065 if (!S.hasErrorBlock()) {
2066 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2067 AssumptionContext =
2068 isl_set_gist_params(AssumptionContext, DomainParameters);
2069 }
2070
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002071 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2072 return AssumptionContext;
2073}
2074
2075void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002076 // The parameter constraints of the iteration domains give us a set of
2077 // constraints that need to hold for all cases where at least a single
2078 // statement iteration is executed in the whole scop. We now simplify the
2079 // assumed context under the assumption that such constraints hold and at
2080 // least a single statement iteration is executed. For cases where no
2081 // statement instances are executed, the assumptions we have taken about
2082 // the executed code do not matter and can be changed.
2083 //
2084 // WARNING: This only holds if the assumptions we have taken do not reduce
2085 // the set of statement instances that are executed. Otherwise we
2086 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002087 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002088 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002089 // performed. In such a case, modifying the run-time conditions and
2090 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002091 // to not be executed.
2092 //
2093 // Example:
2094 //
2095 // When delinearizing the following code:
2096 //
2097 // for (long i = 0; i < 100; i++)
2098 // for (long j = 0; j < m; j++)
2099 // A[i+p][j] = 1.0;
2100 //
2101 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002102 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002103 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002104 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002105 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002106}
2107
Tobias Grosserc80d6972016-09-02 06:33:33 +00002108/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002109static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002110 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2111 isl_pw_multi_aff *MinPMA, *MaxPMA;
2112 isl_pw_aff *LastDimAff;
2113 isl_aff *OneAff;
2114 unsigned Pos;
2115
Johannes Doerfert6296d952016-04-22 11:38:19 +00002116 Set = isl_set_remove_divs(Set);
2117
Michael Krusebc150122016-05-02 12:25:18 +00002118 if (isl_set_n_basic_set(Set) >= MaxDisjunctionsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002119 isl_set_free(Set);
2120 return isl_stat_error;
2121 }
2122
Johannes Doerfert9143d672014-09-27 11:02:39 +00002123 // Restrict the number of parameters involved in the access as the lexmin/
2124 // lexmax computation will take too long if this number is high.
2125 //
2126 // Experiments with a simple test case using an i7 4800MQ:
2127 //
2128 // #Parameters involved | Time (in sec)
2129 // 6 | 0.01
2130 // 7 | 0.04
2131 // 8 | 0.12
2132 // 9 | 0.40
2133 // 10 | 1.54
2134 // 11 | 6.78
2135 // 12 | 30.38
2136 //
2137 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2138 unsigned InvolvedParams = 0;
2139 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2140 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2141 InvolvedParams++;
2142
2143 if (InvolvedParams > RunTimeChecksMaxParameters) {
2144 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002145 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002146 }
2147 }
2148
Johannes Doerfertb164c792014-09-18 11:17:17 +00002149 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2150 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2151
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002152 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2153 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2154
Johannes Doerfertb164c792014-09-18 11:17:17 +00002155 // Adjust the last dimension of the maximal access by one as we want to
2156 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2157 // we test during code generation might now point after the end of the
2158 // allocated array but we will never dereference it anyway.
2159 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2160 "Assumed at least one output dimension");
2161 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2162 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2163 OneAff = isl_aff_zero_on_domain(
2164 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2165 OneAff = isl_aff_add_constant_si(OneAff, 1);
2166 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2167 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2168
2169 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2170
2171 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002172 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002173}
2174
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002175static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2176 isl_set *Domain = MA->getStatement()->getDomain();
2177 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2178 return isl_set_reset_tuple_id(Domain);
2179}
2180
Tobias Grosserc80d6972016-09-02 06:33:33 +00002181/// Wrapper function to calculate minimal/maximal accesses to each array.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002182static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002183 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002184 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002185
2186 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2187 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002188 Locations = isl_union_set_coalesce(Locations);
2189 Locations = isl_union_set_detect_equalities(Locations);
2190 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002191 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002192 isl_union_set_free(Locations);
2193 return Valid;
2194}
2195
Tobias Grosserc80d6972016-09-02 06:33:33 +00002196/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002197///
2198///{
2199
Tobias Grosserc80d6972016-09-02 06:33:33 +00002200/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002201static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2202 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2203 : RN->getNodeAs<BasicBlock>();
2204}
2205
Tobias Grosserc80d6972016-09-02 06:33:33 +00002206/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002207static inline BasicBlock *
2208getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002209 if (RN->isSubRegion()) {
2210 assert(idx == 0);
2211 return RN->getNodeAs<Region>()->getExit();
2212 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002213 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002214}
2215
Tobias Grosserc80d6972016-09-02 06:33:33 +00002216/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002217static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2218 if (!RN->isSubRegion())
2219 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2220
2221 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2222 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2223 while (L && NonAffineSubRegion->contains(L))
2224 L = L->getParentLoop();
2225 return L;
2226}
2227
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002228static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2229 if (!RN->isSubRegion())
2230 return 1;
2231
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002232 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002233 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002234}
2235
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002236static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2237 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002238 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002239 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002240 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002241 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002242 return true;
2243 return false;
2244}
2245
Johannes Doerfert96425c22015-08-30 21:13:53 +00002246///}
2247
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002248static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2249 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002250 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002251 isl_id *DimId =
2252 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2253 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2254}
2255
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002256__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002257 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002258}
2259
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002260__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002261 auto DIt = DomainMap.find(BB);
2262 if (DIt != DomainMap.end())
2263 return isl_set_copy(DIt->getSecond());
2264
2265 auto &RI = *R.getRegionInfo();
2266 auto *BBR = RI.getRegionFor(BB);
2267 while (BBR->getEntry() == BB)
2268 BBR = BBR->getParent();
2269 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002270}
2271
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002272bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002273
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002274 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002275 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002276 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2277 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002278 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002279
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002280 while (LD-- >= 0) {
2281 S = addDomainDimId(S, LD + 1, L);
2282 L = L->getParentLoop();
2283 }
2284
Johannes Doerferta3519512016-04-23 13:02:23 +00002285 // Initialize the invalid domain.
2286 auto *EntryStmt = getStmtFor(EntryBB);
2287 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2288
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002289 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002290
Johannes Doerfert432658d2016-01-26 11:01:41 +00002291 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002292 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002293
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002294 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002295 return false;
2296
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002297 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002298 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002299
2300 // Error blocks and blocks dominated by them have been assumed to never be
2301 // executed. Representing them in the Scop does not add any value. In fact,
2302 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002303 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002304 // will cause problems when building up a ScopStmt for them.
2305 // Furthermore, basic blocks dominated by error blocks may reference
2306 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002307 // can themselves not be constructed properly. To this end we will replace
2308 // the domains of error blocks and those only reachable via error blocks
2309 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002310 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002311 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002312 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002313 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002314
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002315 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002316}
2317
Michael Kruse586e5792016-07-08 12:38:28 +00002318// If the loop is nonaffine/boxed, return the first non-boxed surrounding loop
2319// for Polly. If the loop is affine, return the loop itself. Do not call
2320// `getSCEVAtScope()` on the result of `getFirstNonBoxedLoopFor()`, as we need
2321// to analyze the memory accesses of the nonaffine/boxed loops.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002322static Loop *getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI,
2323 const BoxedLoopsSetTy &BoxedLoops) {
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002324 auto *L = LI.getLoopFor(BB);
2325 while (BoxedLoops.count(L))
2326 L = L->getParentLoop();
2327 return L;
2328}
2329
Tobias Grosserc80d6972016-09-02 06:33:33 +00002330/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002331/// to be compatible to domains constructed for loop @p NewL.
2332///
2333/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2334/// edge from @p OldL to @p NewL.
2335static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2336 __isl_take isl_set *Dom,
2337 Loop *OldL, Loop *NewL) {
2338
2339 // If the loops are the same there is nothing to do.
2340 if (NewL == OldL)
2341 return Dom;
2342
2343 int OldDepth = S.getRelativeLoopDepth(OldL);
2344 int NewDepth = S.getRelativeLoopDepth(NewL);
2345 // If both loops are non-affine loops there is nothing to do.
2346 if (OldDepth == -1 && NewDepth == -1)
2347 return Dom;
2348
2349 // Distinguish three cases:
2350 // 1) The depth is the same but the loops are not.
2351 // => One loop was left one was entered.
2352 // 2) The depth increased from OldL to NewL.
2353 // => One loop was entered, none was left.
2354 // 3) The depth decreased from OldL to NewL.
2355 // => Loops were left were difference of the depths defines how many.
2356 if (OldDepth == NewDepth) {
2357 assert(OldL->getParentLoop() == NewL->getParentLoop());
2358 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2359 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2360 Dom = addDomainDimId(Dom, NewDepth, NewL);
2361 } else if (OldDepth < NewDepth) {
2362 assert(OldDepth + 1 == NewDepth);
2363 auto &R = S.getRegion();
2364 (void)R;
2365 assert(NewL->getParentLoop() == OldL ||
2366 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2367 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2368 Dom = addDomainDimId(Dom, NewDepth, NewL);
2369 } else {
2370 assert(OldDepth > NewDepth);
2371 int Diff = OldDepth - NewDepth;
2372 int NumDim = isl_set_n_dim(Dom);
2373 assert(NumDim >= Diff);
2374 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2375 }
2376
2377 return Dom;
2378}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002379
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002380bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2381 LoopInfo &LI) {
2382 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002383
2384 ReversePostOrderTraversal<Region *> RTraversal(R);
2385 for (auto *RN : RTraversal) {
2386
2387 // Recurse for affine subregions but go on for basic blocks and non-affine
2388 // subregions.
2389 if (RN->isSubRegion()) {
2390 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002391 if (!isNonAffineSubRegion(SubRegion)) {
2392 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002393 continue;
2394 }
2395 }
2396
2397 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2398 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002399 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002400 isl_set *&Domain = DomainMap[BB];
2401 assert(Domain && "Cannot propagate a nullptr");
2402
Johannes Doerferta3519512016-04-23 13:02:23 +00002403 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002404 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002405 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002406
Johannes Doerferta3519512016-04-23 13:02:23 +00002407 if (!IsInvalidBlock) {
2408 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002409 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002410 isl_set_free(InvalidDomain);
2411 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002412 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2413 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2414 AS_RESTRICTION);
2415 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002416 }
2417
Johannes Doerferta3519512016-04-23 13:02:23 +00002418 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002419 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002420 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002421 }
2422
Johannes Doerferta3519512016-04-23 13:02:23 +00002423 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002424 auto *TI = BB->getTerminator();
2425 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2426 for (unsigned u = 0; u < NumSuccs; u++) {
2427 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002428 auto *SuccStmt = getStmtFor(SuccBB);
2429
2430 // Skip successors outside the SCoP.
2431 if (!SuccStmt)
2432 continue;
2433
Johannes Doerferte4459a22016-04-25 13:34:50 +00002434 // Skip backedges.
2435 if (DT.dominates(SuccBB, BB))
2436 continue;
2437
Johannes Doerferta3519512016-04-23 13:02:23 +00002438 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2439 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2440 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2441 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2442 SuccInvalidDomain =
2443 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2444 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2445 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2446 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002447
Michael Krusebc150122016-05-02 12:25:18 +00002448 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002449 // In case this happens we will bail.
Michael Krusebc150122016-05-02 12:25:18 +00002450 if (NumConjucts < MaxDisjunctionsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002451 continue;
2452
Johannes Doerferta3519512016-04-23 13:02:23 +00002453 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002454 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002455 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002456 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002457
2458 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002459 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002460
2461 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002462}
2463
Johannes Doerfert642594a2016-04-04 07:57:39 +00002464void Scop::propagateDomainConstraintsToRegionExit(
2465 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002466 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002467
2468 // Check if the block @p BB is the entry of a region. If so we propagate it's
2469 // domain to the exit block of the region. Otherwise we are done.
2470 auto *RI = R.getRegionInfo();
2471 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2472 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002473 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002474 return;
2475
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002476 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002477 // Do not propagate the domain if there is a loop backedge inside the region
2478 // that would prevent the exit block from beeing executed.
2479 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002480 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002481 SmallVector<BasicBlock *, 4> LatchBBs;
2482 BBLoop->getLoopLatches(LatchBBs);
2483 for (auto *LatchBB : LatchBBs)
2484 if (BB != LatchBB && BBReg->contains(LatchBB))
2485 return;
2486 L = L->getParentLoop();
2487 }
2488
2489 auto *Domain = DomainMap[BB];
2490 assert(Domain && "Cannot propagate a nullptr");
2491
2492 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2493
2494 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2495 // adjust the domain before we can propagate it.
2496 auto *AdjustedDomain =
2497 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2498 auto *&ExitDomain = DomainMap[ExitBB];
2499
2500 // If the exit domain is not yet created we set it otherwise we "add" the
2501 // current domain.
2502 ExitDomain =
2503 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2504
Johannes Doerferta3519512016-04-23 13:02:23 +00002505 // Initialize the invalid domain.
2506 auto *ExitStmt = getStmtFor(ExitBB);
2507 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2508
Johannes Doerfert642594a2016-04-04 07:57:39 +00002509 FinishedExitBlocks.insert(ExitBB);
2510}
2511
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002512bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2513 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002514 // To create the domain for each block in R we iterate over all blocks and
2515 // subregions in R and propagate the conditions under which the current region
2516 // element is executed. To this end we iterate in reverse post order over R as
2517 // it ensures that we first visit all predecessors of a region node (either a
2518 // basic block or a subregion) before we visit the region node itself.
2519 // Initially, only the domain for the SCoP region entry block is set and from
2520 // there we propagate the current domain to all successors, however we add the
2521 // condition that the successor is actually executed next.
2522 // As we are only interested in non-loop carried constraints here we can
2523 // simply skip loop back edges.
2524
Johannes Doerfert642594a2016-04-04 07:57:39 +00002525 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002526 ReversePostOrderTraversal<Region *> RTraversal(R);
2527 for (auto *RN : RTraversal) {
2528
2529 // Recurse for affine subregions but go on for basic blocks and non-affine
2530 // subregions.
2531 if (RN->isSubRegion()) {
2532 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002533 if (!isNonAffineSubRegion(SubRegion)) {
2534 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002535 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002536 continue;
2537 }
2538 }
2539
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002540 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002541 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002542
Johannes Doerfert96425c22015-08-30 21:13:53 +00002543 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002544 TerminatorInst *TI = BB->getTerminator();
2545
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002546 if (isa<UnreachableInst>(TI))
2547 continue;
2548
Johannes Doerfertf5673802015-10-01 23:48:18 +00002549 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002550 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002551 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002552 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002553
Johannes Doerfert642594a2016-04-04 07:57:39 +00002554 auto *BBLoop = getRegionNodeLoop(RN, LI);
2555 // Propagate the domain from BB directly to blocks that have a superset
2556 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002557 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002558
2559 // If all successors of BB have been set a domain through the propagation
2560 // above we do not need to build condition sets but can just skip this
2561 // block. However, it is important to note that this is a local property
2562 // with regards to the region @p R. To this end FinishedExitBlocks is a
2563 // local variable.
2564 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2565 return FinishedExitBlocks.count(SuccBB);
2566 };
2567 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2568 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002569
2570 // Build the condition sets for the successor nodes of the current region
2571 // node. If it is a non-affine subregion we will always execute the single
2572 // exit node, hence the single entry node domain is the condition set. For
2573 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002574 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002575 if (RN->isSubRegion())
2576 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002577 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2578 ConditionSets))
2579 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002580
2581 // Now iterate over the successors and set their initial domain based on
2582 // their condition set. We skip back edges here and have to be careful when
2583 // we leave a loop not to keep constraints over a dimension that doesn't
2584 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002585 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002586 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002587 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002588 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002589
Johannes Doerfert535de032016-04-19 14:49:05 +00002590 auto *SuccStmt = getStmtFor(SuccBB);
2591 // Skip blocks outside the region.
2592 if (!SuccStmt) {
2593 isl_set_free(CondSet);
2594 continue;
2595 }
2596
Johannes Doerfert642594a2016-04-04 07:57:39 +00002597 // If we propagate the domain of some block to "SuccBB" we do not have to
2598 // adjust the domain.
2599 if (FinishedExitBlocks.count(SuccBB)) {
2600 isl_set_free(CondSet);
2601 continue;
2602 }
2603
Johannes Doerfert96425c22015-08-30 21:13:53 +00002604 // Skip back edges.
2605 if (DT.dominates(SuccBB, BB)) {
2606 isl_set_free(CondSet);
2607 continue;
2608 }
2609
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002610 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002611 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002612 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002613
2614 // Set the domain for the successor or merge it with an existing domain in
2615 // case there are multiple paths (without loop back edges) to the
2616 // successor block.
2617 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002618
Johannes Doerferta3519512016-04-23 13:02:23 +00002619 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002620 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002621 } else {
2622 // Initialize the invalid domain.
2623 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2624 SuccDomain = CondSet;
2625 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002626
Michael Krusebc150122016-05-02 12:25:18 +00002627 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002628 // In case this happens we will clean up and bail.
Michael Krusebc150122016-05-02 12:25:18 +00002629 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctionsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002630 continue;
2631
2632 invalidate(COMPLEXITY, DebugLoc());
2633 while (++u < ConditionSets.size())
2634 isl_set_free(ConditionSets[u]);
2635 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002636 }
2637 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002638
2639 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002640}
2641
Michael Krused56b90a2016-09-01 09:03:27 +00002642__isl_give isl_set *
2643Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2644 __isl_keep isl_set *Domain,
2645 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002646 // If @p BB is the ScopEntry we are done
2647 if (R.getEntry() == BB)
2648 return isl_set_universe(isl_set_get_space(Domain));
2649
2650 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002651 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002652
2653 // The region info of this function.
2654 auto &RI = *R.getRegionInfo();
2655
2656 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2657
2658 // A domain to collect all predecessor domains, thus all conditions under
2659 // which the block is executed. To this end we start with the empty domain.
2660 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2661
2662 // Set of regions of which the entry block domain has been propagated to BB.
2663 // all predecessors inside any of the regions can be skipped.
2664 SmallSet<Region *, 8> PropagatedRegions;
2665
2666 for (auto *PredBB : predecessors(BB)) {
2667 // Skip backedges.
2668 if (DT.dominates(BB, PredBB))
2669 continue;
2670
2671 // If the predecessor is in a region we used for propagation we can skip it.
2672 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2673 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2674 PredBBInRegion)) {
2675 continue;
2676 }
2677
2678 // Check if there is a valid region we can use for propagation, thus look
2679 // for a region that contains the predecessor and has @p BB as exit block.
2680 auto *PredR = RI.getRegionFor(PredBB);
2681 while (PredR->getExit() != BB && !PredR->contains(BB))
2682 PredR->getParent();
2683
2684 // If a valid region for propagation was found use the entry of that region
2685 // for propagation, otherwise the PredBB directly.
2686 if (PredR->getExit() == BB) {
2687 PredBB = PredR->getEntry();
2688 PropagatedRegions.insert(PredR);
2689 }
2690
Johannes Doerfert41cda152016-04-08 10:32:26 +00002691 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002692 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2693 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2694
2695 PredDom = isl_set_union(PredDom, PredBBDom);
2696 }
2697
2698 return PredDom;
2699}
2700
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002701bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2702 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002703 // Iterate over the region R and propagate the domain constrains from the
2704 // predecessors to the current node. In contrast to the
2705 // buildDomainsWithBranchConstraints function, this one will pull the domain
2706 // information from the predecessors instead of pushing it to the successors.
2707 // Additionally, we assume the domains to be already present in the domain
2708 // map here. However, we iterate again in reverse post order so we know all
2709 // predecessors have been visited before a block or non-affine subregion is
2710 // visited.
2711
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002712 ReversePostOrderTraversal<Region *> RTraversal(R);
2713 for (auto *RN : RTraversal) {
2714
2715 // Recurse for affine subregions but go on for basic blocks and non-affine
2716 // subregions.
2717 if (RN->isSubRegion()) {
2718 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002719 if (!isNonAffineSubRegion(SubRegion)) {
2720 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002721 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002722 continue;
2723 }
2724 }
2725
2726 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002727 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002728 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002729
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002730 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002731 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002732 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002733 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002734
Johannes Doerfert642594a2016-04-04 07:57:39 +00002735 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002736 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002737 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2738 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002739 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002740
2741 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002742}
2743
Tobias Grosserc80d6972016-09-02 06:33:33 +00002744/// Create a map to map from a given iteration to a subsequent iteration.
2745///
2746/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2747/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002748/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002749///
2750/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002751static __isl_give isl_map *
2752createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2753 auto *MapSpace = isl_space_map_from_set(SetSpace);
2754 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2755 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2756 if (u != Dim)
2757 NextIterationMap =
2758 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2759 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2760 C = isl_constraint_set_constant_si(C, 1);
2761 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2762 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2763 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2764 return NextIterationMap;
2765}
2766
Johannes Doerfert297c7202016-05-10 13:06:42 +00002767bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002768 int LoopDepth = getRelativeLoopDepth(L);
2769 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002770
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002771 BasicBlock *HeaderBB = L->getHeader();
2772 assert(DomainMap.count(HeaderBB));
2773 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002774
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002775 isl_map *NextIterationMap =
2776 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002777
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002778 isl_set *UnionBackedgeCondition =
2779 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002780
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002781 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2782 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002783
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002784 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002785
2786 // If the latch is only reachable via error statements we skip it.
2787 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2788 if (!LatchBBDom)
2789 continue;
2790
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002791 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002792
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002793 TerminatorInst *TI = LatchBB->getTerminator();
2794 BranchInst *BI = dyn_cast<BranchInst>(TI);
2795 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002796 BackedgeCondition = isl_set_copy(LatchBBDom);
2797 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002798 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002799 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002800 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
Michael Krusee1dc3872016-11-03 15:19:41 +00002801 ConditionSets)) {
2802 isl_map_free(NextIterationMap);
2803 isl_set_free(UnionBackedgeCondition);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002804 return false;
Michael Krusee1dc3872016-11-03 15:19:41 +00002805 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002806
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002807 // Free the non back edge condition set as we do not need it.
2808 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002809
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002810 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002811 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002812
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002813 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2814 assert(LatchLoopDepth >= LoopDepth);
2815 BackedgeCondition =
2816 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2817 LatchLoopDepth - LoopDepth);
2818 UnionBackedgeCondition =
2819 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002820 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002821
2822 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2823 for (int i = 0; i < LoopDepth; i++)
2824 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2825
2826 isl_set *UnionBackedgeConditionComplement =
2827 isl_set_complement(UnionBackedgeCondition);
2828 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2829 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2830 UnionBackedgeConditionComplement =
2831 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2832 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2833 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2834
2835 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2836 HeaderBBDom = Parts.second;
2837
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002838 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2839 // the bounded assumptions to the context as they are already implied by the
2840 // <nsw> tag.
2841 if (Affinator.hasNSWAddRecForLoop(L)) {
2842 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002843 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002844 }
2845
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002846 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002847 recordAssumption(INFINITELOOP, UnboundedCtx,
2848 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002849 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002850}
2851
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002852MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
2853 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2854 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2855 if (!PointerBase)
2856 return nullptr;
2857
2858 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase->getValue());
2859 if (!PointerBaseInst)
2860 return nullptr;
2861
2862 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2863 if (!BasePtrStmt)
2864 return nullptr;
2865
2866 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2867}
2868
2869bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2870 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00002871 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
2872 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
2873 bool Hoistable = NHCtx != nullptr;
2874 isl_set_free(NHCtx);
2875 return !Hoistable;
2876 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002877
2878 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2879 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2880 if (auto *BasePtrInst = dyn_cast<Instruction>(PointerBase->getValue()))
2881 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00002882 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002883
2884 return false;
2885}
2886
Johannes Doerfert5210da52016-06-02 11:06:54 +00002887bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002888 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00002889 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002890
2891 if (buildAliasGroups(AA))
Johannes Doerfert5210da52016-06-02 11:06:54 +00002892 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002893
2894 // If a problem occurs while building the alias groups we need to delete
2895 // this SCoP and pretend it wasn't valid in the first place. To this end
2896 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002897 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002898
2899 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2900 << " could not be created as the number of parameters involved "
2901 "is too high. The SCoP will be "
2902 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2903 "the maximal number of parameters but be advised that the "
2904 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00002905 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002906}
2907
Johannes Doerfert9143d672014-09-27 11:02:39 +00002908bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002909 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002910 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002911 // for all memory accesses inside the SCoP.
2912 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002913 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002914 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002915 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002916 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002917 // if their access domains intersect, otherwise they are in different
2918 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002919 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002920 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002921 // and maximal accesses to each array of a group in read only and non
2922 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002923 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2924
2925 AliasSetTracker AST(AA);
2926
2927 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002928 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002929 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002930
2931 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002932 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002933 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2934 isl_set_free(StmtDomain);
2935 if (StmtDomainEmpty)
2936 continue;
2937
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002938 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002939 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002940 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002941 if (!MA->isRead())
2942 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002943 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002944 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00002945 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002946 else
2947 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002948 AST.add(Acc);
2949 }
2950 }
2951
2952 SmallVector<AliasGroupTy, 4> AliasGroups;
2953 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002954 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002955 continue;
2956 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002957 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002958 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002959 if (AG.size() < 2)
2960 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002961 AliasGroups.push_back(std::move(AG));
2962 }
2963
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002964 // Split the alias groups based on their domain.
2965 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2966 AliasGroupTy NewAG;
2967 AliasGroupTy &AG = AliasGroups[u];
2968 AliasGroupTy::iterator AGI = AG.begin();
2969 isl_set *AGDomain = getAccessDomain(*AGI);
2970 while (AGI != AG.end()) {
2971 MemoryAccess *MA = *AGI;
2972 isl_set *MADomain = getAccessDomain(MA);
2973 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2974 NewAG.push_back(MA);
2975 AGI = AG.erase(AGI);
2976 isl_set_free(MADomain);
2977 } else {
2978 AGDomain = isl_set_union(AGDomain, MADomain);
2979 AGI++;
2980 }
2981 }
2982 if (NewAG.size() > 1)
2983 AliasGroups.push_back(std::move(NewAG));
2984 isl_set_free(AGDomain);
2985 }
2986
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002987 auto &F = getFunction();
Mandeep Singh Grang48e7add2016-10-21 17:29:10 +00002988 MapVector<const Value *, SmallSetVector<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002989 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2990 for (AliasGroupTy &AG : AliasGroups) {
2991 NonReadOnlyBaseValues.clear();
2992 ReadOnlyPairs.clear();
2993
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002994 if (AG.size() < 2) {
2995 AG.clear();
2996 continue;
2997 }
2998
Johannes Doerfert13771732014-10-01 12:40:46 +00002999 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00003000 emitOptimizationRemarkAnalysis(
3001 F.getContext(), DEBUG_TYPE, F,
3002 (*II)->getAccessInstruction()->getDebugLoc(),
3003 "Possibly aliasing pointer, use restrict keyword.");
3004
Johannes Doerfert13771732014-10-01 12:40:46 +00003005 Value *BaseAddr = (*II)->getBaseAddr();
3006 if (HasWriteAccess.count(BaseAddr)) {
3007 NonReadOnlyBaseValues.insert(BaseAddr);
3008 II++;
3009 } else {
3010 ReadOnlyPairs[BaseAddr].insert(*II);
3011 II = AG.erase(II);
3012 }
3013 }
3014
3015 // If we don't have read only pointers check if there are at least two
3016 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00003017 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003018 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00003019 continue;
3020 }
3021
3022 // If we don't have non read only pointers clear the alias group.
3023 if (NonReadOnlyBaseValues.empty()) {
3024 AG.clear();
3025 continue;
3026 }
3027
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003028 // Check if we have non-affine accesses left, if so bail out as we cannot
3029 // generate a good access range yet.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003030 for (auto *MA : AG) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003031 if (!MA->isAffine()) {
3032 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3033 return false;
3034 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003035 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
3036 addRequiredInvariantLoad(
3037 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3038 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003039 for (auto &ReadOnlyPair : ReadOnlyPairs)
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003040 for (auto *MA : ReadOnlyPair.second) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003041 if (!MA->isAffine()) {
3042 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3043 return false;
3044 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003045 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
3046 addRequiredInvariantLoad(
3047 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3048 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003049
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003050 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003051 MinMaxAliasGroups.emplace_back();
3052 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3053 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
3054 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3055 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003056
3057 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003058
3059 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00003060 for (MemoryAccess *MA : AG)
3061 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003062
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003063 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
3064 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003065
3066 // Bail out if the number of values we need to compare is too large.
3067 // This is important as the number of comparisions grows quadratically with
3068 // the number of values we need to compare.
Johannes Doerfert5210da52016-06-02 11:06:54 +00003069 if (!Valid || (MinMaxAccessesNonReadOnly.size() + ReadOnlyPairs.size() >
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003070 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003071 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003072
3073 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003074 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003075 Accesses = isl_union_map_empty(getParamSpace());
3076
3077 for (const auto &ReadOnlyPair : ReadOnlyPairs)
3078 for (MemoryAccess *MA : ReadOnlyPair.second)
3079 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
3080
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003081 Valid =
3082 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003083
3084 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003085 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003086 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003087
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003088 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003089}
3090
Tobias Grosserc80d6972016-09-02 06:33:33 +00003091/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003092static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003093 // Start with the smallest loop containing the entry and expand that
3094 // loop until it contains all blocks in the region. If there is a loop
3095 // containing all blocks in the region check if it is itself contained
3096 // and if so take the parent loop as it will be the smallest containing
3097 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003098 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003099 while (L) {
3100 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003101 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003102 AllContained &= L->contains(BB);
3103 if (AllContained)
3104 break;
3105 L = L->getParentLoop();
3106 }
3107
Johannes Doerfertef744432016-05-23 12:42:38 +00003108 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003109}
3110
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003111Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003112 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003113 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003114 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003115 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3116 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3117 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3118 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003119 if (IslOnErrorAbort)
3120 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003121 buildContext();
3122}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003123
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003124void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT,
3125 LoopInfo &LI) {
3126 buildInvariantEquivalenceClasses();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003127
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003128 if (!buildDomains(&R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003129 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003130
Johannes Doerfertff68f462016-04-19 14:49:42 +00003131 addUserAssumptions(AC, DT, LI);
3132
Johannes Doerfert26404542016-05-10 12:19:47 +00003133 // Remove empty statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003134 // Exit early in case there are no executable statements left in this scop.
Michael Kruse977d38b2016-07-22 17:31:17 +00003135 simplifySCoP(false);
Michael Kruseafe06702015-10-02 16:33:27 +00003136 if (Stmts.empty())
3137 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003138
Michael Krusecac948e2015-10-02 13:53:07 +00003139 // The ScopStmts now have enough information to initialize themselves.
3140 for (ScopStmt &Stmt : Stmts)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003141 Stmt.init(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00003142
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003143 // Check early for profitability. Afterwards it cannot change anymore,
3144 // only the runtime context could become infeasible.
3145 if (!isProfitable()) {
3146 invalidate(PROFITABLE, DebugLoc());
Tobias Grosser8286b832015-11-02 11:29:32 +00003147 return;
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003148 }
3149
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003150 buildSchedule(LI);
Tobias Grosser8286b832015-11-02 11:29:32 +00003151
3152 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003153 realignParams();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003154 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003155
3156 // After the context was fully constructed, thus all our knowledge about
3157 // the parameters is in there, we add all recorded assumptions to the
3158 // assumed/invalid context.
3159 addRecordedAssumptions();
3160
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003161 simplifyContexts();
Johannes Doerfert5210da52016-06-02 11:06:54 +00003162 if (!buildAliasChecks(AA))
3163 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003164
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003165 hoistInvariantLoads();
3166 verifyInvariantLoads();
Michael Kruse977d38b2016-07-22 17:31:17 +00003167 simplifySCoP(true);
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003168
3169 // Check late for a feasible runtime context because profitability did not
3170 // change.
3171 if (!hasFeasibleRuntimeContext()) {
3172 invalidate(PROFITABLE, DebugLoc());
3173 return;
3174 }
Tobias Grosser75805372011-04-29 06:27:02 +00003175}
3176
3177Scop::~Scop() {
3178 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003179 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003180 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003181 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003182
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003183 for (auto &It : ParameterIds)
3184 isl_id_free(It.second);
3185
Johannes Doerfert96425c22015-08-30 21:13:53 +00003186 for (auto It : DomainMap)
3187 isl_set_free(It.second);
3188
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003189 for (auto &AS : RecordedAssumptions)
3190 isl_set_free(AS.Set);
3191
Johannes Doerfertb164c792014-09-18 11:17:17 +00003192 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003193 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003194 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003195 isl_pw_multi_aff_free(MMA.first);
3196 isl_pw_multi_aff_free(MMA.second);
3197 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003198 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003199 isl_pw_multi_aff_free(MMA.first);
3200 isl_pw_multi_aff_free(MMA.second);
3201 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003202 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003203
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003204 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003205 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003206
3207 // Explicitly release all Scop objects and the underlying isl objects before
3208 // we relase the isl context.
3209 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003210 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003211 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003212 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003213 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003214}
3215
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003216void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003217 // Check all array accesses for each base pointer and find a (virtual) element
3218 // size for the base pointer that divides all access functions.
3219 for (auto &Stmt : *this)
3220 for (auto *Access : Stmt) {
3221 if (!Access->isArrayKind())
3222 continue;
3223 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
3224 ScopArrayInfo::MK_Array)];
3225 if (SAI->getNumberOfDimensions() != 1)
3226 continue;
3227 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3228 auto *Subscript = Access->getSubscript(0);
3229 while (!isDivisible(Subscript, DivisibleSize, *SE))
3230 DivisibleSize /= 2;
3231 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3232 SAI->updateElementType(Ty);
3233 }
3234
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003235 for (auto &Stmt : *this)
3236 for (auto &Access : Stmt)
3237 Access->updateDimensionality();
3238}
3239
Michael Kruse977d38b2016-07-22 17:31:17 +00003240void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003241 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3242 ScopStmt &Stmt = *StmtIt;
3243
Johannes Doerfert26404542016-05-10 12:19:47 +00003244 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003245 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003246 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003247
Johannes Doerferteca9e892015-11-03 16:54:49 +00003248 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003249 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003250 bool OnlyRead = true;
3251 for (MemoryAccess *MA : Stmt) {
3252 if (MA->isRead())
3253 continue;
3254
3255 OnlyRead = false;
3256 break;
3257 }
3258
3259 RemoveStmt = OnlyRead;
3260 }
3261
Johannes Doerfert26404542016-05-10 12:19:47 +00003262 if (!RemoveStmt) {
3263 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003264 continue;
3265 }
3266
Johannes Doerfert26404542016-05-10 12:19:47 +00003267 // Remove the statement because it is unnecessary.
3268 if (Stmt.isRegionStmt())
3269 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3270 StmtMap.erase(BB);
3271 else
3272 StmtMap.erase(Stmt.getBasicBlock());
3273
3274 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003275 }
3276}
3277
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003278InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003279 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3280 if (!LInst)
3281 return nullptr;
3282
3283 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3284 LInst = cast<LoadInst>(Rep);
3285
Johannes Doerfert96e54712016-02-07 17:30:13 +00003286 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003287 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003288 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003289 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003290 continue;
3291
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003292 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003293 for (auto *MA : MAs)
3294 if (MA->getAccessInstruction() == Val)
3295 return &IAClass;
3296 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003297
3298 return nullptr;
3299}
3300
Tobias Grosserc80d6972016-09-02 06:33:33 +00003301/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003302static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003303 bool MAInvalidCtxIsEmpty,
3304 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003305 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3306 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3307 // TODO: We can provide more information for better but more expensive
3308 // results.
3309 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3310 LInst->getAlignment(), DL))
3311 return false;
3312
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003313 // If the location might be overwritten we do not hoist it unconditionally.
3314 //
3315 // TODO: This is probably to conservative.
3316 if (!NonHoistableCtxIsEmpty)
3317 return false;
3318
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003319 // If a dereferencable load is in a statement that is modeled precisely we can
3320 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003321 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003322 return true;
3323
3324 // Even if the statement is not modeled precisely we can hoist the load if it
3325 // does not involve any parameters that might have been specilized by the
3326 // statement domain.
3327 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3328 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3329 return false;
3330 return true;
3331}
3332
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003333void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003334
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003335 if (InvMAs.empty())
3336 return;
3337
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003338 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003339 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003340
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003341 // Get the context under which the statement is executed but remove the error
3342 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003343 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003344 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003345
Michael Krusebc150122016-05-02 12:25:18 +00003346 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctionsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003347 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003348 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3349 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003350 for (auto &InvMA : InvMAs)
3351 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003352 return;
3353 }
3354
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003355 // Project out all parameters that relate to loads in the statement. Otherwise
3356 // we could have cyclic dependences on the constraints under which the
3357 // hoisted loads are executed and we could not determine an order in which to
3358 // pre-load them. This happens because not only lower bounds are part of the
3359 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003360 for (auto &InvMA : InvMAs) {
3361 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003362 Instruction *AccInst = MA->getAccessInstruction();
3363 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003364 SetVector<Value *> Values;
3365 for (const SCEV *Parameter : Parameters) {
3366 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003367 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003368 if (!Values.count(AccInst))
3369 continue;
3370
3371 if (isl_id *ParamId = getIdForParam(Parameter)) {
3372 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3373 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3374 isl_id_free(ParamId);
3375 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003376 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003377 }
3378 }
3379
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003380 for (auto &InvMA : InvMAs) {
3381 auto *MA = InvMA.MA;
3382 auto *NHCtx = InvMA.NonHoistableCtx;
3383
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003384 // Check for another invariant access that accesses the same location as
3385 // MA and if found consolidate them. Otherwise create a new equivalence
3386 // class at the end of InvariantEquivClasses.
3387 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003388 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003389 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3390
Johannes Doerfert85676e32016-04-23 14:32:34 +00003391 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003392 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003393 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3394
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003395 isl_set *MACtx;
3396 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003397 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3398 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003399 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003400 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003401 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003402 } else {
3403 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003404 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003405 MACtx = isl_set_gist_params(MACtx, getContext());
3406 }
3407
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003408 bool Consolidated = false;
3409 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003410 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003411 continue;
3412
Johannes Doerfertdf880232016-03-03 12:26:58 +00003413 // If the pointer and the type is equal check if the access function wrt.
3414 // to the domain is equal too. It can happen that the domain fixes
3415 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003416 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003417 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003418 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003419 if (!MAs.empty()) {
3420 auto *LastMA = MAs.front();
3421
3422 auto *AR = isl_map_range(MA->getAccessRelation());
3423 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3424 bool SameAR = isl_set_is_equal(AR, LastAR);
3425 isl_set_free(AR);
3426 isl_set_free(LastAR);
3427
3428 if (!SameAR)
3429 continue;
3430 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003431
3432 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003433 MAs.push_front(MA);
3434
Johannes Doerfertdf880232016-03-03 12:26:58 +00003435 Consolidated = true;
3436
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003437 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003438 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003439 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003440 IAClassDomainCtx =
3441 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003442 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003443 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003444 break;
3445 }
3446
3447 if (Consolidated)
3448 continue;
3449
3450 // If we did not consolidate MA, thus did not find an equivalence class
3451 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003452 InvariantEquivClasses.emplace_back(
3453 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003454 }
3455
3456 isl_set_free(DomainCtx);
3457}
3458
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003459__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3460 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003461 // TODO: Loads that are not loop carried, hence are in a statement with
3462 // zero iterators, are by construction invariant, though we
3463 // currently "hoist" them anyway. This is necessary because we allow
3464 // them to be treated as parameters (e.g., in conditions) and our code
3465 // generation would otherwise use the old value.
3466
3467 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003468 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003469
3470 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003471 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003472
3473 // Skip accesses that have an invariant base pointer which is defined but
3474 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3475 // returns a pointer that is used as a base address. However, as we want
3476 // to hoist indirect pointers, we allow the base pointer to be defined in
3477 // the region if it is also a memory access. Each ScopArrayInfo object
3478 // that has a base pointer origin has a base pointer that is loaded and
3479 // that it is invariant, thus it will be hoisted too. However, if there is
3480 // no base pointer origin we check that the base pointer is defined
3481 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003482 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003483 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003484 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003485
3486 // Skip accesses in non-affine subregions as they might not be executed
3487 // under the same condition as the entry of the non-affine subregion.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003488 if (BB != LI->getParent())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003489 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003490
3491 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003492 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003493
3494 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3495 Stmt.getNumIterators())) {
3496 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003497 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003498 }
3499
3500 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3501 isl_set *AccessRange = isl_map_range(AccessRelation);
3502
3503 isl_union_map *Written = isl_union_map_intersect_range(
3504 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003505 auto *WrittenCtx = isl_union_map_params(Written);
3506 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003507
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003508 if (!IsWritten)
3509 return WrittenCtx;
3510
3511 WrittenCtx = isl_set_remove_divs(WrittenCtx);
3512 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctionsInDomain;
3513 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3514 isl_set_free(WrittenCtx);
3515 return nullptr;
3516 }
3517
3518 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3519 AS_RESTRICTION);
3520 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003521}
3522
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003523void Scop::verifyInvariantLoads() {
3524 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003525 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003526 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003527 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003528 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003529 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3530 return;
3531 }
3532 }
3533}
3534
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003535void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003536 if (!PollyInvariantLoadHoisting)
3537 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003538
Tobias Grosser0865e7752016-02-29 07:29:42 +00003539 isl_union_map *Writes = getWrites();
3540 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003541 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003542
Tobias Grosser0865e7752016-02-29 07:29:42 +00003543 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003544 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3545 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003546
3547 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003548 for (auto InvMA : InvariantAccesses)
3549 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003550 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003551 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003552 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003553}
3554
Roman Gareevd7754a12016-07-30 09:25:51 +00003555const ScopArrayInfo *Scop::getOrCreateScopArrayInfo(
3556 Value *BasePtr, Type *ElementType, ArrayRef<const SCEV *> Sizes,
3557 ScopArrayInfo::MemoryKind Kind, const char *BaseName) {
3558 assert((BasePtr || BaseName) &&
3559 "BasePtr and BaseName can not be nullptr at the same time.");
3560 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3561 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3562 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003563 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003564 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003565 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003566 DL, this, BaseName));
3567 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003568 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003569 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003570 // In case of mismatching array sizes, we bail out by setting the run-time
3571 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003572 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003573 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003574 }
Tobias Grosserab671442015-05-23 05:58:27 +00003575 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003576}
3577
Roman Gareevd7754a12016-07-30 09:25:51 +00003578const ScopArrayInfo *
3579Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3580 const std::vector<unsigned> &Sizes) {
3581 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3582 std::vector<const SCEV *> SCEVSizes;
3583
3584 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003585 if (size)
3586 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3587 else
3588 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003589
3590 auto *SAI =
3591 getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3592 ScopArrayInfo::MK_Array, BaseName.c_str());
3593 return SAI;
3594}
3595
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003596const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003597 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003598 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003599 assert(SAI && "No ScopArrayInfo available for this base pointer");
3600 return SAI;
3601}
3602
Tobias Grosser74394f02013-01-14 22:40:23 +00003603std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003604
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003605std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003606 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003607 return stringFromIslObj(AssumedContext);
3608}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003609
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003610std::string Scop::getInvalidContextStr() const {
3611 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003612}
Tobias Grosser75805372011-04-29 06:27:02 +00003613
3614std::string Scop::getNameStr() const {
3615 std::string ExitName, EntryName;
3616 raw_string_ostream ExitStr(ExitName);
3617 raw_string_ostream EntryStr(EntryName);
3618
Tobias Grosserf240b482014-01-09 10:42:15 +00003619 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003620 EntryStr.str();
3621
3622 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003623 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003624 ExitStr.str();
3625 } else
3626 ExitName = "FunctionExit";
3627
3628 return EntryName + "---" + ExitName;
3629}
3630
Tobias Grosser74394f02013-01-14 22:40:23 +00003631__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003632__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003633 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003634}
3635
Tobias Grossere86109f2013-10-29 21:05:49 +00003636__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003637 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003638 return isl_set_copy(AssumedContext);
3639}
3640
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003641bool Scop::isProfitable() const {
3642 if (PollyProcessUnprofitable)
3643 return true;
3644
3645 if (!hasFeasibleRuntimeContext())
3646 return false;
3647
3648 if (isEmpty())
3649 return false;
3650
3651 unsigned OptimizableStmtsOrLoops = 0;
3652 for (auto &Stmt : *this) {
3653 if (Stmt.getNumIterators() == 0)
3654 continue;
3655
3656 bool ContainsArrayAccs = false;
3657 bool ContainsScalarAccs = false;
3658 for (auto *MA : Stmt) {
3659 if (MA->isRead())
3660 continue;
3661 ContainsArrayAccs |= MA->isArrayKind();
3662 ContainsScalarAccs |= MA->isScalarKind();
3663 }
3664
Michael Kruse6ab44762016-10-04 17:33:39 +00003665 if (!UnprofitableScalarAccs || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003666 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3667 }
3668
3669 return OptimizableStmtsOrLoops > 1;
3670}
3671
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003672bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003673 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003674 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003675 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3676 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3677 isl_set_is_subset(PositiveContext, NegativeContext));
3678 isl_set_free(PositiveContext);
3679 if (!IsFeasible) {
3680 isl_set_free(NegativeContext);
3681 return false;
3682 }
3683
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003684 auto *DomainContext = isl_union_set_params(getDomains());
3685 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003686 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003687 isl_set_free(NegativeContext);
3688 isl_set_free(DomainContext);
3689
Johannes Doerfert43788c52015-08-20 05:58:56 +00003690 return IsFeasible;
3691}
3692
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003693static std::string toString(AssumptionKind Kind) {
3694 switch (Kind) {
3695 case ALIASING:
3696 return "No-aliasing";
3697 case INBOUNDS:
3698 return "Inbounds";
3699 case WRAPPING:
3700 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00003701 case UNSIGNED:
3702 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003703 case COMPLEXITY:
3704 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003705 case PROFITABLE:
3706 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003707 case ERRORBLOCK:
3708 return "No-error";
3709 case INFINITELOOP:
3710 return "Finite loop";
3711 case INVARIANTLOAD:
3712 return "Invariant load";
3713 case DELINEARIZATION:
3714 return "Delinearization";
3715 }
3716 llvm_unreachable("Unknown AssumptionKind!");
3717}
3718
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003719bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
3720 if (Sign == AS_ASSUMPTION) {
3721 if (isl_set_is_subset(Context, Set))
3722 return false;
3723
3724 if (isl_set_is_subset(AssumedContext, Set))
3725 return false;
3726 } else {
3727 if (isl_set_is_disjoint(Set, Context))
3728 return false;
3729
3730 if (isl_set_is_subset(Set, InvalidContext))
3731 return false;
3732 }
3733 return true;
3734}
3735
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003736bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3737 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003738 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
3739 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003740
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003741 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003742 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3743 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003744 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003745 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003746}
3747
3748void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003749 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003750 // Simplify the assumptions/restrictions first.
3751 Set = isl_set_gist_params(Set, getContext());
3752
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003753 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3754 isl_set_free(Set);
3755 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003756 }
3757
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003758 if (Sign == AS_ASSUMPTION) {
3759 AssumedContext = isl_set_intersect(AssumedContext, Set);
3760 AssumedContext = isl_set_coalesce(AssumedContext);
3761 } else {
3762 InvalidContext = isl_set_union(InvalidContext, Set);
3763 InvalidContext = isl_set_coalesce(InvalidContext);
3764 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003765}
3766
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003767void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003768 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
3769 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003770}
3771
3772void Scop::addRecordedAssumptions() {
3773 while (!RecordedAssumptions.empty()) {
3774 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003775
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003776 if (!AS.BB) {
3777 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
3778 continue;
3779 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003780
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003781 // If the domain was deleted the assumptions are void.
3782 isl_set *Dom = getDomainConditions(AS.BB);
3783 if (!Dom) {
3784 isl_set_free(AS.Set);
3785 continue;
3786 }
3787
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003788 // If a basic block was given use its domain to simplify the assumption.
3789 // In case of restrictions we know they only have to hold on the domain,
3790 // thus we can intersect them with the domain of the block. However, for
3791 // assumptions the domain has to imply them, thus:
3792 // _ _____
3793 // Dom => S <==> A v B <==> A - B
3794 //
3795 // To avoid the complement we will register A - B as a restricton not an
3796 // assumption.
3797 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003798 if (AS.Sign == AS_RESTRICTION)
3799 S = isl_set_params(isl_set_intersect(S, Dom));
3800 else /* (AS.Sign == AS_ASSUMPTION) */
3801 S = isl_set_params(isl_set_subtract(Dom, S));
3802
3803 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003804 }
3805}
3806
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003807void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003808 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003809}
3810
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003811__isl_give isl_set *Scop::getInvalidContext() const {
3812 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003813}
3814
Tobias Grosser75805372011-04-29 06:27:02 +00003815void Scop::printContext(raw_ostream &OS) const {
3816 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003817 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003818
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003819 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003820 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003821
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003822 OS.indent(4) << "Invalid Context:\n";
3823 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003824
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003825 unsigned Dim = 0;
3826 for (const SCEV *Parameter : Parameters)
3827 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003828}
3829
Johannes Doerfertb164c792014-09-18 11:17:17 +00003830void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003831 int noOfGroups = 0;
3832 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003833 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003834 noOfGroups += 1;
3835 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003836 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003837 }
3838
Tobias Grosserbb853c22015-07-25 12:31:03 +00003839 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003840 if (MinMaxAliasGroups.empty()) {
3841 OS.indent(8) << "n/a\n";
3842 return;
3843 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003844
Tobias Grosserbb853c22015-07-25 12:31:03 +00003845 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003846
3847 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003848 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003849 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003850 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003851 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3852 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003853 }
3854 OS << " ]]\n";
3855 }
3856
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003857 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003858 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003859 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003860 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003861 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3862 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003863 }
3864 OS << " ]]\n";
3865 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003866 }
3867}
3868
Tobias Grosser75805372011-04-29 06:27:02 +00003869void Scop::printStatements(raw_ostream &OS) const {
3870 OS << "Statements {\n";
3871
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003872 for (const ScopStmt &Stmt : *this)
3873 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003874
3875 OS.indent(4) << "}\n";
3876}
3877
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003878void Scop::printArrayInfo(raw_ostream &OS) const {
3879 OS << "Arrays {\n";
3880
Tobias Grosserab671442015-05-23 05:58:27 +00003881 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00003882 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003883
3884 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003885
3886 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3887
3888 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00003889 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003890
3891 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003892}
3893
Tobias Grosser75805372011-04-29 06:27:02 +00003894void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003895 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003896 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003897 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003898 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003899 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003900 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003901 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003902 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003903 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003904 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003905 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
3906 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003907 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003908 }
3909 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003910 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003911 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003912 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003913 printStatements(OS.indent(4));
3914}
3915
3916void Scop::dump() const { print(dbgs()); }
3917
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003918isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003919
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003920__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
3921 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003922 // First try to use the SCEVAffinator to generate a piecewise defined
3923 // affine function from @p E in the context of @p BB. If that tasks becomes to
3924 // complex the affinator might return a nullptr. In such a case we invalidate
3925 // the SCoP and return a dummy value. This way we do not need to add error
3926 // handling cdoe to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003927 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003928 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00003929 // TODO: We could use a heuristic and either use:
3930 // SCEVAffinator::takeNonNegativeAssumption
3931 // or
3932 // SCEVAffinator::interpretAsUnsigned
3933 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003934 if (NonNegative)
3935 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003936 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003937 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003938
3939 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
3940 invalidate(COMPLEXITY, DL);
3941 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003942}
3943
Tobias Grosser808cd692015-07-14 09:33:13 +00003944__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003945 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003946
Tobias Grosser808cd692015-07-14 09:33:13 +00003947 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003948 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003949
3950 return Domain;
3951}
3952
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003953__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
3954 PWACtx PWAC = getPwAff(E, BB);
3955 isl_set_free(PWAC.second);
3956 return PWAC.first;
3957}
3958
Tobias Grossere5a35142015-11-12 14:07:09 +00003959__isl_give isl_union_map *
3960Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3961 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003962
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003963 for (ScopStmt &Stmt : *this) {
3964 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003965 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003966 continue;
3967
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003968 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003969 isl_map *AccessDomain = MA->getAccessRelation();
3970 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003971 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003972 }
3973 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003974 return isl_union_map_coalesce(Accesses);
3975}
3976
3977__isl_give isl_union_map *Scop::getMustWrites() {
3978 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003979}
3980
3981__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003982 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003983}
3984
Tobias Grosser37eb4222014-02-20 21:43:54 +00003985__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003986 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003987}
3988
3989__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003990 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003991}
3992
Tobias Grosser2ac23382015-11-12 14:07:13 +00003993__isl_give isl_union_map *Scop::getAccesses() {
3994 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3995}
3996
Roman Gareevb3224ad2016-09-14 06:26:09 +00003997// Check whether @p Node is an extension node.
3998//
3999// @return true if @p Node is an extension node.
4000isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4001 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4002 return isl_bool_error;
4003 else
4004 return isl_bool_true;
4005}
4006
4007bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4008 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4009 nullptr) == isl_stat_error;
4010}
4011
Tobias Grosser808cd692015-07-14 09:33:13 +00004012__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004013 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004014 if (containsExtensionNode(Tree)) {
4015 isl_schedule_free(Tree);
4016 return nullptr;
4017 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004018 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004019 isl_schedule_free(Tree);
4020 return S;
4021}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004022
Tobias Grosser808cd692015-07-14 09:33:13 +00004023__isl_give isl_schedule *Scop::getScheduleTree() const {
4024 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4025 getDomains());
4026}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004027
Tobias Grosser808cd692015-07-14 09:33:13 +00004028void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4029 auto *S = isl_schedule_from_domain(getDomains());
4030 S = isl_schedule_insert_partial_schedule(
4031 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4032 isl_schedule_free(Schedule);
4033 Schedule = S;
4034}
4035
4036void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4037 isl_schedule_free(Schedule);
4038 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004039}
4040
4041bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4042 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004043 for (ScopStmt &Stmt : *this) {
4044 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004045 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4046 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4047
4048 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4049 isl_union_set_free(StmtDomain);
4050 isl_union_set_free(NewStmtDomain);
4051 continue;
4052 }
4053
4054 Changed = true;
4055
4056 isl_union_set_free(StmtDomain);
4057 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4058
4059 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004060 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004061 isl_union_set_free(NewStmtDomain);
4062 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004063 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004064 }
4065 isl_union_set_free(Domain);
4066 return Changed;
4067}
4068
Tobias Grosser75805372011-04-29 06:27:02 +00004069ScalarEvolution *Scop::getSE() const { return SE; }
4070
Tobias Grosser808cd692015-07-14 09:33:13 +00004071struct MapToDimensionDataTy {
4072 int N;
4073 isl_union_pw_multi_aff *Res;
4074};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004075
Tobias Grosserc80d6972016-09-02 06:33:33 +00004076// Create a function that maps the elements of 'Set' to its N-th dimension and
4077// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004078//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004079// @param Set The input set.
4080// @param User->N The dimension to map to.
4081// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004082//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004083// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004084static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4085 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4086 int Dim;
4087 isl_space *Space;
4088 isl_pw_multi_aff *PMA;
4089
4090 Dim = isl_set_dim(Set, isl_dim_set);
4091 Space = isl_set_get_space(Set);
4092 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4093 Dim - Data->N);
4094 if (Data->N > 1)
4095 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4096 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4097
4098 isl_set_free(Set);
4099
4100 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004101}
4102
Tobias Grosserc80d6972016-09-02 06:33:33 +00004103// Create an isl_multi_union_aff that defines an identity mapping from the
4104// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004105//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004106// # Example:
4107//
4108// Domain: { A[i,j]; B[i,j,k] }
4109// N: 1
4110//
4111// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4112//
4113// @param USet A union set describing the elements for which to generate a
4114// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004115// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004116// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004117static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004118mapToDimension(__isl_take isl_union_set *USet, int N) {
4119 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004120 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004121 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004122
Tobias Grosser808cd692015-07-14 09:33:13 +00004123 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004124
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004125 auto *Space = isl_union_set_get_space(USet);
4126 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004127
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004128 Data = {N, PwAff};
4129
4130 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004131 (void)Res;
4132
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004133 assert(Res == isl_stat_ok);
4134
4135 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004136 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4137}
4138
Tobias Grosser316b5b22015-11-11 19:28:14 +00004139void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00004140 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00004141 Stmts.emplace_back(*this, *BB);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004142 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004143 StmtMap[BB] = Stmt;
4144 } else {
4145 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00004146 Stmts.emplace_back(*this, *R);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004147 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004148 for (BasicBlock *BB : R->blocks())
4149 StmtMap[BB] = Stmt;
4150 }
Tobias Grosser808cd692015-07-14 09:33:13 +00004151}
4152
Roman Gareevb3224ad2016-09-14 06:26:09 +00004153ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4154 __isl_take isl_map *TargetRel,
4155 __isl_take isl_set *Domain) {
Tobias Grosser744740a2016-11-05 21:02:43 +00004156 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4157 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4158 assert(isl_set_is_subset(Domain, TargetDomain) &&
4159 "Target access not defined for complete statement domain");
4160 assert(isl_set_is_subset(Domain, SourceDomain) &&
4161 "Source access not defined for complete statement domain");
4162 isl_set_free(SourceDomain);
4163 isl_set_free(TargetDomain);
Roman Gareevb3224ad2016-09-14 06:26:09 +00004164 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4165 CopyStmtsNum++;
4166 return &(Stmts.back());
4167}
4168
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004169void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004170 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004171 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004172 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004173 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4174 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004175}
4176
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004177/// To generate a schedule for the elements in a Region we traverse the Region
4178/// in reverse-post-order and add the contained RegionNodes in traversal order
4179/// to the schedule of the loop that is currently at the top of the LoopStack.
4180/// For loop-free codes, this results in a correct sequential ordering.
4181///
4182/// Example:
4183/// bb1(0)
4184/// / \.
4185/// bb2(1) bb3(2)
4186/// \ / \.
4187/// bb4(3) bb5(4)
4188/// \ /
4189/// bb6(5)
4190///
4191/// Including loops requires additional processing. Whenever a loop header is
4192/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4193/// from an empty schedule, we first process all RegionNodes that are within
4194/// this loop and complete the sequential schedule at this loop-level before
4195/// processing about any other nodes. To implement this
4196/// loop-nodes-first-processing, the reverse post-order traversal is
4197/// insufficient. Hence, we additionally check if the traversal yields
4198/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4199/// These region-nodes are then queue and only traverse after the all nodes
4200/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004201void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004202 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004203
4204 ReversePostOrderTraversal<Region *> RTraversal(R);
4205 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4206 std::deque<RegionNode *> DelayList;
4207 bool LastRNWaiting = false;
4208
4209 // Iterate over the region @p R in reverse post-order but queue
4210 // sub-regions/blocks iff they are not part of the last encountered but not
4211 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4212 // that we queued the last sub-region/block from the reverse post-order
4213 // iterator. If it is set we have to explore the next sub-region/block from
4214 // the iterator (if any) to guarantee progress. If it is not set we first try
4215 // the next queued sub-region/blocks.
4216 while (!WorkList.empty() || !DelayList.empty()) {
4217 RegionNode *RN;
4218
4219 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4220 RN = WorkList.front();
4221 WorkList.pop_front();
4222 LastRNWaiting = false;
4223 } else {
4224 RN = DelayList.front();
4225 DelayList.pop_front();
4226 }
4227
4228 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004229 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004230 L = OuterScopLoop;
4231
Tobias Grosser151ae322016-04-03 19:36:52 +00004232 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004233 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004234 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004235 LastRNWaiting = true;
4236 DelayList.push_back(RN);
4237 continue;
4238 }
4239 LoopStack.push_back({L, nullptr, 0});
4240 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004241 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004242 }
4243
4244 return;
4245}
4246
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004247void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004248
Tobias Grosser8362c262016-01-06 15:30:06 +00004249 if (RN->isSubRegion()) {
4250 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004251 if (!isNonAffineSubRegion(LocalRegion)) {
4252 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004253 return;
4254 }
4255 }
Michael Kruse046dde42015-08-10 13:01:57 +00004256
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004257 auto &LoopData = LoopStack.back();
4258 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004259
Michael Kruse6f7721f2016-02-24 22:08:19 +00004260 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004261 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4262 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004263 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004264 }
4265
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004266 // Check if we just processed the last node in this loop. If we did, finalize
4267 // the loop by:
4268 //
4269 // - adding new schedule dimensions
4270 // - folding the resulting schedule into the parent loop schedule
4271 // - dropping the loop schedule from the LoopStack.
4272 //
4273 // Then continue to check surrounding loops, which might also have been
4274 // completed by this node.
4275 while (LoopData.L &&
4276 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004277 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004278 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004279
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004280 LoopStack.pop_back();
4281 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004282
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004283 if (Schedule) {
4284 auto *Domain = isl_schedule_get_domain(Schedule);
4285 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4286 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4287 NextLoopData.Schedule =
4288 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004289 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004290
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004291 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4292 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004293 }
Tobias Grosser75805372011-04-29 06:27:02 +00004294}
4295
Michael Kruse6f7721f2016-02-24 22:08:19 +00004296ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004297 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004298 if (StmtMapIt == StmtMap.end())
4299 return nullptr;
4300 return StmtMapIt->second;
4301}
4302
Michael Kruse6f7721f2016-02-24 22:08:19 +00004303ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4304 if (RN->isSubRegion())
4305 return getStmtFor(RN->getNodeAs<Region>());
4306 return getStmtFor(RN->getNodeAs<BasicBlock>());
4307}
4308
4309ScopStmt *Scop::getStmtFor(Region *R) const {
4310 ScopStmt *Stmt = getStmtFor(R->getEntry());
4311 assert(!Stmt || Stmt->getRegion() == R);
4312 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004313}
4314
Johannes Doerfert96425c22015-08-30 21:13:53 +00004315int Scop::getRelativeLoopDepth(const Loop *L) const {
4316 Loop *OuterLoop =
4317 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4318 if (!OuterLoop)
4319 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004320 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4321}
4322
Roman Gareevd7754a12016-07-30 09:25:51 +00004323ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4324 for (auto &SAI : arrays()) {
4325 if (SAI->getName() == BaseName)
4326 return SAI;
4327 }
4328 return nullptr;
4329}
4330
Johannes Doerfert99191c72016-05-31 09:41:04 +00004331//===----------------------------------------------------------------------===//
4332void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4333 AU.addRequired<LoopInfoWrapperPass>();
4334 AU.addRequired<RegionInfoPass>();
4335 AU.addRequired<DominatorTreeWrapperPass>();
4336 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4337 AU.addRequiredTransitive<ScopDetection>();
4338 AU.addRequired<AAResultsWrapperPass>();
4339 AU.addRequired<AssumptionCacheTracker>();
4340 AU.setPreservesAll();
4341}
4342
4343bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4344 auto &SD = getAnalysis<ScopDetection>();
4345
4346 if (!SD.isMaxRegionInScop(*R))
4347 return false;
4348
4349 Function *F = R->getEntry()->getParent();
4350 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4351 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4352 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4353 auto const &DL = F->getParent()->getDataLayout();
4354 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4355 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
4356
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004357 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4358 S = SB.getScop(); // take ownership of scop object
Tobias Grosser75805372011-04-29 06:27:02 +00004359 return false;
4360}
4361
Johannes Doerfert99191c72016-05-31 09:41:04 +00004362void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004363 if (S)
4364 S->print(OS);
4365 else
4366 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004367}
Tobias Grosser75805372011-04-29 06:27:02 +00004368
Johannes Doerfert99191c72016-05-31 09:41:04 +00004369char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004370
Johannes Doerfert99191c72016-05-31 09:41:04 +00004371Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4372
4373INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004374 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004375 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004376INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004377INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004378INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004379INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004380INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004381INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004382INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004383INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004384 "Polly - Create polyhedral description of Scops", false,
4385 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004386
4387//===----------------------------------------------------------------------===//
4388void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4389 AU.addRequired<LoopInfoWrapperPass>();
4390 AU.addRequired<RegionInfoPass>();
4391 AU.addRequired<DominatorTreeWrapperPass>();
4392 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4393 AU.addRequiredTransitive<ScopDetection>();
4394 AU.addRequired<AAResultsWrapperPass>();
4395 AU.addRequired<AssumptionCacheTracker>();
4396 AU.setPreservesAll();
4397}
4398
4399bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4400 auto &SD = getAnalysis<ScopDetection>();
4401
4402 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4403 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4404 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4405 auto const &DL = F.getParent()->getDataLayout();
4406 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4407 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4408
4409 /// Create polyhedral descripton of scops for all the valid regions of a
4410 /// function.
4411 for (auto &It : SD) {
4412 Region *R = const_cast<Region *>(It);
4413 if (!SD.isMaxRegionInScop(*R))
4414 continue;
4415
4416 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004417 std::unique_ptr<Scop> S = SB.getScop();
4418 if (!S)
4419 continue;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004420 bool Inserted =
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004421 RegionToScopMap.insert(std::make_pair(R, std::move(S))).second;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004422 assert(Inserted && "Building Scop for the same region twice!");
4423 (void)Inserted;
4424 }
4425 return false;
4426}
4427
4428void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4429 for (auto &It : RegionToScopMap) {
4430 if (It.second)
4431 It.second->print(OS);
4432 else
4433 OS << "Invalid Scop!\n";
4434 }
4435}
4436
4437char ScopInfoWrapperPass::ID = 0;
4438
4439Pass *polly::createScopInfoWrapperPassPass() {
4440 return new ScopInfoWrapperPass();
4441}
4442
4443INITIALIZE_PASS_BEGIN(
4444 ScopInfoWrapperPass, "polly-function-scops",
4445 "Polly - Create polyhedral description of all Scops of a function", false,
4446 false);
4447INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
4448INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
4449INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4450INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4451INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4452INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4453INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4454INITIALIZE_PASS_END(
4455 ScopInfoWrapperPass, "polly-function-scops",
4456 "Polly - Create polyhedral description of all Scops of a function", false,
4457 false)