blob: 174160ff259de53ad5f5e41312944b401a90a568 [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
Michael Krusee2bccbb2015-09-18 19:59:43 +0000819 if (!isAffine()) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000820 if (isa<MemIntrinsic>(getAccessInstruction()))
821 buildMemIntrinsicAccessRelation();
822
Tobias Grosser4f967492013-06-23 05:21:18 +0000823 // We overapproximate non-affine accesses with a possible access to the
824 // whole array. For read accesses it does not make a difference, if an
825 // access must or may happen. However, for write accesses it is important to
826 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000827 if (!AccessRelation)
828 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
829
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000830 AccessRelation =
831 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000832 return;
833 }
834
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000835 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000836 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000837
Michael Krusee2bccbb2015-09-18 19:59:43 +0000838 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000839 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000840 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000841 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000842 }
843
Roman Gareevf5aff702016-09-12 17:08:31 +0000844 if (Sizes.size() >= 2 && !isa<SCEVConstant>(Sizes[1]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000845 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000846
Tobias Grosser79baa212014-04-10 08:38:02 +0000847 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000848 AccessRelation = isl_map_set_tuple_id(
849 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000850 AccessRelation =
851 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
852
Tobias Grosseraa660a92015-03-30 00:07:50 +0000853 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000854 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000855}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000856
Michael Krusecac948e2015-10-02 13:53:07 +0000857MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000858 AccessType AccType, Value *BaseAddress,
859 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000860 ArrayRef<const SCEV *> Subscripts,
861 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000862 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000863 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Johannes Doerfert85676e32016-04-23 14:32:34 +0000864 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
865 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()),
866 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000867 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000868 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000869 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000870 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000871
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000872 std::string IdName =
873 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000874 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
875}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000876
Roman Gareevb3224ad2016-09-14 06:26:09 +0000877MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
878 __isl_take isl_map *AccRel)
879 : Kind(ScopArrayInfo::MemoryKind::MK_Array), AccType(AccType),
880 RedType(RT_NONE), Statement(Stmt), InvalidDomain(nullptr),
881 AccessInstruction(nullptr), IsAffine(true), AccessRelation(nullptr),
882 NewAccessRelation(AccRel) {
883 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
884 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
885 Sizes.push_back(nullptr);
886 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
887 Sizes.push_back(SAI->getDimensionSize(i));
888 ElementType = SAI->getElementType();
889 BaseAddr = SAI->getBasePtr();
890 BaseName = SAI->getName();
891 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
892 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
893
894 std::string IdName =
895 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
896 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
897}
898
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000899void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +0000900 auto *Ctx = Statement->getParent()->getContext();
901 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
902 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +0000903}
904
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000905const std::string MemoryAccess::getReductionOperatorStr() const {
906 return MemoryAccess::getReductionOperatorStr(getReductionType());
907}
908
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000909__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
910
Johannes Doerfertf6183392014-07-01 20:52:51 +0000911raw_ostream &polly::operator<<(raw_ostream &OS,
912 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000913 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000914 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000915 else
916 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000917 return OS;
918}
919
Tobias Grosser75805372011-04-29 06:27:02 +0000920void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000921 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000922 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000923 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000924 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000925 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000926 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000927 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000928 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000929 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000930 break;
931 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000932 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000933 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000934 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000935 if (hasNewAccessRelation())
936 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000937}
938
Tobias Grosser74394f02013-01-14 22:40:23 +0000939void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000940
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000941__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
942 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000943 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +0000944 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
945 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
946 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000947 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000948}
949
Tobias Grosser75805372011-04-29 06:27:02 +0000950// Create a map in the size of the provided set domain, that maps from the
951// one element of the provided set domain to another element of the provided
952// set domain.
953// The mapping is limited to all points that are equal in all but the last
954// dimension and for which the last dimension of the input is strict smaller
955// than the last dimension of the output.
956//
957// getEqualAndLarger(set[i0, i1, ..., iX]):
958//
959// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
960// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
961//
Tobias Grosser2a526fe2016-09-08 11:18:56 +0000962static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000963 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000964 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000965 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000966
967 // Set all but the last dimension to be equal for the input and output
968 //
969 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
970 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000971 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000972 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000973
974 // Set the last dimension of the input to be strict smaller than the
975 // last dimension of the output.
976 //
977 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000978 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
979 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000980 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000981}
982
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000983__isl_give isl_set *
984MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000985 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000986 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000987 isl_space *Space = isl_space_range(isl_map_get_space(S));
988 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000989
Sebastian Popa00a0292012-12-18 07:46:06 +0000990 S = isl_map_reverse(S);
991 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000992
Sebastian Popa00a0292012-12-18 07:46:06 +0000993 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
994 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
995 NextScatt = isl_map_apply_domain(NextScatt, S);
996 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000997
Sebastian Popa00a0292012-12-18 07:46:06 +0000998 isl_set *Deltas = isl_map_deltas(NextScatt);
999 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001000}
1001
Sebastian Popa00a0292012-12-18 07:46:06 +00001002bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001003 int StrideWidth) const {
1004 isl_set *Stride, *StrideX;
1005 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001006
Sebastian Popa00a0292012-12-18 07:46:06 +00001007 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001008 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001009 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1010 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1011 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1012 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001013 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001014
Tobias Grosser28dd4862012-01-24 16:42:16 +00001015 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001016 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001017
Tobias Grosser28dd4862012-01-24 16:42:16 +00001018 return IsStrideX;
1019}
1020
Michael Krused56b90a2016-09-01 09:03:27 +00001021bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001022 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001023}
1024
Michael Krused56b90a2016-09-01 09:03:27 +00001025bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001026 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001027}
1028
Michael Krused56b90a2016-09-01 09:03:27 +00001029void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001030 assert(NewAccess);
1031
1032#ifndef NDEBUG
1033 // Check domain space compatibility.
1034 auto *NewSpace = isl_map_get_space(NewAccess);
1035 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1036 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1037 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1038 isl_space_free(NewDomainSpace);
1039 isl_space_free(OriginalDomainSpace);
1040
1041 // Check whether there is an access for every statement instance.
1042 auto *StmtDomain = getStatement()->getDomain();
1043 StmtDomain = isl_set_intersect_params(
1044 StmtDomain, getStatement()->getParent()->getContext());
1045 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1046 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1047 "Partial accesses not supported");
1048 isl_set_free(NewDomain);
1049 isl_set_free(StmtDomain);
1050
1051 // Check whether access dimensions correspond to number of dimensions of the
1052 // accesses array.
1053 auto *NewAccessSpace = isl_space_range(NewSpace);
1054 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1055 "Must specify the array that is accessed");
1056 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1057 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1058 assert(SAI && "Must set a ScopArrayInfo");
1059 assert(!SAI->getBasePtrOriginSAI() &&
1060 "Indirect array not supported by codegen");
1061 auto Dims = SAI->getNumberOfDimensions();
1062 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1063 "Access dims must match array dims");
1064 isl_space_free(NewAccessSpace);
1065 isl_id_free(NewArrayId);
1066#endif
1067
Tobias Grosser166c4222015-09-05 07:46:40 +00001068 isl_map_free(NewAccessRelation);
1069 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001070}
Tobias Grosser75805372011-04-29 06:27:02 +00001071
1072//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001073
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001074__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001075 isl_set *Domain = getDomain();
1076 if (isl_set_is_empty(Domain)) {
1077 isl_set_free(Domain);
1078 return isl_map_from_aff(
1079 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1080 }
1081 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001082 if (!Schedule) {
1083 isl_set_free(Domain);
1084 return nullptr;
1085 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001086 Schedule = isl_union_map_intersect_domain(
1087 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1088 if (isl_union_map_is_empty(Schedule)) {
1089 isl_set_free(Domain);
1090 isl_union_map_free(Schedule);
1091 return isl_map_from_aff(
1092 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1093 }
1094 auto *M = isl_map_from_union_map(Schedule);
1095 M = isl_map_coalesce(M);
1096 M = isl_map_gist_domain(M, Domain);
1097 M = isl_map_coalesce(M);
1098 return M;
1099}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001100
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001101__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1102 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001103 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1104 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001105}
1106
Tobias Grosser37eb4222014-02-20 21:43:54 +00001107void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1108 assert(isl_set_is_subset(NewDomain, Domain) &&
1109 "New domain is not a subset of old domain!");
1110 isl_set_free(Domain);
1111 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001112}
1113
Michael Krusecac948e2015-10-02 13:53:07 +00001114void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001115 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001116 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001117 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001118
Tobias Grossera535dff2015-12-13 19:59:01 +00001119 ScopArrayInfo::MemoryKind Ty;
1120 if (Access->isPHIKind())
1121 Ty = ScopArrayInfo::MK_PHI;
1122 else if (Access->isExitPHIKind())
1123 Ty = ScopArrayInfo::MK_ExitPHI;
1124 else if (Access->isValueKind())
1125 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001126 else
Tobias Grossera535dff2015-12-13 19:59:01 +00001127 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001128
Johannes Doerfertadeab372016-02-07 13:57:32 +00001129 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1130 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001131 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001132 }
1133}
1134
Michael Krusecac948e2015-10-02 13:53:07 +00001135void ScopStmt::addAccess(MemoryAccess *Access) {
1136 Instruction *AccessInst = Access->getAccessInstruction();
1137
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001138 if (Access->isArrayKind()) {
1139 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1140 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001141 } else if (Access->isValueKind() && Access->isWrite()) {
1142 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001143 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001144 assert(!ValueWrites.lookup(AccessVal));
1145
1146 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001147 } else if (Access->isValueKind() && Access->isRead()) {
1148 Value *AccessVal = Access->getAccessValue();
1149 assert(!ValueReads.lookup(AccessVal));
1150
1151 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001152 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1153 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1154 assert(!PHIWrites.lookup(PHI));
1155
1156 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001157 }
1158
1159 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001160}
1161
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001162void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001163 for (MemoryAccess *MA : *this)
1164 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001165
Johannes Doerferta60ad842016-05-10 12:18:22 +00001166 auto *Ctx = Parent.getContext();
1167 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1168 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001169}
1170
Tobias Grosserc80d6972016-09-02 06:33:33 +00001171/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001172static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1173 void *User) {
1174 isl_set **BoundedParts = static_cast<isl_set **>(User);
1175 if (isl_basic_set_is_bounded(BSet))
1176 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1177 else
1178 isl_basic_set_free(BSet);
1179 return isl_stat_ok;
1180}
1181
Tobias Grosserc80d6972016-09-02 06:33:33 +00001182/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001183static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1184 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1185 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1186 isl_set_free(S);
1187 return BoundedParts;
1188}
1189
Tobias Grosserc80d6972016-09-02 06:33:33 +00001190/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001191///
1192/// @returns A separation of @p S into first an unbounded then a bounded subset,
1193/// both with regards to the dimension @p Dim.
1194static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1195partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1196
1197 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001198 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001199
1200 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001201 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001202
1203 // Remove dimensions that are greater than Dim as they are not interesting.
1204 assert(NumDimsS >= Dim + 1);
1205 OnlyDimS =
1206 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1207
1208 // Create artificial parametric upper bounds for dimensions smaller than Dim
1209 // as we are not interested in them.
1210 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1211 for (unsigned u = 0; u < Dim; u++) {
1212 isl_constraint *C = isl_inequality_alloc(
1213 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1214 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1215 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1216 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1217 }
1218
1219 // Collect all bounded parts of OnlyDimS.
1220 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1221
1222 // Create the dimensions greater than Dim again.
1223 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1224 NumDimsS - Dim - 1);
1225
1226 // Remove the artificial upper bound parameters again.
1227 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1228
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001229 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001230 return std::make_pair(UnboundedParts, BoundedParts);
1231}
1232
Tobias Grosserc80d6972016-09-02 06:33:33 +00001233/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001234static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1235 __isl_take isl_set *To) {
1236 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1237 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1238 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1239 }
1240 return To;
1241}
1242
Tobias Grosserc80d6972016-09-02 06:33:33 +00001243/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001244static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001245 __isl_take isl_pw_aff *L,
1246 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001247 switch (Pred) {
1248 case ICmpInst::ICMP_EQ:
1249 return isl_pw_aff_eq_set(L, R);
1250 case ICmpInst::ICMP_NE:
1251 return isl_pw_aff_ne_set(L, R);
1252 case ICmpInst::ICMP_SLT:
1253 return isl_pw_aff_lt_set(L, R);
1254 case ICmpInst::ICMP_SLE:
1255 return isl_pw_aff_le_set(L, R);
1256 case ICmpInst::ICMP_SGT:
1257 return isl_pw_aff_gt_set(L, R);
1258 case ICmpInst::ICMP_SGE:
1259 return isl_pw_aff_ge_set(L, R);
1260 case ICmpInst::ICMP_ULT:
1261 return isl_pw_aff_lt_set(L, R);
1262 case ICmpInst::ICMP_UGT:
1263 return isl_pw_aff_gt_set(L, R);
1264 case ICmpInst::ICMP_ULE:
1265 return isl_pw_aff_le_set(L, R);
1266 case ICmpInst::ICMP_UGE:
1267 return isl_pw_aff_ge_set(L, R);
1268 default:
1269 llvm_unreachable("Non integer predicate not supported");
1270 }
1271}
1272
Tobias Grosserc80d6972016-09-02 06:33:33 +00001273/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001274///
1275/// Helper function that will make sure the dimensions of the result have the
1276/// same isl_id's as the @p Domain.
1277static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1278 __isl_take isl_pw_aff *L,
1279 __isl_take isl_pw_aff *R,
1280 __isl_keep isl_set *Domain) {
1281 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1282 return setDimensionIds(Domain, ConsequenceCondSet);
1283}
1284
Tobias Grosserc80d6972016-09-02 06:33:33 +00001285/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001286///
1287/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001288/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1289/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001290static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001291buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1292 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001293 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1294
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001295 Value *Condition = getConditionFromTerminator(SI);
1296 assert(Condition && "No condition for switch");
1297
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001298 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001299 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001300 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001301 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001302
1303 unsigned NumSuccessors = SI->getNumSuccessors();
1304 ConditionSets.resize(NumSuccessors);
1305 for (auto &Case : SI->cases()) {
1306 unsigned Idx = Case.getSuccessorIndex();
1307 ConstantInt *CaseValue = Case.getCaseValue();
1308
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001309 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001310 isl_set *CaseConditionSet =
1311 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1312 ConditionSets[Idx] = isl_set_coalesce(
1313 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1314 }
1315
1316 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1317 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1318 for (unsigned u = 2; u < NumSuccessors; u++)
1319 ConditionSetUnion =
1320 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1321 ConditionSets[0] = setDimensionIds(
1322 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1323
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001324 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001325
1326 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001327}
1328
Tobias Grosserc80d6972016-09-02 06:33:33 +00001329/// Build the conditions sets for the branch condition @p Condition in
1330/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001331///
1332/// This will fill @p ConditionSets with the conditions under which control
1333/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001334/// have as many elements as @p TI has successors. If @p TI is nullptr the
1335/// context under which @p Condition is true/false will be returned as the
1336/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001337static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001338buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1339 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001340 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1341
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001342 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001343 isl_set *ConsequenceCondSet = nullptr;
1344 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1345 if (CCond->isZero())
1346 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1347 else
1348 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1349 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1350 auto Opcode = BinOp->getOpcode();
1351 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1352
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001353 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1354 ConditionSets) &&
1355 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1356 ConditionSets);
1357 if (!Valid) {
1358 while (!ConditionSets.empty())
1359 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001360 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001361 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001362
1363 isl_set_free(ConditionSets.pop_back_val());
1364 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1365 isl_set_free(ConditionSets.pop_back_val());
1366 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1367
1368 if (Opcode == Instruction::And)
1369 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1370 else
1371 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1372 } else {
1373 auto *ICond = dyn_cast<ICmpInst>(Condition);
1374 assert(ICond &&
1375 "Condition of exiting branch was neither constant nor ICmp!");
1376
1377 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001378 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001379 // For unsigned comparisons we assumed the signed bit of neither operand
1380 // to be set. The comparison is equal to a signed comparison under this
1381 // assumption.
1382 bool NonNeg = ICond->isUnsigned();
1383 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1384 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001385 ConsequenceCondSet =
1386 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1387 }
1388
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001389 // If no terminator was given we are only looking for parameter constraints
1390 // under which @p Condition is true/false.
1391 if (!TI)
1392 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001393 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001394 ConsequenceCondSet = isl_set_coalesce(
1395 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001396
Johannes Doerfertb2885792016-04-26 09:20:41 +00001397 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001398 bool TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001399 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001400
Michael Krusef7a4a942016-05-02 12:25:36 +00001401 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001402 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1403 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001404 TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001405 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001406 }
1407
Michael Krusef7a4a942016-05-02 12:25:36 +00001408 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001409 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001410 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001411 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001412 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001413 }
1414
1415 ConditionSets.push_back(ConsequenceCondSet);
1416 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001417
1418 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001419}
1420
Tobias Grosserc80d6972016-09-02 06:33:33 +00001421/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001422///
1423/// This will fill @p ConditionSets with the conditions under which control
1424/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1425/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001426static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001427buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001428 __isl_keep isl_set *Domain,
1429 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1430
1431 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001432 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001433
1434 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1435
1436 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001437 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001438 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001439 }
1440
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001441 Value *Condition = getConditionFromTerminator(TI);
1442 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001443
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001444 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001445}
1446
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001447void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001448 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001449
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001450 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001451 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001452}
1453
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001454void ScopStmt::collectSurroundingLoops() {
1455 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1456 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1457 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1458 isl_id_free(DimId);
1459 }
1460}
1461
Michael Kruse9d080092015-09-11 21:41:48 +00001462ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerferta3519512016-04-23 13:02:23 +00001463 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1464 R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001465
Tobias Grosser16c44032015-07-09 07:31:45 +00001466 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001467}
1468
Michael Kruse9d080092015-09-11 21:41:48 +00001469ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerferta3519512016-04-23 13:02:23 +00001470 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1471 R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001472
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001473 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001474}
1475
Roman Gareevb3224ad2016-09-14 06:26:09 +00001476ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1477 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1478 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1479 R(nullptr), Build(nullptr) {
1480 BaseName = getIslCompatibleName("CopyStmt_", "",
1481 std::to_string(parent.getCopyStmtsNum()));
1482 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1483 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1484 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1485 auto *Access =
1486 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1487 parent.addAccessFunction(Access);
1488 addAccess(Access);
1489 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1490 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1491 parent.addAccessFunction(Access);
1492 addAccess(Access);
1493}
1494
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001495void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001496 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001497
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001498 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001499 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001500 buildAccessRelations();
1501
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001502 if (DetectReductions)
1503 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001504}
1505
Tobias Grosserc80d6972016-09-02 06:33:33 +00001506/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001507///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001508/// Check if the stored value for @p StoreMA is a binary operator with one or
1509/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001510/// used only once (by @p StoreMA) and its load operands are also used only
1511/// once, we have found a possible reduction chain. It starts at an operand
1512/// load and includes the binary operator and @p StoreMA.
1513///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001514/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001515/// escape this block or into any other store except @p StoreMA.
1516void ScopStmt::collectCandiateReductionLoads(
1517 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1518 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1519 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001520 return;
1521
1522 // Skip if there is not one binary operator between the load and the store
1523 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001524 if (!BinOp)
1525 return;
1526
1527 // Skip if the binary operators has multiple uses
1528 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001529 return;
1530
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001531 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001532 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1533 return;
1534
Johannes Doerfert9890a052014-07-01 00:32:29 +00001535 // Skip if the binary operator is outside the current SCoP
1536 if (BinOp->getParent() != Store->getParent())
1537 return;
1538
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001539 // Skip if it is a multiplicative reduction and we disabled them
1540 if (DisableMultiplicativeReductions &&
1541 (BinOp->getOpcode() == Instruction::Mul ||
1542 BinOp->getOpcode() == Instruction::FMul))
1543 return;
1544
Johannes Doerferte58a0122014-06-27 20:31:28 +00001545 // Check the binary operator operands for a candidate load
1546 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1547 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1548 if (!PossibleLoad0 && !PossibleLoad1)
1549 return;
1550
1551 // A load is only a candidate if it cannot escape (thus has only this use)
1552 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001553 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001554 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001555 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001556 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001557 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001558}
1559
Tobias Grosserc80d6972016-09-02 06:33:33 +00001560/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001561///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001562/// Iterate over all store memory accesses and check for valid binary reduction
1563/// like chains. For all candidates we check if they have the same base address
1564/// and there are no other accesses which overlap with them. The base address
1565/// check rules out impossible reductions candidates early. The overlap check,
1566/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001567/// guarantees that none of the intermediate results will escape during
1568/// execution of the loop nest. We basically check here that no other memory
1569/// access can access the same memory as the potential reduction.
1570void ScopStmt::checkForReductions() {
1571 SmallVector<MemoryAccess *, 2> Loads;
1572 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1573
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001574 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001575 // stores and collecting possible reduction loads.
1576 for (MemoryAccess *StoreMA : MemAccs) {
1577 if (StoreMA->isRead())
1578 continue;
1579
1580 Loads.clear();
1581 collectCandiateReductionLoads(StoreMA, Loads);
1582 for (MemoryAccess *LoadMA : Loads)
1583 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1584 }
1585
1586 // Then check each possible candidate pair.
1587 for (const auto &CandidatePair : Candidates) {
1588 bool Valid = true;
1589 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1590 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1591
1592 // Skip those with obviously unequal base addresses.
1593 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1594 isl_map_free(LoadAccs);
1595 isl_map_free(StoreAccs);
1596 continue;
1597 }
1598
1599 // And check if the remaining for overlap with other memory accesses.
1600 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1601 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1602 isl_set *AllAccs = isl_map_range(AllAccsRel);
1603
1604 for (MemoryAccess *MA : MemAccs) {
1605 if (MA == CandidatePair.first || MA == CandidatePair.second)
1606 continue;
1607
1608 isl_map *AccRel =
1609 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1610 isl_set *Accs = isl_map_range(AccRel);
1611
Tobias Grosser55a7af72016-09-08 14:08:07 +00001612 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001613 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1614 Valid = Valid && isl_set_is_empty(OverlapAccs);
1615 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001616 } else {
1617 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001618 }
1619 }
1620
1621 isl_set_free(AllAccs);
1622 if (!Valid)
1623 continue;
1624
Johannes Doerfertf6183392014-07-01 20:52:51 +00001625 const LoadInst *Load =
1626 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1627 MemoryAccess::ReductionType RT =
1628 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1629
Johannes Doerferte58a0122014-06-27 20:31:28 +00001630 // If no overlapping access was found we mark the load and store as
1631 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001632 CandidatePair.first->markAsReductionLike(RT);
1633 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001634 }
Tobias Grosser75805372011-04-29 06:27:02 +00001635}
1636
Tobias Grosser74394f02013-01-14 22:40:23 +00001637std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001638
Tobias Grosser54839312015-04-21 11:37:25 +00001639std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001640 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001641 if (!S)
1642 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001643 auto Str = stringFromIslObj(S);
1644 isl_map_free(S);
1645 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001646}
1647
Johannes Doerferta3519512016-04-23 13:02:23 +00001648void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1649 isl_set_free(InvalidDomain);
1650 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001651}
1652
Michael Kruse375cb5f2016-02-24 22:08:24 +00001653BasicBlock *ScopStmt::getEntryBlock() const {
1654 if (isBlockStmt())
1655 return getBasicBlock();
1656 return getRegion()->getEntry();
1657}
1658
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001659unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001660
Tobias Grosser75805372011-04-29 06:27:02 +00001661const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1662
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001663Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001664 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001665}
1666
Tobias Grosser74394f02013-01-14 22:40:23 +00001667isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001668
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001669__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001670
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001671__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001672 return isl_set_get_space(Domain);
1673}
1674
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001675__isl_give isl_id *ScopStmt::getDomainId() const {
1676 return isl_set_get_tuple_id(Domain);
1677}
Tobias Grossercd95b772012-08-30 11:49:38 +00001678
Johannes Doerfert7c013572016-04-12 09:57:34 +00001679ScopStmt::~ScopStmt() {
1680 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001681 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001682}
Tobias Grosser75805372011-04-29 06:27:02 +00001683
1684void ScopStmt::print(raw_ostream &OS) const {
1685 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001686 OS.indent(12) << "Domain :=\n";
1687
1688 if (Domain) {
1689 OS.indent(16) << getDomainStr() << ";\n";
1690 } else
1691 OS.indent(16) << "n/a\n";
1692
Tobias Grosser54839312015-04-21 11:37:25 +00001693 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001694
1695 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001696 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001697 } else
1698 OS.indent(16) << "n/a\n";
1699
Tobias Grosser083d3d32014-06-28 08:59:45 +00001700 for (MemoryAccess *Access : MemAccs)
1701 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001702}
1703
1704void ScopStmt::dump() const { print(dbgs()); }
1705
Michael Kruse10071822016-05-23 14:45:58 +00001706void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
1707 // Remove the memory accesses from this statement
1708 // together with all scalar accesses that were caused by it.
Michael Krusead28e5a2016-01-26 13:33:15 +00001709 // MK_Value READs have no access instruction, hence would not be removed by
1710 // this function. However, it is only used for invariant LoadInst accesses,
1711 // its arguments are always affine, hence synthesizable, and therefore there
1712 // are no MK_Value READ accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001713 auto Predicate = [&](MemoryAccess *Acc) {
1714 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1715 };
1716 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1717 MemAccs.end());
1718 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001719}
1720
Tobias Grosser75805372011-04-29 06:27:02 +00001721//===----------------------------------------------------------------------===//
1722/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001723
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001724void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001725 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1726 isl_set_free(Context);
1727 Context = NewContext;
1728}
1729
Tobias Grosserc80d6972016-09-02 06:33:33 +00001730/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001731struct SCEVSensitiveParameterRewriter
1732 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1733 ValueToValueMap &VMap;
1734 ScalarEvolution &SE;
1735
1736public:
1737 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1738 : VMap(VMap), SE(SE) {}
1739
1740 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1741 ValueToValueMap &VMap) {
1742 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1743 return SSPR.visit(E);
1744 }
1745
1746 const SCEV *visit(const SCEV *E) {
1747 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1748 }
1749
1750 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1751
1752 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1753 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1754 }
1755
1756 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1757 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1758 }
1759
1760 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1761 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1762 }
1763
1764 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1765 SmallVector<const SCEV *, 4> Operands;
1766 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1767 Operands.push_back(visit(E->getOperand(i)));
1768 return SE.getAddExpr(Operands);
1769 }
1770
1771 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1772 SmallVector<const SCEV *, 4> Operands;
1773 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1774 Operands.push_back(visit(E->getOperand(i)));
1775 return SE.getMulExpr(Operands);
1776 }
1777
1778 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1779 SmallVector<const SCEV *, 4> Operands;
1780 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1781 Operands.push_back(visit(E->getOperand(i)));
1782 return SE.getSMaxExpr(Operands);
1783 }
1784
1785 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1786 SmallVector<const SCEV *, 4> Operands;
1787 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1788 Operands.push_back(visit(E->getOperand(i)));
1789 return SE.getUMaxExpr(Operands);
1790 }
1791
1792 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1793 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1794 }
1795
1796 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1797 auto *Start = visit(E->getStart());
1798 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1799 visit(E->getStepRecurrence(SE)),
1800 E->getLoop(), SCEV::FlagAnyWrap);
1801 return SE.getAddExpr(Start, AddRec);
1802 }
1803
1804 const SCEV *visitUnknown(const SCEVUnknown *E) {
1805 if (auto *NewValue = VMap.lookup(E->getValue()))
1806 return SE.getUnknown(NewValue);
1807 return E;
1808 }
1809};
1810
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001811const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001812 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001813}
1814
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001815void Scop::createParameterId(const SCEV *Parameter) {
1816 assert(Parameters.count(Parameter));
1817 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001818
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001819 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001820
Tobias Grosser8f99c162011-11-15 11:38:55 +00001821 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1822 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001823
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001824 // If this parameter references a specific Value and this value has a name
1825 // we use this name as it is likely to be unique and more useful than just
1826 // a number.
1827 if (Val->hasName())
1828 ParameterName = Val->getName();
1829 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001830 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001831 if (LoadOrigin->hasName()) {
1832 ParameterName += "_loaded_from_";
1833 ParameterName +=
1834 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1835 }
1836 }
1837 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001838
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001839 ParameterName = getIslCompatibleName("", ParameterName, "");
1840
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001841 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1842 const_cast<void *>((const void *)Parameter));
1843 ParameterIds[Parameter] = Id;
1844}
1845
1846void Scop::addParams(const ParameterSetTy &NewParameters) {
1847 for (const SCEV *Parameter : NewParameters) {
1848 // Normalize the SCEV to get the representing element for an invariant load.
1849 Parameter = extractConstantFactor(Parameter, *SE).second;
1850 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1851
1852 if (Parameters.insert(Parameter))
1853 createParameterId(Parameter);
1854 }
1855}
1856
1857__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1858 // Normalize the SCEV to get the representing element for an invariant load.
1859 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1860 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001861}
Tobias Grosser75805372011-04-29 06:27:02 +00001862
Michael Krused56b90a2016-09-01 09:03:27 +00001863__isl_give isl_set *
1864Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001865 isl_set *DomainContext = isl_union_set_params(getDomains());
1866 return isl_set_intersect_params(C, DomainContext);
1867}
1868
Johannes Doerferte0b08072016-05-23 12:43:44 +00001869bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1870 return DT.dominates(BB, getEntry());
1871}
1872
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001873void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1874 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001875 auto &F = getFunction();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001876 for (auto &Assumption : AC.assumptions()) {
1877 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1878 if (!CI || CI->getNumArgOperands() != 1)
1879 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001880
Johannes Doerfert952b5302016-05-23 12:40:48 +00001881 bool InScop = contains(CI);
Johannes Doerferte0b08072016-05-23 12:43:44 +00001882 if (!InScop && !isDominatedBy(DT, CI->getParent()))
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001883 continue;
1884
Michael Kruse09eb4452016-03-03 22:10:47 +00001885 auto *L = LI.getLoopFor(CI->getParent());
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001886 auto *Val = CI->getArgOperand(0);
Johannes Doerfertf560b3d2016-04-25 13:33:07 +00001887 ParameterSetTy DetectedParams;
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001888 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001889 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1890 CI->getDebugLoc(),
1891 "Non-affine user assumption ignored.");
1892 continue;
1893 }
1894
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001895 // Collect all newly introduced parameters.
1896 ParameterSetTy NewParams;
1897 for (auto *Param : DetectedParams) {
1898 Param = extractConstantFactor(Param, *SE).second;
1899 Param = getRepresentingInvariantLoadSCEV(Param);
1900 if (Parameters.count(Param))
1901 continue;
1902 NewParams.insert(Param);
1903 }
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001904
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001905 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001906 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
1907 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
1908 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001909 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
1910 isl_set_free(Dom);
1911
1912 if (!Valid)
Johannes Doerfert297c7202016-05-10 13:06:42 +00001913 continue;
1914
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001915 isl_set *AssumptionCtx = nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001916 if (InScop) {
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001917 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
1918 isl_set_free(ConditionSets[0]);
1919 } else {
1920 AssumptionCtx = isl_set_complement(ConditionSets[1]);
1921 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
1922 }
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001923
1924 // Project out newly introduced parameters as they are not otherwise useful.
1925 if (!NewParams.empty()) {
1926 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
1927 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
1928 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
1929 isl_id_free(Id);
1930
1931 if (!NewParams.count(Param))
1932 continue;
1933
1934 AssumptionCtx =
1935 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
1936 }
1937 }
1938
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001939 emitOptimizationRemarkAnalysis(
1940 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1941 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1942 Context = isl_set_intersect(Context, AssumptionCtx);
1943 }
1944}
1945
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001946void Scop::addUserContext() {
1947 if (UserContextStr.empty())
1948 return;
1949
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001950 isl_set *UserContext =
1951 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001952 isl_space *Space = getParamSpace();
1953 if (isl_space_dim(Space, isl_dim_param) !=
1954 isl_set_dim(UserContext, isl_dim_param)) {
1955 auto SpaceStr = isl_space_to_str(Space);
1956 errs() << "Error: the context provided in -polly-context has not the same "
1957 << "number of dimensions than the computed context. Due to this "
1958 << "mismatch, the -polly-context option is ignored. Please provide "
1959 << "the context in the parameter space: " << SpaceStr << ".\n";
1960 free(SpaceStr);
1961 isl_set_free(UserContext);
1962 isl_space_free(Space);
1963 return;
1964 }
1965
1966 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001967 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1968 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001969
1970 if (strcmp(NameContext, NameUserContext) != 0) {
1971 auto SpaceStr = isl_space_to_str(Space);
1972 errs() << "Error: the name of dimension " << i
1973 << " provided in -polly-context "
1974 << "is '" << NameUserContext << "', but the name in the computed "
1975 << "context is '" << NameContext
1976 << "'. Due to this name mismatch, "
1977 << "the -polly-context option is ignored. Please provide "
1978 << "the context in the parameter space: " << SpaceStr << ".\n";
1979 free(SpaceStr);
1980 isl_set_free(UserContext);
1981 isl_space_free(Space);
1982 return;
1983 }
1984
1985 UserContext =
1986 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1987 isl_space_get_dim_id(Space, isl_dim_param, i));
1988 }
1989
1990 Context = isl_set_intersect(Context, UserContext);
1991 isl_space_free(Space);
1992}
1993
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001994void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001995 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001996
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001997 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001998 for (LoadInst *LInst : RIL) {
1999 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2000
Johannes Doerfert96e54712016-02-07 17:30:13 +00002001 Type *Ty = LInst->getType();
2002 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002003 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002004 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002005 continue;
2006 }
2007
2008 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002009 InvariantEquivClasses.emplace_back(
2010 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002011 }
2012}
2013
Tobias Grosser6be480c2011-11-08 15:41:13 +00002014void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002015 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002016 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002017 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002018 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002019}
2020
Tobias Grosser18daaca2012-05-22 10:47:27 +00002021void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002022 unsigned PDim = 0;
2023 for (auto *Parameter : Parameters) {
2024 ConstantRange SRange = SE->getSignedRange(Parameter);
2025 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002026 }
2027}
2028
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002029void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002030 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002031 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002032
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002033 unsigned PDim = 0;
2034 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002035 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002036 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002037 }
2038
2039 // Align the parameters of all data structures to the model.
2040 Context = isl_set_align_params(Context, Space);
2041
Johannes Doerferta60ad842016-05-10 12:18:22 +00002042 // As all parameters are known add bounds to them.
2043 addParameterBounds();
2044
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002045 for (ScopStmt &Stmt : *this)
2046 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002047
2048 // Simplify the schedule according to the context too.
2049 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002050}
2051
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002052static __isl_give isl_set *
2053simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2054 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002055 // If we modelt all blocks in the SCoP that have side effects we can simplify
2056 // the context with the constraints that are needed for anything to be
2057 // executed at all. However, if we have error blocks in the SCoP we already
2058 // assumed some parameter combinations cannot occure and removed them from the
2059 // domains, thus we cannot use the remaining domain to simplify the
2060 // assumptions.
2061 if (!S.hasErrorBlock()) {
2062 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2063 AssumptionContext =
2064 isl_set_gist_params(AssumptionContext, DomainParameters);
2065 }
2066
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002067 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2068 return AssumptionContext;
2069}
2070
2071void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002072 // The parameter constraints of the iteration domains give us a set of
2073 // constraints that need to hold for all cases where at least a single
2074 // statement iteration is executed in the whole scop. We now simplify the
2075 // assumed context under the assumption that such constraints hold and at
2076 // least a single statement iteration is executed. For cases where no
2077 // statement instances are executed, the assumptions we have taken about
2078 // the executed code do not matter and can be changed.
2079 //
2080 // WARNING: This only holds if the assumptions we have taken do not reduce
2081 // the set of statement instances that are executed. Otherwise we
2082 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002083 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002084 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002085 // performed. In such a case, modifying the run-time conditions and
2086 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002087 // to not be executed.
2088 //
2089 // Example:
2090 //
2091 // When delinearizing the following code:
2092 //
2093 // for (long i = 0; i < 100; i++)
2094 // for (long j = 0; j < m; j++)
2095 // A[i+p][j] = 1.0;
2096 //
2097 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002098 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002099 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002100 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002101 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002102}
2103
Tobias Grosserc80d6972016-09-02 06:33:33 +00002104/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002105static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002106 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2107 isl_pw_multi_aff *MinPMA, *MaxPMA;
2108 isl_pw_aff *LastDimAff;
2109 isl_aff *OneAff;
2110 unsigned Pos;
2111
Johannes Doerfert6296d952016-04-22 11:38:19 +00002112 Set = isl_set_remove_divs(Set);
2113
Michael Krusebc150122016-05-02 12:25:18 +00002114 if (isl_set_n_basic_set(Set) >= MaxDisjunctionsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002115 isl_set_free(Set);
2116 return isl_stat_error;
2117 }
2118
Johannes Doerfert9143d672014-09-27 11:02:39 +00002119 // Restrict the number of parameters involved in the access as the lexmin/
2120 // lexmax computation will take too long if this number is high.
2121 //
2122 // Experiments with a simple test case using an i7 4800MQ:
2123 //
2124 // #Parameters involved | Time (in sec)
2125 // 6 | 0.01
2126 // 7 | 0.04
2127 // 8 | 0.12
2128 // 9 | 0.40
2129 // 10 | 1.54
2130 // 11 | 6.78
2131 // 12 | 30.38
2132 //
2133 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2134 unsigned InvolvedParams = 0;
2135 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2136 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2137 InvolvedParams++;
2138
2139 if (InvolvedParams > RunTimeChecksMaxParameters) {
2140 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002141 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002142 }
2143 }
2144
Johannes Doerfertb164c792014-09-18 11:17:17 +00002145 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2146 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2147
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002148 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2149 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2150
Johannes Doerfertb164c792014-09-18 11:17:17 +00002151 // Adjust the last dimension of the maximal access by one as we want to
2152 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2153 // we test during code generation might now point after the end of the
2154 // allocated array but we will never dereference it anyway.
2155 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2156 "Assumed at least one output dimension");
2157 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2158 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2159 OneAff = isl_aff_zero_on_domain(
2160 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2161 OneAff = isl_aff_add_constant_si(OneAff, 1);
2162 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2163 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2164
2165 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2166
2167 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002168 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002169}
2170
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002171static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2172 isl_set *Domain = MA->getStatement()->getDomain();
2173 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2174 return isl_set_reset_tuple_id(Domain);
2175}
2176
Tobias Grosserc80d6972016-09-02 06:33:33 +00002177/// Wrapper function to calculate minimal/maximal accesses to each array.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002178static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002179 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002180 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002181
2182 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2183 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002184 Locations = isl_union_set_coalesce(Locations);
2185 Locations = isl_union_set_detect_equalities(Locations);
2186 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002187 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002188 isl_union_set_free(Locations);
2189 return Valid;
2190}
2191
Tobias Grosserc80d6972016-09-02 06:33:33 +00002192/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002193///
2194///{
2195
Tobias Grosserc80d6972016-09-02 06:33:33 +00002196/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002197static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2198 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2199 : RN->getNodeAs<BasicBlock>();
2200}
2201
Tobias Grosserc80d6972016-09-02 06:33:33 +00002202/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002203static inline BasicBlock *
2204getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002205 if (RN->isSubRegion()) {
2206 assert(idx == 0);
2207 return RN->getNodeAs<Region>()->getExit();
2208 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002209 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002210}
2211
Tobias Grosserc80d6972016-09-02 06:33:33 +00002212/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002213static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2214 if (!RN->isSubRegion())
2215 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2216
2217 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2218 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2219 while (L && NonAffineSubRegion->contains(L))
2220 L = L->getParentLoop();
2221 return L;
2222}
2223
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002224static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2225 if (!RN->isSubRegion())
2226 return 1;
2227
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002228 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002229 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002230}
2231
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002232static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2233 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002234 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002235 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002236 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002237 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002238 return true;
2239 return false;
2240}
2241
Johannes Doerfert96425c22015-08-30 21:13:53 +00002242///}
2243
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002244static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2245 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002246 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002247 isl_id *DimId =
2248 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2249 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2250}
2251
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002252__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002253 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002254}
2255
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002256__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002257 auto DIt = DomainMap.find(BB);
2258 if (DIt != DomainMap.end())
2259 return isl_set_copy(DIt->getSecond());
2260
2261 auto &RI = *R.getRegionInfo();
2262 auto *BBR = RI.getRegionFor(BB);
2263 while (BBR->getEntry() == BB)
2264 BBR = BBR->getParent();
2265 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002266}
2267
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002268bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002269
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002270 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002271 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002272 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2273 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002274 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002275
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002276 while (LD-- >= 0) {
2277 S = addDomainDimId(S, LD + 1, L);
2278 L = L->getParentLoop();
2279 }
2280
Johannes Doerferta3519512016-04-23 13:02:23 +00002281 // Initialize the invalid domain.
2282 auto *EntryStmt = getStmtFor(EntryBB);
2283 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2284
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002285 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002286
Johannes Doerfert432658d2016-01-26 11:01:41 +00002287 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002288 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002289
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002290 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002291 return false;
2292
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002293 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002294 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002295
2296 // Error blocks and blocks dominated by them have been assumed to never be
2297 // executed. Representing them in the Scop does not add any value. In fact,
2298 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002299 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002300 // will cause problems when building up a ScopStmt for them.
2301 // Furthermore, basic blocks dominated by error blocks may reference
2302 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002303 // can themselves not be constructed properly. To this end we will replace
2304 // the domains of error blocks and those only reachable via error blocks
2305 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002306 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002307 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002308 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002309 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002310
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002311 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002312}
2313
Michael Kruse586e5792016-07-08 12:38:28 +00002314// If the loop is nonaffine/boxed, return the first non-boxed surrounding loop
2315// for Polly. If the loop is affine, return the loop itself. Do not call
2316// `getSCEVAtScope()` on the result of `getFirstNonBoxedLoopFor()`, as we need
2317// to analyze the memory accesses of the nonaffine/boxed loops.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002318static Loop *getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI,
2319 const BoxedLoopsSetTy &BoxedLoops) {
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002320 auto *L = LI.getLoopFor(BB);
2321 while (BoxedLoops.count(L))
2322 L = L->getParentLoop();
2323 return L;
2324}
2325
Tobias Grosserc80d6972016-09-02 06:33:33 +00002326/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002327/// to be compatible to domains constructed for loop @p NewL.
2328///
2329/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2330/// edge from @p OldL to @p NewL.
2331static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2332 __isl_take isl_set *Dom,
2333 Loop *OldL, Loop *NewL) {
2334
2335 // If the loops are the same there is nothing to do.
2336 if (NewL == OldL)
2337 return Dom;
2338
2339 int OldDepth = S.getRelativeLoopDepth(OldL);
2340 int NewDepth = S.getRelativeLoopDepth(NewL);
2341 // If both loops are non-affine loops there is nothing to do.
2342 if (OldDepth == -1 && NewDepth == -1)
2343 return Dom;
2344
2345 // Distinguish three cases:
2346 // 1) The depth is the same but the loops are not.
2347 // => One loop was left one was entered.
2348 // 2) The depth increased from OldL to NewL.
2349 // => One loop was entered, none was left.
2350 // 3) The depth decreased from OldL to NewL.
2351 // => Loops were left were difference of the depths defines how many.
2352 if (OldDepth == NewDepth) {
2353 assert(OldL->getParentLoop() == NewL->getParentLoop());
2354 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2355 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2356 Dom = addDomainDimId(Dom, NewDepth, NewL);
2357 } else if (OldDepth < NewDepth) {
2358 assert(OldDepth + 1 == NewDepth);
2359 auto &R = S.getRegion();
2360 (void)R;
2361 assert(NewL->getParentLoop() == OldL ||
2362 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2363 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2364 Dom = addDomainDimId(Dom, NewDepth, NewL);
2365 } else {
2366 assert(OldDepth > NewDepth);
2367 int Diff = OldDepth - NewDepth;
2368 int NumDim = isl_set_n_dim(Dom);
2369 assert(NumDim >= Diff);
2370 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2371 }
2372
2373 return Dom;
2374}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002375
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002376bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2377 LoopInfo &LI) {
2378 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002379
2380 ReversePostOrderTraversal<Region *> RTraversal(R);
2381 for (auto *RN : RTraversal) {
2382
2383 // Recurse for affine subregions but go on for basic blocks and non-affine
2384 // subregions.
2385 if (RN->isSubRegion()) {
2386 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002387 if (!isNonAffineSubRegion(SubRegion)) {
2388 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002389 continue;
2390 }
2391 }
2392
2393 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2394 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002395 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002396 isl_set *&Domain = DomainMap[BB];
2397 assert(Domain && "Cannot propagate a nullptr");
2398
Johannes Doerferta3519512016-04-23 13:02:23 +00002399 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002400 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002401 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002402
Johannes Doerferta3519512016-04-23 13:02:23 +00002403 if (!IsInvalidBlock) {
2404 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002405 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002406 isl_set_free(InvalidDomain);
2407 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002408 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2409 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2410 AS_RESTRICTION);
2411 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002412 }
2413
Johannes Doerferta3519512016-04-23 13:02:23 +00002414 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002415 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002416 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002417 }
2418
Johannes Doerferta3519512016-04-23 13:02:23 +00002419 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002420 auto *TI = BB->getTerminator();
2421 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2422 for (unsigned u = 0; u < NumSuccs; u++) {
2423 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002424 auto *SuccStmt = getStmtFor(SuccBB);
2425
2426 // Skip successors outside the SCoP.
2427 if (!SuccStmt)
2428 continue;
2429
Johannes Doerferte4459a22016-04-25 13:34:50 +00002430 // Skip backedges.
2431 if (DT.dominates(SuccBB, BB))
2432 continue;
2433
Johannes Doerferta3519512016-04-23 13:02:23 +00002434 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2435 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2436 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2437 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2438 SuccInvalidDomain =
2439 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2440 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2441 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2442 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002443
Michael Krusebc150122016-05-02 12:25:18 +00002444 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002445 // In case this happens we will bail.
Michael Krusebc150122016-05-02 12:25:18 +00002446 if (NumConjucts < MaxDisjunctionsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002447 continue;
2448
Johannes Doerferta3519512016-04-23 13:02:23 +00002449 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002450 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002451 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002452 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002453
2454 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002455 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002456
2457 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002458}
2459
Johannes Doerfert642594a2016-04-04 07:57:39 +00002460void Scop::propagateDomainConstraintsToRegionExit(
2461 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002462 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002463
2464 // Check if the block @p BB is the entry of a region. If so we propagate it's
2465 // domain to the exit block of the region. Otherwise we are done.
2466 auto *RI = R.getRegionInfo();
2467 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2468 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002469 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002470 return;
2471
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002472 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002473 // Do not propagate the domain if there is a loop backedge inside the region
2474 // that would prevent the exit block from beeing executed.
2475 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002476 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002477 SmallVector<BasicBlock *, 4> LatchBBs;
2478 BBLoop->getLoopLatches(LatchBBs);
2479 for (auto *LatchBB : LatchBBs)
2480 if (BB != LatchBB && BBReg->contains(LatchBB))
2481 return;
2482 L = L->getParentLoop();
2483 }
2484
2485 auto *Domain = DomainMap[BB];
2486 assert(Domain && "Cannot propagate a nullptr");
2487
2488 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2489
2490 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2491 // adjust the domain before we can propagate it.
2492 auto *AdjustedDomain =
2493 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2494 auto *&ExitDomain = DomainMap[ExitBB];
2495
2496 // If the exit domain is not yet created we set it otherwise we "add" the
2497 // current domain.
2498 ExitDomain =
2499 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2500
Johannes Doerferta3519512016-04-23 13:02:23 +00002501 // Initialize the invalid domain.
2502 auto *ExitStmt = getStmtFor(ExitBB);
2503 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2504
Johannes Doerfert642594a2016-04-04 07:57:39 +00002505 FinishedExitBlocks.insert(ExitBB);
2506}
2507
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002508bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2509 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002510 // To create the domain for each block in R we iterate over all blocks and
2511 // subregions in R and propagate the conditions under which the current region
2512 // element is executed. To this end we iterate in reverse post order over R as
2513 // it ensures that we first visit all predecessors of a region node (either a
2514 // basic block or a subregion) before we visit the region node itself.
2515 // Initially, only the domain for the SCoP region entry block is set and from
2516 // there we propagate the current domain to all successors, however we add the
2517 // condition that the successor is actually executed next.
2518 // As we are only interested in non-loop carried constraints here we can
2519 // simply skip loop back edges.
2520
Johannes Doerfert642594a2016-04-04 07:57:39 +00002521 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002522 ReversePostOrderTraversal<Region *> RTraversal(R);
2523 for (auto *RN : RTraversal) {
2524
2525 // Recurse for affine subregions but go on for basic blocks and non-affine
2526 // subregions.
2527 if (RN->isSubRegion()) {
2528 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002529 if (!isNonAffineSubRegion(SubRegion)) {
2530 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002531 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002532 continue;
2533 }
2534 }
2535
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002536 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002537 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002538
Johannes Doerfert96425c22015-08-30 21:13:53 +00002539 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002540 TerminatorInst *TI = BB->getTerminator();
2541
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002542 if (isa<UnreachableInst>(TI))
2543 continue;
2544
Johannes Doerfertf5673802015-10-01 23:48:18 +00002545 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002546 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002547 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002548 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002549
Johannes Doerfert642594a2016-04-04 07:57:39 +00002550 auto *BBLoop = getRegionNodeLoop(RN, LI);
2551 // Propagate the domain from BB directly to blocks that have a superset
2552 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002553 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002554
2555 // If all successors of BB have been set a domain through the propagation
2556 // above we do not need to build condition sets but can just skip this
2557 // block. However, it is important to note that this is a local property
2558 // with regards to the region @p R. To this end FinishedExitBlocks is a
2559 // local variable.
2560 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2561 return FinishedExitBlocks.count(SuccBB);
2562 };
2563 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2564 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002565
2566 // Build the condition sets for the successor nodes of the current region
2567 // node. If it is a non-affine subregion we will always execute the single
2568 // exit node, hence the single entry node domain is the condition set. For
2569 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002570 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002571 if (RN->isSubRegion())
2572 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002573 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2574 ConditionSets))
2575 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002576
2577 // Now iterate over the successors and set their initial domain based on
2578 // their condition set. We skip back edges here and have to be careful when
2579 // we leave a loop not to keep constraints over a dimension that doesn't
2580 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002581 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002582 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002583 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002584 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002585
Johannes Doerfert535de032016-04-19 14:49:05 +00002586 auto *SuccStmt = getStmtFor(SuccBB);
2587 // Skip blocks outside the region.
2588 if (!SuccStmt) {
2589 isl_set_free(CondSet);
2590 continue;
2591 }
2592
Johannes Doerfert642594a2016-04-04 07:57:39 +00002593 // If we propagate the domain of some block to "SuccBB" we do not have to
2594 // adjust the domain.
2595 if (FinishedExitBlocks.count(SuccBB)) {
2596 isl_set_free(CondSet);
2597 continue;
2598 }
2599
Johannes Doerfert96425c22015-08-30 21:13:53 +00002600 // Skip back edges.
2601 if (DT.dominates(SuccBB, BB)) {
2602 isl_set_free(CondSet);
2603 continue;
2604 }
2605
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002606 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002607 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002608 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002609
2610 // Set the domain for the successor or merge it with an existing domain in
2611 // case there are multiple paths (without loop back edges) to the
2612 // successor block.
2613 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002614
Johannes Doerferta3519512016-04-23 13:02:23 +00002615 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002616 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002617 } else {
2618 // Initialize the invalid domain.
2619 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2620 SuccDomain = CondSet;
2621 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002622
Michael Krusebc150122016-05-02 12:25:18 +00002623 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002624 // In case this happens we will clean up and bail.
Michael Krusebc150122016-05-02 12:25:18 +00002625 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctionsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002626 continue;
2627
2628 invalidate(COMPLEXITY, DebugLoc());
2629 while (++u < ConditionSets.size())
2630 isl_set_free(ConditionSets[u]);
2631 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002632 }
2633 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002634
2635 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002636}
2637
Michael Krused56b90a2016-09-01 09:03:27 +00002638__isl_give isl_set *
2639Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2640 __isl_keep isl_set *Domain,
2641 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002642 // If @p BB is the ScopEntry we are done
2643 if (R.getEntry() == BB)
2644 return isl_set_universe(isl_set_get_space(Domain));
2645
2646 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002647 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002648
2649 // The region info of this function.
2650 auto &RI = *R.getRegionInfo();
2651
2652 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2653
2654 // A domain to collect all predecessor domains, thus all conditions under
2655 // which the block is executed. To this end we start with the empty domain.
2656 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2657
2658 // Set of regions of which the entry block domain has been propagated to BB.
2659 // all predecessors inside any of the regions can be skipped.
2660 SmallSet<Region *, 8> PropagatedRegions;
2661
2662 for (auto *PredBB : predecessors(BB)) {
2663 // Skip backedges.
2664 if (DT.dominates(BB, PredBB))
2665 continue;
2666
2667 // If the predecessor is in a region we used for propagation we can skip it.
2668 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2669 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2670 PredBBInRegion)) {
2671 continue;
2672 }
2673
2674 // Check if there is a valid region we can use for propagation, thus look
2675 // for a region that contains the predecessor and has @p BB as exit block.
2676 auto *PredR = RI.getRegionFor(PredBB);
2677 while (PredR->getExit() != BB && !PredR->contains(BB))
2678 PredR->getParent();
2679
2680 // If a valid region for propagation was found use the entry of that region
2681 // for propagation, otherwise the PredBB directly.
2682 if (PredR->getExit() == BB) {
2683 PredBB = PredR->getEntry();
2684 PropagatedRegions.insert(PredR);
2685 }
2686
Johannes Doerfert41cda152016-04-08 10:32:26 +00002687 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002688 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2689 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2690
2691 PredDom = isl_set_union(PredDom, PredBBDom);
2692 }
2693
2694 return PredDom;
2695}
2696
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002697bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2698 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002699 // Iterate over the region R and propagate the domain constrains from the
2700 // predecessors to the current node. In contrast to the
2701 // buildDomainsWithBranchConstraints function, this one will pull the domain
2702 // information from the predecessors instead of pushing it to the successors.
2703 // Additionally, we assume the domains to be already present in the domain
2704 // map here. However, we iterate again in reverse post order so we know all
2705 // predecessors have been visited before a block or non-affine subregion is
2706 // visited.
2707
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002708 ReversePostOrderTraversal<Region *> RTraversal(R);
2709 for (auto *RN : RTraversal) {
2710
2711 // Recurse for affine subregions but go on for basic blocks and non-affine
2712 // subregions.
2713 if (RN->isSubRegion()) {
2714 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002715 if (!isNonAffineSubRegion(SubRegion)) {
2716 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002717 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002718 continue;
2719 }
2720 }
2721
2722 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002723 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002724 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002725
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002726 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002727 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002728 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002729 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002730
Johannes Doerfert642594a2016-04-04 07:57:39 +00002731 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002732 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002733 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2734 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002735 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002736
2737 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002738}
2739
Tobias Grosserc80d6972016-09-02 06:33:33 +00002740/// Create a map to map from a given iteration to a subsequent iteration.
2741///
2742/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2743/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002744/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002745///
2746/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002747static __isl_give isl_map *
2748createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2749 auto *MapSpace = isl_space_map_from_set(SetSpace);
2750 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2751 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2752 if (u != Dim)
2753 NextIterationMap =
2754 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2755 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2756 C = isl_constraint_set_constant_si(C, 1);
2757 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2758 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2759 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2760 return NextIterationMap;
2761}
2762
Johannes Doerfert297c7202016-05-10 13:06:42 +00002763bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002764 int LoopDepth = getRelativeLoopDepth(L);
2765 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002766
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002767 BasicBlock *HeaderBB = L->getHeader();
2768 assert(DomainMap.count(HeaderBB));
2769 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002770
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002771 isl_map *NextIterationMap =
2772 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002773
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002774 isl_set *UnionBackedgeCondition =
2775 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002776
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002777 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2778 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002779
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002780 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002781
2782 // If the latch is only reachable via error statements we skip it.
2783 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2784 if (!LatchBBDom)
2785 continue;
2786
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002787 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002788
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002789 TerminatorInst *TI = LatchBB->getTerminator();
2790 BranchInst *BI = dyn_cast<BranchInst>(TI);
2791 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002792 BackedgeCondition = isl_set_copy(LatchBBDom);
2793 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002794 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002795 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002796 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
2797 ConditionSets))
2798 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002799
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002800 // Free the non back edge condition set as we do not need it.
2801 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002802
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002803 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002804 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002805
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002806 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2807 assert(LatchLoopDepth >= LoopDepth);
2808 BackedgeCondition =
2809 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2810 LatchLoopDepth - LoopDepth);
2811 UnionBackedgeCondition =
2812 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002813 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002814
2815 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2816 for (int i = 0; i < LoopDepth; i++)
2817 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2818
2819 isl_set *UnionBackedgeConditionComplement =
2820 isl_set_complement(UnionBackedgeCondition);
2821 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2822 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2823 UnionBackedgeConditionComplement =
2824 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2825 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2826 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2827
2828 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2829 HeaderBBDom = Parts.second;
2830
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002831 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2832 // the bounded assumptions to the context as they are already implied by the
2833 // <nsw> tag.
2834 if (Affinator.hasNSWAddRecForLoop(L)) {
2835 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002836 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002837 }
2838
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002839 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002840 recordAssumption(INFINITELOOP, UnboundedCtx,
2841 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002842 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002843}
2844
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002845MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
2846 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2847 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2848 if (!PointerBase)
2849 return nullptr;
2850
2851 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase->getValue());
2852 if (!PointerBaseInst)
2853 return nullptr;
2854
2855 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2856 if (!BasePtrStmt)
2857 return nullptr;
2858
2859 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2860}
2861
2862bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2863 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00002864 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
2865 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
2866 bool Hoistable = NHCtx != nullptr;
2867 isl_set_free(NHCtx);
2868 return !Hoistable;
2869 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002870
2871 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2872 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2873 if (auto *BasePtrInst = dyn_cast<Instruction>(PointerBase->getValue()))
2874 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00002875 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002876
2877 return false;
2878}
2879
Johannes Doerfert5210da52016-06-02 11:06:54 +00002880bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002881 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00002882 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002883
2884 if (buildAliasGroups(AA))
Johannes Doerfert5210da52016-06-02 11:06:54 +00002885 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002886
2887 // If a problem occurs while building the alias groups we need to delete
2888 // this SCoP and pretend it wasn't valid in the first place. To this end
2889 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002890 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002891
2892 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2893 << " could not be created as the number of parameters involved "
2894 "is too high. The SCoP will be "
2895 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2896 "the maximal number of parameters but be advised that the "
2897 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00002898 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002899}
2900
Johannes Doerfert9143d672014-09-27 11:02:39 +00002901bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002902 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002903 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002904 // for all memory accesses inside the SCoP.
2905 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002906 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002907 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002908 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002909 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002910 // if their access domains intersect, otherwise they are in different
2911 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002912 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002913 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002914 // and maximal accesses to each array of a group in read only and non
2915 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002916 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2917
2918 AliasSetTracker AST(AA);
2919
2920 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002921 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002922 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002923
2924 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002925 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002926 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2927 isl_set_free(StmtDomain);
2928 if (StmtDomainEmpty)
2929 continue;
2930
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002931 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002932 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002933 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002934 if (!MA->isRead())
2935 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002936 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002937 if (MA->isRead() && isa<MemTransferInst>(Acc))
2938 PtrToAcc[cast<MemTransferInst>(Acc)->getSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002939 else
2940 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002941 AST.add(Acc);
2942 }
2943 }
2944
2945 SmallVector<AliasGroupTy, 4> AliasGroups;
2946 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002947 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002948 continue;
2949 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002950 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002951 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002952 if (AG.size() < 2)
2953 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002954 AliasGroups.push_back(std::move(AG));
2955 }
2956
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002957 // Split the alias groups based on their domain.
2958 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2959 AliasGroupTy NewAG;
2960 AliasGroupTy &AG = AliasGroups[u];
2961 AliasGroupTy::iterator AGI = AG.begin();
2962 isl_set *AGDomain = getAccessDomain(*AGI);
2963 while (AGI != AG.end()) {
2964 MemoryAccess *MA = *AGI;
2965 isl_set *MADomain = getAccessDomain(MA);
2966 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2967 NewAG.push_back(MA);
2968 AGI = AG.erase(AGI);
2969 isl_set_free(MADomain);
2970 } else {
2971 AGDomain = isl_set_union(AGDomain, MADomain);
2972 AGI++;
2973 }
2974 }
2975 if (NewAG.size() > 1)
2976 AliasGroups.push_back(std::move(NewAG));
2977 isl_set_free(AGDomain);
2978 }
2979
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002980 auto &F = getFunction();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002981 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002982 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2983 for (AliasGroupTy &AG : AliasGroups) {
2984 NonReadOnlyBaseValues.clear();
2985 ReadOnlyPairs.clear();
2986
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002987 if (AG.size() < 2) {
2988 AG.clear();
2989 continue;
2990 }
2991
Johannes Doerfert13771732014-10-01 12:40:46 +00002992 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002993 emitOptimizationRemarkAnalysis(
2994 F.getContext(), DEBUG_TYPE, F,
2995 (*II)->getAccessInstruction()->getDebugLoc(),
2996 "Possibly aliasing pointer, use restrict keyword.");
2997
Johannes Doerfert13771732014-10-01 12:40:46 +00002998 Value *BaseAddr = (*II)->getBaseAddr();
2999 if (HasWriteAccess.count(BaseAddr)) {
3000 NonReadOnlyBaseValues.insert(BaseAddr);
3001 II++;
3002 } else {
3003 ReadOnlyPairs[BaseAddr].insert(*II);
3004 II = AG.erase(II);
3005 }
3006 }
3007
3008 // If we don't have read only pointers check if there are at least two
3009 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00003010 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003011 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00003012 continue;
3013 }
3014
3015 // If we don't have non read only pointers clear the alias group.
3016 if (NonReadOnlyBaseValues.empty()) {
3017 AG.clear();
3018 continue;
3019 }
3020
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003021 // Check if we have non-affine accesses left, if so bail out as we cannot
3022 // generate a good access range yet.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003023 for (auto *MA : AG) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003024 if (!MA->isAffine()) {
3025 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3026 return false;
3027 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003028 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
3029 addRequiredInvariantLoad(
3030 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3031 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003032 for (auto &ReadOnlyPair : ReadOnlyPairs)
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003033 for (auto *MA : ReadOnlyPair.second) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003034 if (!MA->isAffine()) {
3035 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3036 return false;
3037 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003038 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
3039 addRequiredInvariantLoad(
3040 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3041 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003042
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003043 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003044 MinMaxAliasGroups.emplace_back();
3045 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3046 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
3047 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3048 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003049
3050 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003051
3052 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00003053 for (MemoryAccess *MA : AG)
3054 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003055
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003056 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
3057 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003058
3059 // Bail out if the number of values we need to compare is too large.
3060 // This is important as the number of comparisions grows quadratically with
3061 // the number of values we need to compare.
Johannes Doerfert5210da52016-06-02 11:06:54 +00003062 if (!Valid || (MinMaxAccessesNonReadOnly.size() + ReadOnlyPairs.size() >
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003063 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003064 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003065
3066 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003067 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003068 Accesses = isl_union_map_empty(getParamSpace());
3069
3070 for (const auto &ReadOnlyPair : ReadOnlyPairs)
3071 for (MemoryAccess *MA : ReadOnlyPair.second)
3072 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
3073
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003074 Valid =
3075 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003076
3077 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003078 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003079 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003080
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003081 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003082}
3083
Tobias Grosserc80d6972016-09-02 06:33:33 +00003084/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003085static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003086 // Start with the smallest loop containing the entry and expand that
3087 // loop until it contains all blocks in the region. If there is a loop
3088 // containing all blocks in the region check if it is itself contained
3089 // and if so take the parent loop as it will be the smallest containing
3090 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003091 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003092 while (L) {
3093 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003094 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003095 AllContained &= L->contains(BB);
3096 if (AllContained)
3097 break;
3098 L = L->getParentLoop();
3099 }
3100
Johannes Doerfertef744432016-05-23 12:42:38 +00003101 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003102}
3103
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003104Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003105 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003106 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003107 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003108 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3109 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3110 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3111 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003112 if (IslOnErrorAbort)
3113 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003114 buildContext();
3115}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003116
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003117void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT,
3118 LoopInfo &LI) {
3119 buildInvariantEquivalenceClasses();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003120
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003121 if (!buildDomains(&R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003122 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003123
Johannes Doerfertff68f462016-04-19 14:49:42 +00003124 addUserAssumptions(AC, DT, LI);
3125
Johannes Doerfert26404542016-05-10 12:19:47 +00003126 // Remove empty statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003127 // Exit early in case there are no executable statements left in this scop.
Michael Kruse977d38b2016-07-22 17:31:17 +00003128 simplifySCoP(false);
Michael Kruseafe06702015-10-02 16:33:27 +00003129 if (Stmts.empty())
3130 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003131
Michael Krusecac948e2015-10-02 13:53:07 +00003132 // The ScopStmts now have enough information to initialize themselves.
3133 for (ScopStmt &Stmt : Stmts)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003134 Stmt.init(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00003135
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003136 // Check early for profitability. Afterwards it cannot change anymore,
3137 // only the runtime context could become infeasible.
3138 if (!isProfitable()) {
3139 invalidate(PROFITABLE, DebugLoc());
Tobias Grosser8286b832015-11-02 11:29:32 +00003140 return;
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003141 }
3142
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003143 buildSchedule(LI);
Tobias Grosser8286b832015-11-02 11:29:32 +00003144
3145 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003146 realignParams();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003147 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003148
3149 // After the context was fully constructed, thus all our knowledge about
3150 // the parameters is in there, we add all recorded assumptions to the
3151 // assumed/invalid context.
3152 addRecordedAssumptions();
3153
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003154 simplifyContexts();
Johannes Doerfert5210da52016-06-02 11:06:54 +00003155 if (!buildAliasChecks(AA))
3156 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003157
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003158 hoistInvariantLoads();
3159 verifyInvariantLoads();
Michael Kruse977d38b2016-07-22 17:31:17 +00003160 simplifySCoP(true);
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003161
3162 // Check late for a feasible runtime context because profitability did not
3163 // change.
3164 if (!hasFeasibleRuntimeContext()) {
3165 invalidate(PROFITABLE, DebugLoc());
3166 return;
3167 }
Tobias Grosser75805372011-04-29 06:27:02 +00003168}
3169
3170Scop::~Scop() {
3171 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003172 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003173 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003174 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003175
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003176 for (auto &It : ParameterIds)
3177 isl_id_free(It.second);
3178
Johannes Doerfert96425c22015-08-30 21:13:53 +00003179 for (auto It : DomainMap)
3180 isl_set_free(It.second);
3181
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003182 for (auto &AS : RecordedAssumptions)
3183 isl_set_free(AS.Set);
3184
Johannes Doerfertb164c792014-09-18 11:17:17 +00003185 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003186 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003187 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003188 isl_pw_multi_aff_free(MMA.first);
3189 isl_pw_multi_aff_free(MMA.second);
3190 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003191 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003192 isl_pw_multi_aff_free(MMA.first);
3193 isl_pw_multi_aff_free(MMA.second);
3194 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003195 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003196
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003197 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003198 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003199
3200 // Explicitly release all Scop objects and the underlying isl objects before
3201 // we relase the isl context.
3202 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003203 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003204 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003205 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003206 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003207}
3208
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003209void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003210 // Check all array accesses for each base pointer and find a (virtual) element
3211 // size for the base pointer that divides all access functions.
3212 for (auto &Stmt : *this)
3213 for (auto *Access : Stmt) {
3214 if (!Access->isArrayKind())
3215 continue;
3216 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
3217 ScopArrayInfo::MK_Array)];
3218 if (SAI->getNumberOfDimensions() != 1)
3219 continue;
3220 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3221 auto *Subscript = Access->getSubscript(0);
3222 while (!isDivisible(Subscript, DivisibleSize, *SE))
3223 DivisibleSize /= 2;
3224 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3225 SAI->updateElementType(Ty);
3226 }
3227
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003228 for (auto &Stmt : *this)
3229 for (auto &Access : Stmt)
3230 Access->updateDimensionality();
3231}
3232
Michael Kruse977d38b2016-07-22 17:31:17 +00003233void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003234 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3235 ScopStmt &Stmt = *StmtIt;
3236
Johannes Doerfert26404542016-05-10 12:19:47 +00003237 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003238 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003239 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003240
Johannes Doerferteca9e892015-11-03 16:54:49 +00003241 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003242 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003243 bool OnlyRead = true;
3244 for (MemoryAccess *MA : Stmt) {
3245 if (MA->isRead())
3246 continue;
3247
3248 OnlyRead = false;
3249 break;
3250 }
3251
3252 RemoveStmt = OnlyRead;
3253 }
3254
Johannes Doerfert26404542016-05-10 12:19:47 +00003255 if (!RemoveStmt) {
3256 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003257 continue;
3258 }
3259
Johannes Doerfert26404542016-05-10 12:19:47 +00003260 // Remove the statement because it is unnecessary.
3261 if (Stmt.isRegionStmt())
3262 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3263 StmtMap.erase(BB);
3264 else
3265 StmtMap.erase(Stmt.getBasicBlock());
3266
3267 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003268 }
3269}
3270
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003271InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003272 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3273 if (!LInst)
3274 return nullptr;
3275
3276 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3277 LInst = cast<LoadInst>(Rep);
3278
Johannes Doerfert96e54712016-02-07 17:30:13 +00003279 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003280 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003281 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003282 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003283 continue;
3284
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003285 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003286 for (auto *MA : MAs)
3287 if (MA->getAccessInstruction() == Val)
3288 return &IAClass;
3289 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003290
3291 return nullptr;
3292}
3293
Tobias Grosserc80d6972016-09-02 06:33:33 +00003294/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003295static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003296 bool MAInvalidCtxIsEmpty,
3297 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003298 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3299 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3300 // TODO: We can provide more information for better but more expensive
3301 // results.
3302 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3303 LInst->getAlignment(), DL))
3304 return false;
3305
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003306 // If the location might be overwritten we do not hoist it unconditionally.
3307 //
3308 // TODO: This is probably to conservative.
3309 if (!NonHoistableCtxIsEmpty)
3310 return false;
3311
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003312 // If a dereferencable load is in a statement that is modeled precisely we can
3313 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003314 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003315 return true;
3316
3317 // Even if the statement is not modeled precisely we can hoist the load if it
3318 // does not involve any parameters that might have been specilized by the
3319 // statement domain.
3320 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3321 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3322 return false;
3323 return true;
3324}
3325
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003326void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003327
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003328 if (InvMAs.empty())
3329 return;
3330
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003331 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003332 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003333
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003334 // Get the context under which the statement is executed but remove the error
3335 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003336 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003337 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003338
Michael Krusebc150122016-05-02 12:25:18 +00003339 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctionsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003340 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003341 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3342 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003343 for (auto &InvMA : InvMAs)
3344 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003345 return;
3346 }
3347
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003348 // Project out all parameters that relate to loads in the statement. Otherwise
3349 // we could have cyclic dependences on the constraints under which the
3350 // hoisted loads are executed and we could not determine an order in which to
3351 // pre-load them. This happens because not only lower bounds are part of the
3352 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003353 for (auto &InvMA : InvMAs) {
3354 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003355 Instruction *AccInst = MA->getAccessInstruction();
3356 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003357 SetVector<Value *> Values;
3358 for (const SCEV *Parameter : Parameters) {
3359 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003360 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003361 if (!Values.count(AccInst))
3362 continue;
3363
3364 if (isl_id *ParamId = getIdForParam(Parameter)) {
3365 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3366 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3367 isl_id_free(ParamId);
3368 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003369 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003370 }
3371 }
3372
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003373 for (auto &InvMA : InvMAs) {
3374 auto *MA = InvMA.MA;
3375 auto *NHCtx = InvMA.NonHoistableCtx;
3376
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003377 // Check for another invariant access that accesses the same location as
3378 // MA and if found consolidate them. Otherwise create a new equivalence
3379 // class at the end of InvariantEquivClasses.
3380 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003381 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003382 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3383
Johannes Doerfert85676e32016-04-23 14:32:34 +00003384 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003385 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003386 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3387
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003388 isl_set *MACtx;
3389 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003390 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3391 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003392 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003393 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003394 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003395 } else {
3396 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003397 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003398 MACtx = isl_set_gist_params(MACtx, getContext());
3399 }
3400
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003401 bool Consolidated = false;
3402 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003403 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003404 continue;
3405
Johannes Doerfertdf880232016-03-03 12:26:58 +00003406 // If the pointer and the type is equal check if the access function wrt.
3407 // to the domain is equal too. It can happen that the domain fixes
3408 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003409 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003410 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003411 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003412 if (!MAs.empty()) {
3413 auto *LastMA = MAs.front();
3414
3415 auto *AR = isl_map_range(MA->getAccessRelation());
3416 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3417 bool SameAR = isl_set_is_equal(AR, LastAR);
3418 isl_set_free(AR);
3419 isl_set_free(LastAR);
3420
3421 if (!SameAR)
3422 continue;
3423 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003424
3425 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003426 MAs.push_front(MA);
3427
Johannes Doerfertdf880232016-03-03 12:26:58 +00003428 Consolidated = true;
3429
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003430 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003431 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003432 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003433 IAClassDomainCtx =
3434 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003435 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003436 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003437 break;
3438 }
3439
3440 if (Consolidated)
3441 continue;
3442
3443 // If we did not consolidate MA, thus did not find an equivalence class
3444 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003445 InvariantEquivClasses.emplace_back(
3446 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003447 }
3448
3449 isl_set_free(DomainCtx);
3450}
3451
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003452__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3453 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003454 // TODO: Loads that are not loop carried, hence are in a statement with
3455 // zero iterators, are by construction invariant, though we
3456 // currently "hoist" them anyway. This is necessary because we allow
3457 // them to be treated as parameters (e.g., in conditions) and our code
3458 // generation would otherwise use the old value.
3459
3460 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003461 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003462
3463 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003464 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003465
3466 // Skip accesses that have an invariant base pointer which is defined but
3467 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3468 // returns a pointer that is used as a base address. However, as we want
3469 // to hoist indirect pointers, we allow the base pointer to be defined in
3470 // the region if it is also a memory access. Each ScopArrayInfo object
3471 // that has a base pointer origin has a base pointer that is loaded and
3472 // that it is invariant, thus it will be hoisted too. However, if there is
3473 // no base pointer origin we check that the base pointer is defined
3474 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003475 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003476 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003477 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003478
3479 // Skip accesses in non-affine subregions as they might not be executed
3480 // under the same condition as the entry of the non-affine subregion.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003481 if (BB != LI->getParent())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003482 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003483
3484 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003485 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003486
3487 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3488 Stmt.getNumIterators())) {
3489 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003490 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003491 }
3492
3493 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3494 isl_set *AccessRange = isl_map_range(AccessRelation);
3495
3496 isl_union_map *Written = isl_union_map_intersect_range(
3497 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003498 auto *WrittenCtx = isl_union_map_params(Written);
3499 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003500
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003501 if (!IsWritten)
3502 return WrittenCtx;
3503
3504 WrittenCtx = isl_set_remove_divs(WrittenCtx);
3505 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctionsInDomain;
3506 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3507 isl_set_free(WrittenCtx);
3508 return nullptr;
3509 }
3510
3511 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3512 AS_RESTRICTION);
3513 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003514}
3515
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003516void Scop::verifyInvariantLoads() {
3517 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003518 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003519 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003520 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003521 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003522 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3523 return;
3524 }
3525 }
3526}
3527
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003528void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003529 if (!PollyInvariantLoadHoisting)
3530 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003531
Tobias Grosser0865e7752016-02-29 07:29:42 +00003532 isl_union_map *Writes = getWrites();
3533 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003534 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003535
Tobias Grosser0865e7752016-02-29 07:29:42 +00003536 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003537 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3538 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003539
3540 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003541 for (auto InvMA : InvariantAccesses)
3542 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003543 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003544 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003545 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003546}
3547
Roman Gareevd7754a12016-07-30 09:25:51 +00003548const ScopArrayInfo *Scop::getOrCreateScopArrayInfo(
3549 Value *BasePtr, Type *ElementType, ArrayRef<const SCEV *> Sizes,
3550 ScopArrayInfo::MemoryKind Kind, const char *BaseName) {
3551 assert((BasePtr || BaseName) &&
3552 "BasePtr and BaseName can not be nullptr at the same time.");
3553 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3554 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3555 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003556 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003557 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003558 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003559 DL, this, BaseName));
3560 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003561 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003562 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003563 // In case of mismatching array sizes, we bail out by setting the run-time
3564 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003565 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003566 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003567 }
Tobias Grosserab671442015-05-23 05:58:27 +00003568 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003569}
3570
Roman Gareevd7754a12016-07-30 09:25:51 +00003571const ScopArrayInfo *
3572Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3573 const std::vector<unsigned> &Sizes) {
3574 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3575 std::vector<const SCEV *> SCEVSizes;
3576
3577 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003578 if (size)
3579 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3580 else
3581 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003582
3583 auto *SAI =
3584 getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3585 ScopArrayInfo::MK_Array, BaseName.c_str());
3586 return SAI;
3587}
3588
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003589const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003590 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003591 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003592 assert(SAI && "No ScopArrayInfo available for this base pointer");
3593 return SAI;
3594}
3595
Tobias Grosser74394f02013-01-14 22:40:23 +00003596std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003597
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003598std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003599 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003600 return stringFromIslObj(AssumedContext);
3601}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003602
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003603std::string Scop::getInvalidContextStr() const {
3604 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003605}
Tobias Grosser75805372011-04-29 06:27:02 +00003606
3607std::string Scop::getNameStr() const {
3608 std::string ExitName, EntryName;
3609 raw_string_ostream ExitStr(ExitName);
3610 raw_string_ostream EntryStr(EntryName);
3611
Tobias Grosserf240b482014-01-09 10:42:15 +00003612 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003613 EntryStr.str();
3614
3615 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003616 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003617 ExitStr.str();
3618 } else
3619 ExitName = "FunctionExit";
3620
3621 return EntryName + "---" + ExitName;
3622}
3623
Tobias Grosser74394f02013-01-14 22:40:23 +00003624__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003625__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003626 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003627}
3628
Tobias Grossere86109f2013-10-29 21:05:49 +00003629__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003630 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003631 return isl_set_copy(AssumedContext);
3632}
3633
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003634bool Scop::isProfitable() const {
3635 if (PollyProcessUnprofitable)
3636 return true;
3637
3638 if (!hasFeasibleRuntimeContext())
3639 return false;
3640
3641 if (isEmpty())
3642 return false;
3643
3644 unsigned OptimizableStmtsOrLoops = 0;
3645 for (auto &Stmt : *this) {
3646 if (Stmt.getNumIterators() == 0)
3647 continue;
3648
3649 bool ContainsArrayAccs = false;
3650 bool ContainsScalarAccs = false;
3651 for (auto *MA : Stmt) {
3652 if (MA->isRead())
3653 continue;
3654 ContainsArrayAccs |= MA->isArrayKind();
3655 ContainsScalarAccs |= MA->isScalarKind();
3656 }
3657
Michael Kruse6ab44762016-10-04 17:33:39 +00003658 if (!UnprofitableScalarAccs || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003659 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3660 }
3661
3662 return OptimizableStmtsOrLoops > 1;
3663}
3664
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003665bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003666 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003667 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003668 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3669 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3670 isl_set_is_subset(PositiveContext, NegativeContext));
3671 isl_set_free(PositiveContext);
3672 if (!IsFeasible) {
3673 isl_set_free(NegativeContext);
3674 return false;
3675 }
3676
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003677 auto *DomainContext = isl_union_set_params(getDomains());
3678 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003679 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003680 isl_set_free(NegativeContext);
3681 isl_set_free(DomainContext);
3682
Johannes Doerfert43788c52015-08-20 05:58:56 +00003683 return IsFeasible;
3684}
3685
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003686static std::string toString(AssumptionKind Kind) {
3687 switch (Kind) {
3688 case ALIASING:
3689 return "No-aliasing";
3690 case INBOUNDS:
3691 return "Inbounds";
3692 case WRAPPING:
3693 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00003694 case UNSIGNED:
3695 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003696 case COMPLEXITY:
3697 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003698 case PROFITABLE:
3699 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003700 case ERRORBLOCK:
3701 return "No-error";
3702 case INFINITELOOP:
3703 return "Finite loop";
3704 case INVARIANTLOAD:
3705 return "Invariant load";
3706 case DELINEARIZATION:
3707 return "Delinearization";
3708 }
3709 llvm_unreachable("Unknown AssumptionKind!");
3710}
3711
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003712bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
3713 if (Sign == AS_ASSUMPTION) {
3714 if (isl_set_is_subset(Context, Set))
3715 return false;
3716
3717 if (isl_set_is_subset(AssumedContext, Set))
3718 return false;
3719 } else {
3720 if (isl_set_is_disjoint(Set, Context))
3721 return false;
3722
3723 if (isl_set_is_subset(Set, InvalidContext))
3724 return false;
3725 }
3726 return true;
3727}
3728
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003729bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3730 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003731 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
3732 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003733
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003734 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003735 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3736 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003737 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003738 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003739}
3740
3741void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003742 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003743 // Simplify the assumptions/restrictions first.
3744 Set = isl_set_gist_params(Set, getContext());
3745
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003746 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3747 isl_set_free(Set);
3748 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003749 }
3750
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003751 if (Sign == AS_ASSUMPTION) {
3752 AssumedContext = isl_set_intersect(AssumedContext, Set);
3753 AssumedContext = isl_set_coalesce(AssumedContext);
3754 } else {
3755 InvalidContext = isl_set_union(InvalidContext, Set);
3756 InvalidContext = isl_set_coalesce(InvalidContext);
3757 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003758}
3759
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003760void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003761 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
3762 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003763}
3764
3765void Scop::addRecordedAssumptions() {
3766 while (!RecordedAssumptions.empty()) {
3767 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003768
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003769 if (!AS.BB) {
3770 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
3771 continue;
3772 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003773
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003774 // If the domain was deleted the assumptions are void.
3775 isl_set *Dom = getDomainConditions(AS.BB);
3776 if (!Dom) {
3777 isl_set_free(AS.Set);
3778 continue;
3779 }
3780
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003781 // If a basic block was given use its domain to simplify the assumption.
3782 // In case of restrictions we know they only have to hold on the domain,
3783 // thus we can intersect them with the domain of the block. However, for
3784 // assumptions the domain has to imply them, thus:
3785 // _ _____
3786 // Dom => S <==> A v B <==> A - B
3787 //
3788 // To avoid the complement we will register A - B as a restricton not an
3789 // assumption.
3790 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003791 if (AS.Sign == AS_RESTRICTION)
3792 S = isl_set_params(isl_set_intersect(S, Dom));
3793 else /* (AS.Sign == AS_ASSUMPTION) */
3794 S = isl_set_params(isl_set_subtract(Dom, S));
3795
3796 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003797 }
3798}
3799
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003800void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003801 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003802}
3803
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003804__isl_give isl_set *Scop::getInvalidContext() const {
3805 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003806}
3807
Tobias Grosser75805372011-04-29 06:27:02 +00003808void Scop::printContext(raw_ostream &OS) const {
3809 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003810 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003811
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003812 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003813 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003814
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003815 OS.indent(4) << "Invalid Context:\n";
3816 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003817
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003818 unsigned Dim = 0;
3819 for (const SCEV *Parameter : Parameters)
3820 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003821}
3822
Johannes Doerfertb164c792014-09-18 11:17:17 +00003823void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003824 int noOfGroups = 0;
3825 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003826 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003827 noOfGroups += 1;
3828 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003829 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003830 }
3831
Tobias Grosserbb853c22015-07-25 12:31:03 +00003832 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003833 if (MinMaxAliasGroups.empty()) {
3834 OS.indent(8) << "n/a\n";
3835 return;
3836 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003837
Tobias Grosserbb853c22015-07-25 12:31:03 +00003838 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003839
3840 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003841 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003842 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003843 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003844 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3845 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003846 }
3847 OS << " ]]\n";
3848 }
3849
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003850 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003851 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003852 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003853 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003854 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3855 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003856 }
3857 OS << " ]]\n";
3858 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003859 }
3860}
3861
Tobias Grosser75805372011-04-29 06:27:02 +00003862void Scop::printStatements(raw_ostream &OS) const {
3863 OS << "Statements {\n";
3864
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003865 for (const ScopStmt &Stmt : *this)
3866 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003867
3868 OS.indent(4) << "}\n";
3869}
3870
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003871void Scop::printArrayInfo(raw_ostream &OS) const {
3872 OS << "Arrays {\n";
3873
Tobias Grosserab671442015-05-23 05:58:27 +00003874 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00003875 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003876
3877 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003878
3879 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3880
3881 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00003882 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003883
3884 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003885}
3886
Tobias Grosser75805372011-04-29 06:27:02 +00003887void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003888 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003889 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003890 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003891 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003892 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003893 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003894 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003895 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003896 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003897 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003898 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
3899 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003900 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003901 }
3902 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003903 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003904 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003905 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003906 printStatements(OS.indent(4));
3907}
3908
3909void Scop::dump() const { print(dbgs()); }
3910
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003911isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003912
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003913__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
3914 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003915 // First try to use the SCEVAffinator to generate a piecewise defined
3916 // affine function from @p E in the context of @p BB. If that tasks becomes to
3917 // complex the affinator might return a nullptr. In such a case we invalidate
3918 // the SCoP and return a dummy value. This way we do not need to add error
3919 // handling cdoe to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003920 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003921 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00003922 // TODO: We could use a heuristic and either use:
3923 // SCEVAffinator::takeNonNegativeAssumption
3924 // or
3925 // SCEVAffinator::interpretAsUnsigned
3926 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003927 if (NonNegative)
3928 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003929 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003930 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003931
3932 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
3933 invalidate(COMPLEXITY, DL);
3934 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003935}
3936
Tobias Grosser808cd692015-07-14 09:33:13 +00003937__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003938 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003939
Tobias Grosser808cd692015-07-14 09:33:13 +00003940 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003941 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003942
3943 return Domain;
3944}
3945
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003946__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
3947 PWACtx PWAC = getPwAff(E, BB);
3948 isl_set_free(PWAC.second);
3949 return PWAC.first;
3950}
3951
Tobias Grossere5a35142015-11-12 14:07:09 +00003952__isl_give isl_union_map *
3953Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3954 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003955
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003956 for (ScopStmt &Stmt : *this) {
3957 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003958 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003959 continue;
3960
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003961 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003962 isl_map *AccessDomain = MA->getAccessRelation();
3963 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003964 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003965 }
3966 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003967 return isl_union_map_coalesce(Accesses);
3968}
3969
3970__isl_give isl_union_map *Scop::getMustWrites() {
3971 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003972}
3973
3974__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003975 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003976}
3977
Tobias Grosser37eb4222014-02-20 21:43:54 +00003978__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003979 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003980}
3981
3982__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003983 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003984}
3985
Tobias Grosser2ac23382015-11-12 14:07:13 +00003986__isl_give isl_union_map *Scop::getAccesses() {
3987 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3988}
3989
Roman Gareevb3224ad2016-09-14 06:26:09 +00003990// Check whether @p Node is an extension node.
3991//
3992// @return true if @p Node is an extension node.
3993isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
3994 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
3995 return isl_bool_error;
3996 else
3997 return isl_bool_true;
3998}
3999
4000bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4001 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4002 nullptr) == isl_stat_error;
4003}
4004
Tobias Grosser808cd692015-07-14 09:33:13 +00004005__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004006 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004007 if (containsExtensionNode(Tree)) {
4008 isl_schedule_free(Tree);
4009 return nullptr;
4010 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004011 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004012 isl_schedule_free(Tree);
4013 return S;
4014}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004015
Tobias Grosser808cd692015-07-14 09:33:13 +00004016__isl_give isl_schedule *Scop::getScheduleTree() const {
4017 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4018 getDomains());
4019}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004020
Tobias Grosser808cd692015-07-14 09:33:13 +00004021void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4022 auto *S = isl_schedule_from_domain(getDomains());
4023 S = isl_schedule_insert_partial_schedule(
4024 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4025 isl_schedule_free(Schedule);
4026 Schedule = S;
4027}
4028
4029void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4030 isl_schedule_free(Schedule);
4031 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004032}
4033
4034bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4035 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004036 for (ScopStmt &Stmt : *this) {
4037 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004038 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4039 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4040
4041 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4042 isl_union_set_free(StmtDomain);
4043 isl_union_set_free(NewStmtDomain);
4044 continue;
4045 }
4046
4047 Changed = true;
4048
4049 isl_union_set_free(StmtDomain);
4050 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4051
4052 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004053 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004054 isl_union_set_free(NewStmtDomain);
4055 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004056 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004057 }
4058 isl_union_set_free(Domain);
4059 return Changed;
4060}
4061
Tobias Grosser75805372011-04-29 06:27:02 +00004062ScalarEvolution *Scop::getSE() const { return SE; }
4063
Tobias Grosser808cd692015-07-14 09:33:13 +00004064struct MapToDimensionDataTy {
4065 int N;
4066 isl_union_pw_multi_aff *Res;
4067};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004068
Tobias Grosserc80d6972016-09-02 06:33:33 +00004069// Create a function that maps the elements of 'Set' to its N-th dimension and
4070// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004071//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004072// @param Set The input set.
4073// @param User->N The dimension to map to.
4074// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004075//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004076// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004077static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4078 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4079 int Dim;
4080 isl_space *Space;
4081 isl_pw_multi_aff *PMA;
4082
4083 Dim = isl_set_dim(Set, isl_dim_set);
4084 Space = isl_set_get_space(Set);
4085 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4086 Dim - Data->N);
4087 if (Data->N > 1)
4088 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4089 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4090
4091 isl_set_free(Set);
4092
4093 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004094}
4095
Tobias Grosserc80d6972016-09-02 06:33:33 +00004096// Create an isl_multi_union_aff that defines an identity mapping from the
4097// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004098//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004099// # Example:
4100//
4101// Domain: { A[i,j]; B[i,j,k] }
4102// N: 1
4103//
4104// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4105//
4106// @param USet A union set describing the elements for which to generate a
4107// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004108// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004109// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004110static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004111mapToDimension(__isl_take isl_union_set *USet, int N) {
4112 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004113 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004114 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004115
Tobias Grosser808cd692015-07-14 09:33:13 +00004116 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004117
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004118 auto *Space = isl_union_set_get_space(USet);
4119 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004120
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004121 Data = {N, PwAff};
4122
4123 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004124 (void)Res;
4125
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004126 assert(Res == isl_stat_ok);
4127
4128 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004129 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4130}
4131
Tobias Grosser316b5b22015-11-11 19:28:14 +00004132void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00004133 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00004134 Stmts.emplace_back(*this, *BB);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004135 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004136 StmtMap[BB] = Stmt;
4137 } else {
4138 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00004139 Stmts.emplace_back(*this, *R);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004140 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004141 for (BasicBlock *BB : R->blocks())
4142 StmtMap[BB] = Stmt;
4143 }
Tobias Grosser808cd692015-07-14 09:33:13 +00004144}
4145
Roman Gareevb3224ad2016-09-14 06:26:09 +00004146ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4147 __isl_take isl_map *TargetRel,
4148 __isl_take isl_set *Domain) {
4149 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4150 CopyStmtsNum++;
4151 return &(Stmts.back());
4152}
4153
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004154void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004155 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004156 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004157 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004158 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4159 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004160}
4161
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004162/// To generate a schedule for the elements in a Region we traverse the Region
4163/// in reverse-post-order and add the contained RegionNodes in traversal order
4164/// to the schedule of the loop that is currently at the top of the LoopStack.
4165/// For loop-free codes, this results in a correct sequential ordering.
4166///
4167/// Example:
4168/// bb1(0)
4169/// / \.
4170/// bb2(1) bb3(2)
4171/// \ / \.
4172/// bb4(3) bb5(4)
4173/// \ /
4174/// bb6(5)
4175///
4176/// Including loops requires additional processing. Whenever a loop header is
4177/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4178/// from an empty schedule, we first process all RegionNodes that are within
4179/// this loop and complete the sequential schedule at this loop-level before
4180/// processing about any other nodes. To implement this
4181/// loop-nodes-first-processing, the reverse post-order traversal is
4182/// insufficient. Hence, we additionally check if the traversal yields
4183/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4184/// These region-nodes are then queue and only traverse after the all nodes
4185/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004186void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004187 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004188
4189 ReversePostOrderTraversal<Region *> RTraversal(R);
4190 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4191 std::deque<RegionNode *> DelayList;
4192 bool LastRNWaiting = false;
4193
4194 // Iterate over the region @p R in reverse post-order but queue
4195 // sub-regions/blocks iff they are not part of the last encountered but not
4196 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4197 // that we queued the last sub-region/block from the reverse post-order
4198 // iterator. If it is set we have to explore the next sub-region/block from
4199 // the iterator (if any) to guarantee progress. If it is not set we first try
4200 // the next queued sub-region/blocks.
4201 while (!WorkList.empty() || !DelayList.empty()) {
4202 RegionNode *RN;
4203
4204 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4205 RN = WorkList.front();
4206 WorkList.pop_front();
4207 LastRNWaiting = false;
4208 } else {
4209 RN = DelayList.front();
4210 DelayList.pop_front();
4211 }
4212
4213 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004214 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004215 L = OuterScopLoop;
4216
Tobias Grosser151ae322016-04-03 19:36:52 +00004217 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004218 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004219 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004220 LastRNWaiting = true;
4221 DelayList.push_back(RN);
4222 continue;
4223 }
4224 LoopStack.push_back({L, nullptr, 0});
4225 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004226 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004227 }
4228
4229 return;
4230}
4231
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004232void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004233
Tobias Grosser8362c262016-01-06 15:30:06 +00004234 if (RN->isSubRegion()) {
4235 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004236 if (!isNonAffineSubRegion(LocalRegion)) {
4237 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004238 return;
4239 }
4240 }
Michael Kruse046dde42015-08-10 13:01:57 +00004241
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004242 auto &LoopData = LoopStack.back();
4243 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004244
Michael Kruse6f7721f2016-02-24 22:08:19 +00004245 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004246 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4247 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004248 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004249 }
4250
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004251 // Check if we just processed the last node in this loop. If we did, finalize
4252 // the loop by:
4253 //
4254 // - adding new schedule dimensions
4255 // - folding the resulting schedule into the parent loop schedule
4256 // - dropping the loop schedule from the LoopStack.
4257 //
4258 // Then continue to check surrounding loops, which might also have been
4259 // completed by this node.
4260 while (LoopData.L &&
4261 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004262 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004263 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004264
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004265 LoopStack.pop_back();
4266 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004267
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004268 if (Schedule) {
4269 auto *Domain = isl_schedule_get_domain(Schedule);
4270 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4271 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4272 NextLoopData.Schedule =
4273 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004274 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004275
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004276 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4277 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004278 }
Tobias Grosser75805372011-04-29 06:27:02 +00004279}
4280
Michael Kruse6f7721f2016-02-24 22:08:19 +00004281ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004282 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004283 if (StmtMapIt == StmtMap.end())
4284 return nullptr;
4285 return StmtMapIt->second;
4286}
4287
Michael Kruse6f7721f2016-02-24 22:08:19 +00004288ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4289 if (RN->isSubRegion())
4290 return getStmtFor(RN->getNodeAs<Region>());
4291 return getStmtFor(RN->getNodeAs<BasicBlock>());
4292}
4293
4294ScopStmt *Scop::getStmtFor(Region *R) const {
4295 ScopStmt *Stmt = getStmtFor(R->getEntry());
4296 assert(!Stmt || Stmt->getRegion() == R);
4297 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004298}
4299
Johannes Doerfert96425c22015-08-30 21:13:53 +00004300int Scop::getRelativeLoopDepth(const Loop *L) const {
4301 Loop *OuterLoop =
4302 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4303 if (!OuterLoop)
4304 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004305 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4306}
4307
Roman Gareevd7754a12016-07-30 09:25:51 +00004308ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4309 for (auto &SAI : arrays()) {
4310 if (SAI->getName() == BaseName)
4311 return SAI;
4312 }
4313 return nullptr;
4314}
4315
Johannes Doerfert99191c72016-05-31 09:41:04 +00004316//===----------------------------------------------------------------------===//
4317void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4318 AU.addRequired<LoopInfoWrapperPass>();
4319 AU.addRequired<RegionInfoPass>();
4320 AU.addRequired<DominatorTreeWrapperPass>();
4321 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4322 AU.addRequiredTransitive<ScopDetection>();
4323 AU.addRequired<AAResultsWrapperPass>();
4324 AU.addRequired<AssumptionCacheTracker>();
4325 AU.setPreservesAll();
4326}
4327
4328bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4329 auto &SD = getAnalysis<ScopDetection>();
4330
4331 if (!SD.isMaxRegionInScop(*R))
4332 return false;
4333
4334 Function *F = R->getEntry()->getParent();
4335 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4336 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4337 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4338 auto const &DL = F->getParent()->getDataLayout();
4339 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4340 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
4341
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004342 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4343 S = SB.getScop(); // take ownership of scop object
Tobias Grosser75805372011-04-29 06:27:02 +00004344 return false;
4345}
4346
Johannes Doerfert99191c72016-05-31 09:41:04 +00004347void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004348 if (S)
4349 S->print(OS);
4350 else
4351 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004352}
Tobias Grosser75805372011-04-29 06:27:02 +00004353
Johannes Doerfert99191c72016-05-31 09:41:04 +00004354char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004355
Johannes Doerfert99191c72016-05-31 09:41:04 +00004356Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4357
4358INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004359 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004360 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004361INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004362INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004363INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004364INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004365INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004366INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004367INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004368INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004369 "Polly - Create polyhedral description of Scops", false,
4370 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004371
4372//===----------------------------------------------------------------------===//
4373void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4374 AU.addRequired<LoopInfoWrapperPass>();
4375 AU.addRequired<RegionInfoPass>();
4376 AU.addRequired<DominatorTreeWrapperPass>();
4377 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4378 AU.addRequiredTransitive<ScopDetection>();
4379 AU.addRequired<AAResultsWrapperPass>();
4380 AU.addRequired<AssumptionCacheTracker>();
4381 AU.setPreservesAll();
4382}
4383
4384bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4385 auto &SD = getAnalysis<ScopDetection>();
4386
4387 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4388 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4389 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4390 auto const &DL = F.getParent()->getDataLayout();
4391 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4392 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4393
4394 /// Create polyhedral descripton of scops for all the valid regions of a
4395 /// function.
4396 for (auto &It : SD) {
4397 Region *R = const_cast<Region *>(It);
4398 if (!SD.isMaxRegionInScop(*R))
4399 continue;
4400
4401 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004402 std::unique_ptr<Scop> S = SB.getScop();
4403 if (!S)
4404 continue;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004405 bool Inserted =
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004406 RegionToScopMap.insert(std::make_pair(R, std::move(S))).second;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004407 assert(Inserted && "Building Scop for the same region twice!");
4408 (void)Inserted;
4409 }
4410 return false;
4411}
4412
4413void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4414 for (auto &It : RegionToScopMap) {
4415 if (It.second)
4416 It.second->print(OS);
4417 else
4418 OS << "Invalid Scop!\n";
4419 }
4420}
4421
4422char ScopInfoWrapperPass::ID = 0;
4423
4424Pass *polly::createScopInfoWrapperPassPass() {
4425 return new ScopInfoWrapperPass();
4426}
4427
4428INITIALIZE_PASS_BEGIN(
4429 ScopInfoWrapperPass, "polly-function-scops",
4430 "Polly - Create polyhedral description of all Scops of a function", false,
4431 false);
4432INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
4433INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
4434INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4435INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4436INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4437INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4438INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4439INITIALIZE_PASS_END(
4440 ScopInfoWrapperPass, "polly-function-scops",
4441 "Polly - Create polyhedral description of all Scops of a function", false,
4442 false)