blob: 64f3b47268978e11974691f2971c2831e34b5337 [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 Kruse7bf39442015-09-10 12:46:52 +0000107//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000108
Michael Kruse046dde42015-08-10 13:01:57 +0000109// Create a sequence of two schedules. Either argument may be null and is
110// interpreted as the empty schedule. Can also return null if both schedules are
111// empty.
112static __isl_give isl_schedule *
113combineInSequence(__isl_take isl_schedule *Prev,
114 __isl_take isl_schedule *Succ) {
115 if (!Prev)
116 return Succ;
117 if (!Succ)
118 return Prev;
119
120 return isl_schedule_sequence(Prev, Succ);
121}
122
Johannes Doerferte7044942015-02-24 11:58:30 +0000123static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
124 const ConstantRange &Range,
125 int dim,
126 enum isl_dim_type type) {
127 isl_val *V;
128 isl_ctx *ctx = isl_set_get_ctx(S);
129
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000130 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
131 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000132 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000133 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
134
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000135 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000136 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000137 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000138 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000139 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
140
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000141 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000142 return isl_set_union(SLB, SUB);
143 else
144 return isl_set_intersect(SLB, SUB);
145}
146
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000147static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
148 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
149 if (!BasePtrLI)
150 return nullptr;
151
Johannes Doerfert952b5302016-05-23 12:40:48 +0000152 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000153 return nullptr;
154
155 ScalarEvolution &SE = *S->getSE();
156
157 auto *OriginBaseSCEV =
158 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
159 if (!OriginBaseSCEV)
160 return nullptr;
161
162 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
163 if (!OriginBaseSCEVUnknown)
164 return nullptr;
165
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000166 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000167 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000168}
169
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000170ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000171 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000172 const DataLayout &DL, Scop *S,
173 const char *BaseName)
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000174 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000175 std::string BasePtrName =
Roman Gareevd7754a12016-07-30 09:25:51 +0000176 BaseName ? BaseName : getIslCompatibleName("MemRef_", BasePtr,
177 Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000178 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000179
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000180 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000181
Michael Kruseca7cbcc2016-10-04 17:33:34 +0000182 if (!BasePtr || Kind != MK_Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000183 BasePtrOriginSAI = nullptr;
184 return;
185 }
186
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000187 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
188 if (BasePtrOriginSAI)
189 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000190}
191
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000192__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000193 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000194 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
195 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
196 return Space;
197}
198
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000199bool ScopArrayInfo::isReadOnly() {
200 isl_union_set *WriteSet = isl_union_map_range(S.getWrites());
201 isl_space *Space = getSpace();
202 WriteSet = isl_union_set_intersect(
203 WriteSet, isl_union_set_from_set(isl_set_universe(Space)));
204
205 bool IsReadOnly = isl_union_set_is_empty(WriteSet);
206 isl_union_set_free(WriteSet);
207
208 return IsReadOnly;
209}
210
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000211void ScopArrayInfo::updateElementType(Type *NewElementType) {
212 if (NewElementType == ElementType)
213 return;
214
Tobias Grosserd840fc72016-02-04 13:18:42 +0000215 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
216 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
217
Johannes Doerferta7920982016-02-25 14:08:48 +0000218 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000219 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000220
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000221 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
222 ElementType = NewElementType;
223 } else {
224 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
225 ElementType = IntegerType::get(ElementType->getContext(), GCD);
226 }
227}
228
229bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000230 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
231 int ExtraDimsNew = NewSizes.size() - SharedDims;
232 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000233
234 for (int i = 0; i < SharedDims; i++) {
Michael Kruse19c9d992016-09-13 09:56:05 +0000235 auto *NewSize = NewSizes[i + ExtraDimsNew];
236 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
Roman Gareevf5aff702016-09-12 17:08:31 +0000237 if (NewSize && KnownSize && NewSize != KnownSize)
Tobias Grosser8286b832015-11-02 11:29:32 +0000238 return false;
Roman Gareevf5aff702016-09-12 17:08:31 +0000239 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000240
241 if (DimensionSizes.size() >= NewSizes.size())
242 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000243
244 DimensionSizes.clear();
245 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
246 NewSizes.end());
247 for (isl_pw_aff *Size : DimensionSizesPw)
248 isl_pw_aff_free(Size);
249 DimensionSizesPw.clear();
250 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000251 if (!Expr) {
252 DimensionSizesPw.push_back(nullptr);
253 continue;
254 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000255 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000256 DimensionSizesPw.push_back(Size);
257 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000258 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000259}
260
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000261ScopArrayInfo::~ScopArrayInfo() {
262 isl_id_free(Id);
263 for (isl_pw_aff *Size : DimensionSizesPw)
264 isl_pw_aff_free(Size);
265}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000266
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000267std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
268
269int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000270 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000271}
272
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000273__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
274 return isl_id_copy(Id);
275}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000276
277void ScopArrayInfo::dump() const { print(errs()); }
278
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000279void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000280 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000281 unsigned u = 0;
282 if (getNumberOfDimensions() > 0 && !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000283 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000284 u++;
285 }
286 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000287 OS << "[";
288
Tobias Grosser26253842015-11-10 14:24:21 +0000289 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000290 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000291 OS << " " << Size << " ";
292 isl_pw_aff_free(Size);
293 } else {
294 OS << *getDimensionSize(u);
295 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000296
297 OS << "]";
298 }
299
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000300 OS << ";";
301
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000302 if (BasePtrOriginSAI)
303 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
304
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000305 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000306}
307
308const ScopArrayInfo *
309ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
310 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
311 assert(Id && "Output dimension didn't have an ID");
312 return getFromId(Id);
313}
314
Michael Krused56b90a2016-09-01 09:03:27 +0000315const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000316 void *User = isl_id_get_user(Id);
317 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
318 isl_id_free(Id);
319 return SAI;
320}
321
Michael Kruse3b425ff2016-04-11 14:34:08 +0000322void MemoryAccess::wrapConstantDimensions() {
323 auto *SAI = getScopArrayInfo();
324 auto *ArraySpace = SAI->getSpace();
325 auto *Ctx = isl_space_get_ctx(ArraySpace);
326 unsigned DimsArray = SAI->getNumberOfDimensions();
327
328 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
329 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
330 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
331
332 // Begin with last dimension, to iteratively carry into higher dimensions.
333 for (int i = DimsArray - 1; i > 0; i--) {
334 auto *DimSize = SAI->getDimensionSize(i);
335 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
336
337 // This transformation is not applicable to dimensions with dynamic size.
338 if (!DimSizeCst)
339 continue;
340
341 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
342 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
343 isl_dim_set, i);
344 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
345 isl_dim_set, i - 1);
346
347 // Compute: index % size
348 // Modulo must apply in the divide of the previous iteration, if any.
349 auto *Modulo = isl_aff_copy(Var);
350 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
351 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
352
353 // Compute: floor(index / size)
354 auto *Divide = Var;
355 Divide = isl_aff_div(
356 Divide,
357 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
358 Divide = isl_aff_floor(Divide);
359 Divide = isl_aff_add(Divide, PrevVar);
360 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
361
362 // Apply Modulo and Divide.
363 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
364 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
365 }
366
367 // Apply all modulo/divides on the accesses.
368 AccessRelation =
369 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
370 AccessRelation = isl_map_detect_equalities(AccessRelation);
371 isl_local_space_free(LArraySpace);
372}
373
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000374void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000375 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000376 auto *ArraySpace = SAI->getSpace();
377 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000378 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000379
380 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
381 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
382 auto DimsMissing = DimsArray - DimsAccess;
383
Michael Kruse375cb5f2016-02-24 22:08:24 +0000384 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000385 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000386 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000387 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000388
Johannes Doerferta90943d2016-02-21 16:37:25 +0000389 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000390 isl_set_universe(AccessSpace),
391 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000392
393 for (unsigned i = 0; i < DimsMissing; i++)
394 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
395
396 for (unsigned i = DimsMissing; i < DimsArray; i++)
397 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
398
399 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000400
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000401 // For the non delinearized arrays, divide the access function of the last
402 // subscript by the size of the elements in the array.
403 //
404 // A stride one array access in C expressed as A[i] is expressed in
405 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
406 // two subsequent values of 'i' index two values that are stored next to
407 // each other in memory. By this division we make this characteristic
408 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000409 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000410 // that divides the offsets of all accesses to this base pointer.
411 if (DimsAccess == 1) {
412 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
413 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
414 }
415
Michael Kruse3b425ff2016-04-11 14:34:08 +0000416 // We currently do this only if we added at least one dimension, which means
417 // some dimension's indices have not been specified, an indicator that some
418 // index values have been added together.
419 // TODO: Investigate general usefulness; Effect on unit tests is to make index
420 // expressions more complicated.
421 if (DimsMissing)
422 wrapConstantDimensions();
423
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000424 if (!isAffine())
425 computeBoundsOnAccessRelation(ArrayElemSize);
426
Tobias Grosserd840fc72016-02-04 13:18:42 +0000427 // Introduce multi-element accesses in case the type loaded by this memory
428 // access is larger than the canonical element type of the array.
429 //
430 // An access ((float *)A)[i] to an array char *A is modeled as
431 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000432 if (ElemBytes > ArrayElemSize) {
433 assert(ElemBytes % ArrayElemSize == 0 &&
434 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000435 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000436 isl_set_universe(isl_space_copy(ArraySpace)),
437 isl_set_universe(isl_space_copy(ArraySpace)));
438 for (unsigned i = 0; i < DimsArray - 1; i++)
439 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
440
Tobias Grosserd840fc72016-02-04 13:18:42 +0000441 isl_constraint *C;
442 isl_local_space *LS;
443
444 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000445 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
446
447 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
448 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000449 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000450 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
451 Map = isl_map_add_constraint(Map, C);
452
453 C = isl_constraint_alloc_inequality(LS);
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 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
457 Map = isl_map_add_constraint(Map, C);
458 AccessRelation = isl_map_apply_range(AccessRelation, Map);
459 }
460
461 isl_space_free(ArraySpace);
462
Roman Gareev10595a12016-01-08 14:01:59 +0000463 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000464}
465
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000466const std::string
467MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
468 switch (RT) {
469 case MemoryAccess::RT_NONE:
470 llvm_unreachable("Requested a reduction operator string for a memory "
471 "access which isn't a reduction");
472 case MemoryAccess::RT_ADD:
473 return "+";
474 case MemoryAccess::RT_MUL:
475 return "*";
476 case MemoryAccess::RT_BOR:
477 return "|";
478 case MemoryAccess::RT_BXOR:
479 return "^";
480 case MemoryAccess::RT_BAND:
481 return "&";
482 }
483 llvm_unreachable("Unknown reduction type");
484 return "";
485}
486
Tobias Grosserc80d6972016-09-02 06:33:33 +0000487/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000488static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
489 const Instruction *Load) {
490 if (!BinOp)
491 return MemoryAccess::RT_NONE;
492 switch (BinOp->getOpcode()) {
493 case Instruction::FAdd:
494 if (!BinOp->hasUnsafeAlgebra())
495 return MemoryAccess::RT_NONE;
496 // Fall through
497 case Instruction::Add:
498 return MemoryAccess::RT_ADD;
499 case Instruction::Or:
500 return MemoryAccess::RT_BOR;
501 case Instruction::Xor:
502 return MemoryAccess::RT_BXOR;
503 case Instruction::And:
504 return MemoryAccess::RT_BAND;
505 case Instruction::FMul:
506 if (!BinOp->hasUnsafeAlgebra())
507 return MemoryAccess::RT_NONE;
508 // Fall through
509 case Instruction::Mul:
510 if (DisableMultiplicativeReductions)
511 return MemoryAccess::RT_NONE;
512 return MemoryAccess::RT_MUL;
513 default:
514 return MemoryAccess::RT_NONE;
515 }
516}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000517
Tobias Grosser75805372011-04-29 06:27:02 +0000518MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000519 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000520 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000521 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000522 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000523}
524
Michael Kruse2fa35192016-09-01 19:53:31 +0000525const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000526 isl_id *ArrayId = getArrayId();
527 void *User = isl_id_get_user(ArrayId);
528 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
529 isl_id_free(ArrayId);
530 return SAI;
531}
532
Michael Kruse2fa35192016-09-01 19:53:31 +0000533const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
534 isl_id *ArrayId = getLatestArrayId();
535 void *User = isl_id_get_user(ArrayId);
536 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
537 isl_id_free(ArrayId);
538 return SAI;
539}
540
541__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000542 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
543}
544
Michael Kruse2fa35192016-09-01 19:53:31 +0000545__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
546 if (!hasNewAccessRelation())
547 return getOriginalArrayId();
548 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
549}
550
Tobias Grosserd840fc72016-02-04 13:18:42 +0000551__isl_give isl_map *MemoryAccess::getAddressFunction() const {
552 return isl_map_lexmin(getAccessRelation());
553}
554
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000555__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
556 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000557 isl_map *Schedule, *ScheduledAccRel;
558 isl_union_set *UDomain;
559
560 UDomain = isl_union_set_from_set(getStatement()->getDomain());
561 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
562 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000563 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000564 return isl_pw_multi_aff_from_map(ScheduledAccRel);
565}
566
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000567__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000568 return isl_map_copy(AccessRelation);
569}
570
Johannes Doerferta99130f2014-10-13 12:58:03 +0000571std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000572 return stringFromIslObj(AccessRelation);
573}
574
Johannes Doerferta99130f2014-10-13 12:58:03 +0000575__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000576 return isl_map_get_space(AccessRelation);
577}
578
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000579__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000580 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000581}
582
Tobias Grosser6f730082015-09-05 07:46:47 +0000583std::string MemoryAccess::getNewAccessRelationStr() const {
584 return stringFromIslObj(NewAccessRelation);
585}
586
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000587__isl_give isl_basic_map *
588MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000589 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000590 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000591
Tobias Grosser084d8f72012-05-29 09:29:44 +0000592 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000593 isl_basic_set_universe(Statement->getDomainSpace()),
594 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000595}
596
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000597// Formalize no out-of-bound access assumption
598//
599// When delinearizing array accesses we optimistically assume that the
600// delinearized accesses do not access out of bound locations (the subscript
601// expression of each array evaluates for each statement instance that is
602// executed to a value that is larger than zero and strictly smaller than the
603// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000604// dimension for which we do not need to assume any upper bound. At this point
605// we formalize this assumption to ensure that at code generation time the
606// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000607//
608// To find the set of constraints necessary to avoid out of bound accesses, we
609// first build the set of data locations that are not within array bounds. We
610// then apply the reverse access relation to obtain the set of iterations that
611// may contain invalid accesses and reduce this set of iterations to the ones
612// that are actually executed by intersecting them with the domain of the
613// statement. If we now project out all loop dimensions, we obtain a set of
614// parameters that may cause statement instances to be executed that may
615// possibly yield out of bound memory accesses. The complement of these
616// constraints is the set of constraints that needs to be assumed to ensure such
617// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000618void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000619 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000620 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000621 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000622 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000623 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
624 isl_pw_aff *Var =
625 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
626 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
627
628 isl_set *DimOutside;
629
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000630 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000631 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000632 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
633 isl_space_dim(Space, isl_dim_set));
634 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
635 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000636
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000637 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000638
639 Outside = isl_set_union(Outside, DimOutside);
640 }
641
642 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
643 Outside = isl_set_intersect(Outside, Statement->getDomain());
644 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000645
646 // Remove divs to avoid the construction of overly complicated assumptions.
647 // Doing so increases the set of parameter combinations that are assumed to
648 // not appear. This is always save, but may make the resulting run-time check
649 // bail out more often than strictly necessary.
650 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000651 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000652 const auto &Loc = getAccessInstruction()
653 ? getAccessInstruction()->getDebugLoc()
654 : DebugLoc();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000655 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
656 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000657 isl_space_free(Space);
658}
659
Johannes Doerfertcea61932016-02-21 19:13:19 +0000660void MemoryAccess::buildMemIntrinsicAccessRelation() {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000661 assert(isa<MemIntrinsic>(getAccessInstruction()));
Roman Gareevf5aff702016-09-12 17:08:31 +0000662 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000663
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000664 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000665 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000666
667 isl_map *LengthMap;
668 if (Subscripts[1] == nullptr) {
669 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
670 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000671 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000672 LengthMap = isl_map_from_pw_aff(LengthPWA);
673 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
674 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
675 }
676 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
677 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000678 SubscriptMap =
679 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000680 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
681 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
682 getStatement()->getDomainId());
683}
684
Johannes Doerferte7044942015-02-24 11:58:30 +0000685void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
686 ScalarEvolution *SE = Statement->getParent()->getSE();
687
Johannes Doerfertcea61932016-02-21 19:13:19 +0000688 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000689 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000690 return;
691
692 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000693 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
694 return;
695
696 auto *PtrSCEV = SE->getSCEV(Ptr);
697 if (isa<SCEVCouldNotCompute>(PtrSCEV))
698 return;
699
700 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
701 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
702 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
703
704 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
705 if (Range.isFullSet())
706 return;
707
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000708 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000709 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000710 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000711 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000712 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000713
714 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000715 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000716
717 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
718 AccessRange =
719 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
720 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
721}
722
Michael Krusee2bccbb2015-09-18 19:59:43 +0000723__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000724 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000725 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000726
727 for (int i = Size - 2; i >= 0; --i) {
728 isl_space *Space;
729 isl_map *MapOne, *MapTwo;
Roman Gareevf5aff702016-09-12 17:08:31 +0000730 isl_pw_aff *DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000731
732 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
733 isl_pw_aff_free(DimSize);
734 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
735
736 Space = isl_map_get_space(AccessRelation);
737 Space = isl_space_map_from_set(isl_space_range(Space));
738 Space = isl_space_align_params(Space, SpaceSize);
739
740 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
741 isl_id_free(ParamId);
742
743 MapOne = isl_map_universe(isl_space_copy(Space));
744 for (int j = 0; j < Size; ++j)
745 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
746 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
747
748 MapTwo = isl_map_universe(isl_space_copy(Space));
749 for (int j = 0; j < Size; ++j)
750 if (j < i || j > i + 1)
751 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
752
753 isl_local_space *LS = isl_local_space_from_space(Space);
754 isl_constraint *C;
755 C = isl_equality_alloc(isl_local_space_copy(LS));
756 C = isl_constraint_set_constant_si(C, -1);
757 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
758 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
759 MapTwo = isl_map_add_constraint(MapTwo, C);
760 C = isl_equality_alloc(LS);
761 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
762 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
763 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
764 MapTwo = isl_map_add_constraint(MapTwo, C);
765 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
766
767 MapOne = isl_map_union(MapOne, MapTwo);
768 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
769 }
770 return AccessRelation;
771}
772
Tobias Grosserc80d6972016-09-02 06:33:33 +0000773/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000774static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000775 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000776 if (Size == 1)
777 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000778
779 // Only one factor needs to be divisible.
780 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
781 for (auto *FactorExpr : MulExpr->operands())
782 if (isDivisible(FactorExpr, Size, SE))
783 return true;
784 return false;
785 }
786
787 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
788 // to be divisble.
789 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
790 for (auto *OpExpr : NAryExpr->operands())
791 if (!isDivisible(OpExpr, Size, SE))
792 return false;
793 return true;
794 }
795
796 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
797 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
798 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
799 return MulSCEV == Expr;
800}
801
Michael Krusee2bccbb2015-09-18 19:59:43 +0000802void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
803 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000804
Johannes Doerfert85676e32016-04-23 14:32:34 +0000805 // Initialize the invalid domain which describes all iterations for which the
806 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000807 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
808 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
809 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000810
Michael Krusee2bccbb2015-09-18 19:59:43 +0000811 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000812 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000813
Michael Krusee2bccbb2015-09-18 19:59:43 +0000814 if (!isAffine()) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000815 if (isa<MemIntrinsic>(getAccessInstruction()))
816 buildMemIntrinsicAccessRelation();
817
Tobias Grosser4f967492013-06-23 05:21:18 +0000818 // We overapproximate non-affine accesses with a possible access to the
819 // whole array. For read accesses it does not make a difference, if an
820 // access must or may happen. However, for write accesses it is important to
821 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000822 if (!AccessRelation)
823 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
824
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000825 AccessRelation =
826 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000827 return;
828 }
829
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000830 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000831 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000832
Michael Krusee2bccbb2015-09-18 19:59:43 +0000833 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000834 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000835 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000836 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000837 }
838
Roman Gareevf5aff702016-09-12 17:08:31 +0000839 if (Sizes.size() >= 2 && !isa<SCEVConstant>(Sizes[1]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000840 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000841
Tobias Grosser79baa212014-04-10 08:38:02 +0000842 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000843 AccessRelation = isl_map_set_tuple_id(
844 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000845 AccessRelation =
846 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
847
Tobias Grosseraa660a92015-03-30 00:07:50 +0000848 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000849 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000850}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000851
Michael Krusecac948e2015-10-02 13:53:07 +0000852MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000853 AccessType AccType, Value *BaseAddress,
854 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000855 ArrayRef<const SCEV *> Subscripts,
856 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000857 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000858 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Johannes Doerfert85676e32016-04-23 14:32:34 +0000859 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
860 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()),
861 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000862 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000863 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000864 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000865 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000866
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000867 std::string IdName =
868 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000869 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
870}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000871
Roman Gareevb3224ad2016-09-14 06:26:09 +0000872MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
873 __isl_take isl_map *AccRel)
874 : Kind(ScopArrayInfo::MemoryKind::MK_Array), AccType(AccType),
875 RedType(RT_NONE), Statement(Stmt), InvalidDomain(nullptr),
876 AccessInstruction(nullptr), IsAffine(true), AccessRelation(nullptr),
877 NewAccessRelation(AccRel) {
878 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
879 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
880 Sizes.push_back(nullptr);
881 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
882 Sizes.push_back(SAI->getDimensionSize(i));
883 ElementType = SAI->getElementType();
884 BaseAddr = SAI->getBasePtr();
885 BaseName = SAI->getName();
886 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
887 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
888
889 std::string IdName =
890 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
891 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
892}
893
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000894void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +0000895 auto *Ctx = Statement->getParent()->getContext();
896 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
897 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +0000898}
899
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000900const std::string MemoryAccess::getReductionOperatorStr() const {
901 return MemoryAccess::getReductionOperatorStr(getReductionType());
902}
903
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000904__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
905
Johannes Doerfertf6183392014-07-01 20:52:51 +0000906raw_ostream &polly::operator<<(raw_ostream &OS,
907 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000908 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000909 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000910 else
911 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000912 return OS;
913}
914
Tobias Grosser75805372011-04-29 06:27:02 +0000915void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000916 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000917 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000918 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000919 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000920 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000921 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000922 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000923 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000924 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000925 break;
926 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000927 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000928 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000929 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000930 if (hasNewAccessRelation())
931 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000932}
933
Tobias Grosser74394f02013-01-14 22:40:23 +0000934void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000935
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000936__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
937 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000938 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +0000939 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
940 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
941 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000942 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000943}
944
Tobias Grosser75805372011-04-29 06:27:02 +0000945// Create a map in the size of the provided set domain, that maps from the
946// one element of the provided set domain to another element of the provided
947// set domain.
948// The mapping is limited to all points that are equal in all but the last
949// dimension and for which the last dimension of the input is strict smaller
950// than the last dimension of the output.
951//
952// getEqualAndLarger(set[i0, i1, ..., iX]):
953//
954// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
955// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
956//
Tobias Grosser2a526fe2016-09-08 11:18:56 +0000957static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000958 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000959 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000960 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000961
962 // Set all but the last dimension to be equal for the input and output
963 //
964 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
965 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000966 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000967 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000968
969 // Set the last dimension of the input to be strict smaller than the
970 // last dimension of the output.
971 //
972 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000973 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
974 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000975 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000976}
977
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000978__isl_give isl_set *
979MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000980 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000981 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000982 isl_space *Space = isl_space_range(isl_map_get_space(S));
983 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000984
Sebastian Popa00a0292012-12-18 07:46:06 +0000985 S = isl_map_reverse(S);
986 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000987
Sebastian Popa00a0292012-12-18 07:46:06 +0000988 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
989 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
990 NextScatt = isl_map_apply_domain(NextScatt, S);
991 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000992
Sebastian Popa00a0292012-12-18 07:46:06 +0000993 isl_set *Deltas = isl_map_deltas(NextScatt);
994 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000995}
996
Sebastian Popa00a0292012-12-18 07:46:06 +0000997bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000998 int StrideWidth) const {
999 isl_set *Stride, *StrideX;
1000 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001001
Sebastian Popa00a0292012-12-18 07:46:06 +00001002 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001003 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001004 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1005 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1006 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1007 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001008 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001009
Tobias Grosser28dd4862012-01-24 16:42:16 +00001010 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001011 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001012
Tobias Grosser28dd4862012-01-24 16:42:16 +00001013 return IsStrideX;
1014}
1015
Michael Krused56b90a2016-09-01 09:03:27 +00001016bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001017 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001018}
1019
Michael Krused56b90a2016-09-01 09:03:27 +00001020bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001021 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001022}
1023
Michael Krused56b90a2016-09-01 09:03:27 +00001024void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001025 assert(NewAccess);
1026
1027#ifndef NDEBUG
1028 // Check domain space compatibility.
1029 auto *NewSpace = isl_map_get_space(NewAccess);
1030 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1031 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1032 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1033 isl_space_free(NewDomainSpace);
1034 isl_space_free(OriginalDomainSpace);
1035
1036 // Check whether there is an access for every statement instance.
1037 auto *StmtDomain = getStatement()->getDomain();
1038 StmtDomain = isl_set_intersect_params(
1039 StmtDomain, getStatement()->getParent()->getContext());
1040 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1041 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1042 "Partial accesses not supported");
1043 isl_set_free(NewDomain);
1044 isl_set_free(StmtDomain);
1045
1046 // Check whether access dimensions correspond to number of dimensions of the
1047 // accesses array.
1048 auto *NewAccessSpace = isl_space_range(NewSpace);
1049 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1050 "Must specify the array that is accessed");
1051 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1052 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1053 assert(SAI && "Must set a ScopArrayInfo");
1054 assert(!SAI->getBasePtrOriginSAI() &&
1055 "Indirect array not supported by codegen");
1056 auto Dims = SAI->getNumberOfDimensions();
1057 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1058 "Access dims must match array dims");
1059 isl_space_free(NewAccessSpace);
1060 isl_id_free(NewArrayId);
1061#endif
1062
Tobias Grosser166c4222015-09-05 07:46:40 +00001063 isl_map_free(NewAccessRelation);
1064 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001065}
Tobias Grosser75805372011-04-29 06:27:02 +00001066
1067//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001068
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001069__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001070 isl_set *Domain = getDomain();
1071 if (isl_set_is_empty(Domain)) {
1072 isl_set_free(Domain);
1073 return isl_map_from_aff(
1074 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1075 }
1076 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001077 if (!Schedule) {
1078 isl_set_free(Domain);
1079 return nullptr;
1080 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001081 Schedule = isl_union_map_intersect_domain(
1082 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1083 if (isl_union_map_is_empty(Schedule)) {
1084 isl_set_free(Domain);
1085 isl_union_map_free(Schedule);
1086 return isl_map_from_aff(
1087 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1088 }
1089 auto *M = isl_map_from_union_map(Schedule);
1090 M = isl_map_coalesce(M);
1091 M = isl_map_gist_domain(M, Domain);
1092 M = isl_map_coalesce(M);
1093 return M;
1094}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001095
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001096__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1097 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001098 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1099 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001100}
1101
Tobias Grosser37eb4222014-02-20 21:43:54 +00001102void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1103 assert(isl_set_is_subset(NewDomain, Domain) &&
1104 "New domain is not a subset of old domain!");
1105 isl_set_free(Domain);
1106 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001107}
1108
Michael Krusecac948e2015-10-02 13:53:07 +00001109void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001110 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001111 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001112 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001113
Tobias Grossera535dff2015-12-13 19:59:01 +00001114 ScopArrayInfo::MemoryKind Ty;
1115 if (Access->isPHIKind())
1116 Ty = ScopArrayInfo::MK_PHI;
1117 else if (Access->isExitPHIKind())
1118 Ty = ScopArrayInfo::MK_ExitPHI;
1119 else if (Access->isValueKind())
1120 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001121 else
Tobias Grossera535dff2015-12-13 19:59:01 +00001122 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001123
Johannes Doerfertadeab372016-02-07 13:57:32 +00001124 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1125 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001126 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001127 }
1128}
1129
Michael Krusecac948e2015-10-02 13:53:07 +00001130void ScopStmt::addAccess(MemoryAccess *Access) {
1131 Instruction *AccessInst = Access->getAccessInstruction();
1132
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001133 if (Access->isArrayKind()) {
1134 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1135 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001136 } else if (Access->isValueKind() && Access->isWrite()) {
1137 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001138 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001139 assert(!ValueWrites.lookup(AccessVal));
1140
1141 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001142 } else if (Access->isValueKind() && Access->isRead()) {
1143 Value *AccessVal = Access->getAccessValue();
1144 assert(!ValueReads.lookup(AccessVal));
1145
1146 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001147 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1148 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1149 assert(!PHIWrites.lookup(PHI));
1150
1151 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001152 }
1153
1154 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001155}
1156
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001157void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001158 for (MemoryAccess *MA : *this)
1159 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001160
Johannes Doerferta60ad842016-05-10 12:18:22 +00001161 auto *Ctx = Parent.getContext();
1162 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1163 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001164}
1165
Tobias Grosserc80d6972016-09-02 06:33:33 +00001166/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001167static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1168 void *User) {
1169 isl_set **BoundedParts = static_cast<isl_set **>(User);
1170 if (isl_basic_set_is_bounded(BSet))
1171 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1172 else
1173 isl_basic_set_free(BSet);
1174 return isl_stat_ok;
1175}
1176
Tobias Grosserc80d6972016-09-02 06:33:33 +00001177/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001178static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1179 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1180 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1181 isl_set_free(S);
1182 return BoundedParts;
1183}
1184
Tobias Grosserc80d6972016-09-02 06:33:33 +00001185/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001186///
1187/// @returns A separation of @p S into first an unbounded then a bounded subset,
1188/// both with regards to the dimension @p Dim.
1189static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1190partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1191
1192 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001193 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001194
1195 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001196 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001197
1198 // Remove dimensions that are greater than Dim as they are not interesting.
1199 assert(NumDimsS >= Dim + 1);
1200 OnlyDimS =
1201 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1202
1203 // Create artificial parametric upper bounds for dimensions smaller than Dim
1204 // as we are not interested in them.
1205 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1206 for (unsigned u = 0; u < Dim; u++) {
1207 isl_constraint *C = isl_inequality_alloc(
1208 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1209 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1210 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1211 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1212 }
1213
1214 // Collect all bounded parts of OnlyDimS.
1215 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1216
1217 // Create the dimensions greater than Dim again.
1218 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1219 NumDimsS - Dim - 1);
1220
1221 // Remove the artificial upper bound parameters again.
1222 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1223
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001224 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001225 return std::make_pair(UnboundedParts, BoundedParts);
1226}
1227
Tobias Grosserc80d6972016-09-02 06:33:33 +00001228/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001229static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1230 __isl_take isl_set *To) {
1231 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1232 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1233 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1234 }
1235 return To;
1236}
1237
Tobias Grosserc80d6972016-09-02 06:33:33 +00001238/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001239static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001240 __isl_take isl_pw_aff *L,
1241 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001242 switch (Pred) {
1243 case ICmpInst::ICMP_EQ:
1244 return isl_pw_aff_eq_set(L, R);
1245 case ICmpInst::ICMP_NE:
1246 return isl_pw_aff_ne_set(L, R);
1247 case ICmpInst::ICMP_SLT:
1248 return isl_pw_aff_lt_set(L, R);
1249 case ICmpInst::ICMP_SLE:
1250 return isl_pw_aff_le_set(L, R);
1251 case ICmpInst::ICMP_SGT:
1252 return isl_pw_aff_gt_set(L, R);
1253 case ICmpInst::ICMP_SGE:
1254 return isl_pw_aff_ge_set(L, R);
1255 case ICmpInst::ICMP_ULT:
1256 return isl_pw_aff_lt_set(L, R);
1257 case ICmpInst::ICMP_UGT:
1258 return isl_pw_aff_gt_set(L, R);
1259 case ICmpInst::ICMP_ULE:
1260 return isl_pw_aff_le_set(L, R);
1261 case ICmpInst::ICMP_UGE:
1262 return isl_pw_aff_ge_set(L, R);
1263 default:
1264 llvm_unreachable("Non integer predicate not supported");
1265 }
1266}
1267
Tobias Grosserc80d6972016-09-02 06:33:33 +00001268/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001269///
1270/// Helper function that will make sure the dimensions of the result have the
1271/// same isl_id's as the @p Domain.
1272static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1273 __isl_take isl_pw_aff *L,
1274 __isl_take isl_pw_aff *R,
1275 __isl_keep isl_set *Domain) {
1276 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1277 return setDimensionIds(Domain, ConsequenceCondSet);
1278}
1279
Tobias Grosserc80d6972016-09-02 06:33:33 +00001280/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001281///
1282/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001283/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1284/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001285static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001286buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1287 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001288 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1289
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001290 Value *Condition = getConditionFromTerminator(SI);
1291 assert(Condition && "No condition for switch");
1292
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001293 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001294 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001295 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001296 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001297
1298 unsigned NumSuccessors = SI->getNumSuccessors();
1299 ConditionSets.resize(NumSuccessors);
1300 for (auto &Case : SI->cases()) {
1301 unsigned Idx = Case.getSuccessorIndex();
1302 ConstantInt *CaseValue = Case.getCaseValue();
1303
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001304 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001305 isl_set *CaseConditionSet =
1306 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1307 ConditionSets[Idx] = isl_set_coalesce(
1308 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1309 }
1310
1311 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1312 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1313 for (unsigned u = 2; u < NumSuccessors; u++)
1314 ConditionSetUnion =
1315 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1316 ConditionSets[0] = setDimensionIds(
1317 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1318
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001319 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001320
1321 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001322}
1323
Tobias Grosserc80d6972016-09-02 06:33:33 +00001324/// Build the conditions sets for the branch condition @p Condition in
1325/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001326///
1327/// This will fill @p ConditionSets with the conditions under which control
1328/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001329/// have as many elements as @p TI has successors. If @p TI is nullptr the
1330/// context under which @p Condition is true/false will be returned as the
1331/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001332static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001333buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1334 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001335 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1336
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001337 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001338 isl_set *ConsequenceCondSet = nullptr;
1339 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1340 if (CCond->isZero())
1341 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1342 else
1343 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1344 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1345 auto Opcode = BinOp->getOpcode();
1346 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1347
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001348 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1349 ConditionSets) &&
1350 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1351 ConditionSets);
1352 if (!Valid) {
1353 while (!ConditionSets.empty())
1354 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001355 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001356 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001357
1358 isl_set_free(ConditionSets.pop_back_val());
1359 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1360 isl_set_free(ConditionSets.pop_back_val());
1361 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1362
1363 if (Opcode == Instruction::And)
1364 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1365 else
1366 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1367 } else {
1368 auto *ICond = dyn_cast<ICmpInst>(Condition);
1369 assert(ICond &&
1370 "Condition of exiting branch was neither constant nor ICmp!");
1371
1372 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001373 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001374 // For unsigned comparisons we assumed the signed bit of neither operand
1375 // to be set. The comparison is equal to a signed comparison under this
1376 // assumption.
1377 bool NonNeg = ICond->isUnsigned();
1378 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1379 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001380 ConsequenceCondSet =
1381 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1382 }
1383
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001384 // If no terminator was given we are only looking for parameter constraints
1385 // under which @p Condition is true/false.
1386 if (!TI)
1387 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001388 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001389 ConsequenceCondSet = isl_set_coalesce(
1390 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001391
Johannes Doerfertb2885792016-04-26 09:20:41 +00001392 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001393 bool TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001394 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001395
Michael Krusef7a4a942016-05-02 12:25:36 +00001396 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001397 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1398 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001399 TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001400 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001401 }
1402
Michael Krusef7a4a942016-05-02 12:25:36 +00001403 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001404 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001405 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001406 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001407 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001408 }
1409
1410 ConditionSets.push_back(ConsequenceCondSet);
1411 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001412
1413 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001414}
1415
Tobias Grosserc80d6972016-09-02 06:33:33 +00001416/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001417///
1418/// This will fill @p ConditionSets with the conditions under which control
1419/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1420/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001421static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001422buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001423 __isl_keep isl_set *Domain,
1424 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1425
1426 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001427 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001428
1429 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1430
1431 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001432 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001433 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001434 }
1435
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001436 Value *Condition = getConditionFromTerminator(TI);
1437 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001438
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001439 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001440}
1441
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001442void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001443 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001444
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001445 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001446 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001447}
1448
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001449void ScopStmt::collectSurroundingLoops() {
1450 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1451 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1452 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1453 isl_id_free(DimId);
1454 }
1455}
1456
Michael Kruse9d080092015-09-11 21:41:48 +00001457ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerferta3519512016-04-23 13:02:23 +00001458 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1459 R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001460
Tobias Grosser16c44032015-07-09 07:31:45 +00001461 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001462}
1463
Michael Kruse9d080092015-09-11 21:41:48 +00001464ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerferta3519512016-04-23 13:02:23 +00001465 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1466 R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001467
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001468 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001469}
1470
Roman Gareevb3224ad2016-09-14 06:26:09 +00001471ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1472 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1473 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1474 R(nullptr), Build(nullptr) {
1475 BaseName = getIslCompatibleName("CopyStmt_", "",
1476 std::to_string(parent.getCopyStmtsNum()));
1477 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1478 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1479 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1480 auto *Access =
1481 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1482 parent.addAccessFunction(Access);
1483 addAccess(Access);
1484 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1485 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1486 parent.addAccessFunction(Access);
1487 addAccess(Access);
1488}
1489
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001490void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001491 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001492
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001493 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001494 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001495 buildAccessRelations();
1496
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001497 if (DetectReductions)
1498 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001499}
1500
Tobias Grosserc80d6972016-09-02 06:33:33 +00001501/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001502///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001503/// Check if the stored value for @p StoreMA is a binary operator with one or
1504/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001505/// used only once (by @p StoreMA) and its load operands are also used only
1506/// once, we have found a possible reduction chain. It starts at an operand
1507/// load and includes the binary operator and @p StoreMA.
1508///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001509/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001510/// escape this block or into any other store except @p StoreMA.
1511void ScopStmt::collectCandiateReductionLoads(
1512 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1513 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1514 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001515 return;
1516
1517 // Skip if there is not one binary operator between the load and the store
1518 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001519 if (!BinOp)
1520 return;
1521
1522 // Skip if the binary operators has multiple uses
1523 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001524 return;
1525
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001526 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001527 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1528 return;
1529
Johannes Doerfert9890a052014-07-01 00:32:29 +00001530 // Skip if the binary operator is outside the current SCoP
1531 if (BinOp->getParent() != Store->getParent())
1532 return;
1533
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001534 // Skip if it is a multiplicative reduction and we disabled them
1535 if (DisableMultiplicativeReductions &&
1536 (BinOp->getOpcode() == Instruction::Mul ||
1537 BinOp->getOpcode() == Instruction::FMul))
1538 return;
1539
Johannes Doerferte58a0122014-06-27 20:31:28 +00001540 // Check the binary operator operands for a candidate load
1541 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1542 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1543 if (!PossibleLoad0 && !PossibleLoad1)
1544 return;
1545
1546 // A load is only a candidate if it cannot escape (thus has only this use)
1547 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001548 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001549 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001550 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001551 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001552 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001553}
1554
Tobias Grosserc80d6972016-09-02 06:33:33 +00001555/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001556///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001557/// Iterate over all store memory accesses and check for valid binary reduction
1558/// like chains. For all candidates we check if they have the same base address
1559/// and there are no other accesses which overlap with them. The base address
1560/// check rules out impossible reductions candidates early. The overlap check,
1561/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001562/// guarantees that none of the intermediate results will escape during
1563/// execution of the loop nest. We basically check here that no other memory
1564/// access can access the same memory as the potential reduction.
1565void ScopStmt::checkForReductions() {
1566 SmallVector<MemoryAccess *, 2> Loads;
1567 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1568
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001569 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001570 // stores and collecting possible reduction loads.
1571 for (MemoryAccess *StoreMA : MemAccs) {
1572 if (StoreMA->isRead())
1573 continue;
1574
1575 Loads.clear();
1576 collectCandiateReductionLoads(StoreMA, Loads);
1577 for (MemoryAccess *LoadMA : Loads)
1578 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1579 }
1580
1581 // Then check each possible candidate pair.
1582 for (const auto &CandidatePair : Candidates) {
1583 bool Valid = true;
1584 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1585 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1586
1587 // Skip those with obviously unequal base addresses.
1588 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1589 isl_map_free(LoadAccs);
1590 isl_map_free(StoreAccs);
1591 continue;
1592 }
1593
1594 // And check if the remaining for overlap with other memory accesses.
1595 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1596 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1597 isl_set *AllAccs = isl_map_range(AllAccsRel);
1598
1599 for (MemoryAccess *MA : MemAccs) {
1600 if (MA == CandidatePair.first || MA == CandidatePair.second)
1601 continue;
1602
1603 isl_map *AccRel =
1604 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1605 isl_set *Accs = isl_map_range(AccRel);
1606
Tobias Grosser55a7af72016-09-08 14:08:07 +00001607 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001608 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1609 Valid = Valid && isl_set_is_empty(OverlapAccs);
1610 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001611 } else {
1612 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001613 }
1614 }
1615
1616 isl_set_free(AllAccs);
1617 if (!Valid)
1618 continue;
1619
Johannes Doerfertf6183392014-07-01 20:52:51 +00001620 const LoadInst *Load =
1621 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1622 MemoryAccess::ReductionType RT =
1623 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1624
Johannes Doerferte58a0122014-06-27 20:31:28 +00001625 // If no overlapping access was found we mark the load and store as
1626 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001627 CandidatePair.first->markAsReductionLike(RT);
1628 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001629 }
Tobias Grosser75805372011-04-29 06:27:02 +00001630}
1631
Tobias Grosser74394f02013-01-14 22:40:23 +00001632std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001633
Tobias Grosser54839312015-04-21 11:37:25 +00001634std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001635 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001636 if (!S)
1637 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001638 auto Str = stringFromIslObj(S);
1639 isl_map_free(S);
1640 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001641}
1642
Johannes Doerferta3519512016-04-23 13:02:23 +00001643void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1644 isl_set_free(InvalidDomain);
1645 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001646}
1647
Michael Kruse375cb5f2016-02-24 22:08:24 +00001648BasicBlock *ScopStmt::getEntryBlock() const {
1649 if (isBlockStmt())
1650 return getBasicBlock();
1651 return getRegion()->getEntry();
1652}
1653
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001654unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001655
Tobias Grosser75805372011-04-29 06:27:02 +00001656const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1657
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001658Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001659 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001660}
1661
Tobias Grosser74394f02013-01-14 22:40:23 +00001662isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001663
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001664__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001665
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001666__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001667 return isl_set_get_space(Domain);
1668}
1669
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001670__isl_give isl_id *ScopStmt::getDomainId() const {
1671 return isl_set_get_tuple_id(Domain);
1672}
Tobias Grossercd95b772012-08-30 11:49:38 +00001673
Johannes Doerfert7c013572016-04-12 09:57:34 +00001674ScopStmt::~ScopStmt() {
1675 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001676 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001677}
Tobias Grosser75805372011-04-29 06:27:02 +00001678
1679void ScopStmt::print(raw_ostream &OS) const {
1680 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001681 OS.indent(12) << "Domain :=\n";
1682
1683 if (Domain) {
1684 OS.indent(16) << getDomainStr() << ";\n";
1685 } else
1686 OS.indent(16) << "n/a\n";
1687
Tobias Grosser54839312015-04-21 11:37:25 +00001688 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001689
1690 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001691 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001692 } else
1693 OS.indent(16) << "n/a\n";
1694
Tobias Grosser083d3d32014-06-28 08:59:45 +00001695 for (MemoryAccess *Access : MemAccs)
1696 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001697}
1698
1699void ScopStmt::dump() const { print(dbgs()); }
1700
Michael Kruse10071822016-05-23 14:45:58 +00001701void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
1702 // Remove the memory accesses from this statement
1703 // together with all scalar accesses that were caused by it.
Michael Krusead28e5a2016-01-26 13:33:15 +00001704 // MK_Value READs have no access instruction, hence would not be removed by
1705 // this function. However, it is only used for invariant LoadInst accesses,
1706 // its arguments are always affine, hence synthesizable, and therefore there
1707 // are no MK_Value READ accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001708 auto Predicate = [&](MemoryAccess *Acc) {
1709 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1710 };
1711 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1712 MemAccs.end());
1713 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001714}
1715
Tobias Grosser75805372011-04-29 06:27:02 +00001716//===----------------------------------------------------------------------===//
1717/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001718
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001719void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001720 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1721 isl_set_free(Context);
1722 Context = NewContext;
1723}
1724
Tobias Grosserc80d6972016-09-02 06:33:33 +00001725/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001726struct SCEVSensitiveParameterRewriter
1727 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1728 ValueToValueMap &VMap;
1729 ScalarEvolution &SE;
1730
1731public:
1732 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1733 : VMap(VMap), SE(SE) {}
1734
1735 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1736 ValueToValueMap &VMap) {
1737 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1738 return SSPR.visit(E);
1739 }
1740
1741 const SCEV *visit(const SCEV *E) {
1742 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1743 }
1744
1745 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1746
1747 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1748 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1749 }
1750
1751 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1752 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1753 }
1754
1755 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1756 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1757 }
1758
1759 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1760 SmallVector<const SCEV *, 4> Operands;
1761 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1762 Operands.push_back(visit(E->getOperand(i)));
1763 return SE.getAddExpr(Operands);
1764 }
1765
1766 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1767 SmallVector<const SCEV *, 4> Operands;
1768 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1769 Operands.push_back(visit(E->getOperand(i)));
1770 return SE.getMulExpr(Operands);
1771 }
1772
1773 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1774 SmallVector<const SCEV *, 4> Operands;
1775 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1776 Operands.push_back(visit(E->getOperand(i)));
1777 return SE.getSMaxExpr(Operands);
1778 }
1779
1780 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1781 SmallVector<const SCEV *, 4> Operands;
1782 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1783 Operands.push_back(visit(E->getOperand(i)));
1784 return SE.getUMaxExpr(Operands);
1785 }
1786
1787 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1788 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1789 }
1790
1791 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1792 auto *Start = visit(E->getStart());
1793 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1794 visit(E->getStepRecurrence(SE)),
1795 E->getLoop(), SCEV::FlagAnyWrap);
1796 return SE.getAddExpr(Start, AddRec);
1797 }
1798
1799 const SCEV *visitUnknown(const SCEVUnknown *E) {
1800 if (auto *NewValue = VMap.lookup(E->getValue()))
1801 return SE.getUnknown(NewValue);
1802 return E;
1803 }
1804};
1805
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001806const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001807 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001808}
1809
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001810void Scop::createParameterId(const SCEV *Parameter) {
1811 assert(Parameters.count(Parameter));
1812 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001813
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001814 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001815
Tobias Grosser8f99c162011-11-15 11:38:55 +00001816 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1817 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001818
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001819 // If this parameter references a specific Value and this value has a name
1820 // we use this name as it is likely to be unique and more useful than just
1821 // a number.
1822 if (Val->hasName())
1823 ParameterName = Val->getName();
1824 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001825 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001826 if (LoadOrigin->hasName()) {
1827 ParameterName += "_loaded_from_";
1828 ParameterName +=
1829 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1830 }
1831 }
1832 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001833
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001834 ParameterName = getIslCompatibleName("", ParameterName, "");
1835
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001836 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1837 const_cast<void *>((const void *)Parameter));
1838 ParameterIds[Parameter] = Id;
1839}
1840
1841void Scop::addParams(const ParameterSetTy &NewParameters) {
1842 for (const SCEV *Parameter : NewParameters) {
1843 // Normalize the SCEV to get the representing element for an invariant load.
1844 Parameter = extractConstantFactor(Parameter, *SE).second;
1845 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1846
1847 if (Parameters.insert(Parameter))
1848 createParameterId(Parameter);
1849 }
1850}
1851
1852__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1853 // Normalize the SCEV to get the representing element for an invariant load.
1854 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1855 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001856}
Tobias Grosser75805372011-04-29 06:27:02 +00001857
Michael Krused56b90a2016-09-01 09:03:27 +00001858__isl_give isl_set *
1859Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001860 isl_set *DomainContext = isl_union_set_params(getDomains());
1861 return isl_set_intersect_params(C, DomainContext);
1862}
1863
Johannes Doerferte0b08072016-05-23 12:43:44 +00001864bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1865 return DT.dominates(BB, getEntry());
1866}
1867
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001868void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1869 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001870 auto &F = getFunction();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001871 for (auto &Assumption : AC.assumptions()) {
1872 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1873 if (!CI || CI->getNumArgOperands() != 1)
1874 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001875
Johannes Doerfert952b5302016-05-23 12:40:48 +00001876 bool InScop = contains(CI);
Johannes Doerferte0b08072016-05-23 12:43:44 +00001877 if (!InScop && !isDominatedBy(DT, CI->getParent()))
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001878 continue;
1879
Michael Kruse09eb4452016-03-03 22:10:47 +00001880 auto *L = LI.getLoopFor(CI->getParent());
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001881 auto *Val = CI->getArgOperand(0);
Johannes Doerfertf560b3d2016-04-25 13:33:07 +00001882 ParameterSetTy DetectedParams;
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001883 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001884 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1885 CI->getDebugLoc(),
1886 "Non-affine user assumption ignored.");
1887 continue;
1888 }
1889
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001890 // Collect all newly introduced parameters.
1891 ParameterSetTy NewParams;
1892 for (auto *Param : DetectedParams) {
1893 Param = extractConstantFactor(Param, *SE).second;
1894 Param = getRepresentingInvariantLoadSCEV(Param);
1895 if (Parameters.count(Param))
1896 continue;
1897 NewParams.insert(Param);
1898 }
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001899
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001900 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001901 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
1902 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
1903 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001904 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
1905 isl_set_free(Dom);
1906
1907 if (!Valid)
Johannes Doerfert297c7202016-05-10 13:06:42 +00001908 continue;
1909
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001910 isl_set *AssumptionCtx = nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001911 if (InScop) {
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001912 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
1913 isl_set_free(ConditionSets[0]);
1914 } else {
1915 AssumptionCtx = isl_set_complement(ConditionSets[1]);
1916 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
1917 }
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001918
1919 // Project out newly introduced parameters as they are not otherwise useful.
1920 if (!NewParams.empty()) {
1921 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
1922 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
1923 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
1924 isl_id_free(Id);
1925
1926 if (!NewParams.count(Param))
1927 continue;
1928
1929 AssumptionCtx =
1930 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
1931 }
1932 }
1933
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001934 emitOptimizationRemarkAnalysis(
1935 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1936 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1937 Context = isl_set_intersect(Context, AssumptionCtx);
1938 }
1939}
1940
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001941void Scop::addUserContext() {
1942 if (UserContextStr.empty())
1943 return;
1944
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001945 isl_set *UserContext =
1946 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001947 isl_space *Space = getParamSpace();
1948 if (isl_space_dim(Space, isl_dim_param) !=
1949 isl_set_dim(UserContext, isl_dim_param)) {
1950 auto SpaceStr = isl_space_to_str(Space);
1951 errs() << "Error: the context provided in -polly-context has not the same "
1952 << "number of dimensions than the computed context. Due to this "
1953 << "mismatch, the -polly-context option is ignored. Please provide "
1954 << "the context in the parameter space: " << SpaceStr << ".\n";
1955 free(SpaceStr);
1956 isl_set_free(UserContext);
1957 isl_space_free(Space);
1958 return;
1959 }
1960
1961 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001962 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1963 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001964
1965 if (strcmp(NameContext, NameUserContext) != 0) {
1966 auto SpaceStr = isl_space_to_str(Space);
1967 errs() << "Error: the name of dimension " << i
1968 << " provided in -polly-context "
1969 << "is '" << NameUserContext << "', but the name in the computed "
1970 << "context is '" << NameContext
1971 << "'. Due to this name mismatch, "
1972 << "the -polly-context option is ignored. Please provide "
1973 << "the context in the parameter space: " << SpaceStr << ".\n";
1974 free(SpaceStr);
1975 isl_set_free(UserContext);
1976 isl_space_free(Space);
1977 return;
1978 }
1979
1980 UserContext =
1981 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1982 isl_space_get_dim_id(Space, isl_dim_param, i));
1983 }
1984
1985 Context = isl_set_intersect(Context, UserContext);
1986 isl_space_free(Space);
1987}
1988
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001989void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001990 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001991
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001992 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001993 for (LoadInst *LInst : RIL) {
1994 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1995
Johannes Doerfert96e54712016-02-07 17:30:13 +00001996 Type *Ty = LInst->getType();
1997 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001998 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001999 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002000 continue;
2001 }
2002
2003 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002004 InvariantEquivClasses.emplace_back(
2005 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002006 }
2007}
2008
Tobias Grosser6be480c2011-11-08 15:41:13 +00002009void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002010 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002011 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002012 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002013 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002014}
2015
Tobias Grosser18daaca2012-05-22 10:47:27 +00002016void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002017 unsigned PDim = 0;
2018 for (auto *Parameter : Parameters) {
2019 ConstantRange SRange = SE->getSignedRange(Parameter);
2020 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002021 }
2022}
2023
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002024void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002025 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002026 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002027
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002028 unsigned PDim = 0;
2029 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002030 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002031 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002032 }
2033
2034 // Align the parameters of all data structures to the model.
2035 Context = isl_set_align_params(Context, Space);
2036
Johannes Doerferta60ad842016-05-10 12:18:22 +00002037 // As all parameters are known add bounds to them.
2038 addParameterBounds();
2039
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002040 for (ScopStmt &Stmt : *this)
2041 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002042
2043 // Simplify the schedule according to the context too.
2044 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002045}
2046
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002047static __isl_give isl_set *
2048simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2049 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002050 // If we modelt all blocks in the SCoP that have side effects we can simplify
2051 // the context with the constraints that are needed for anything to be
2052 // executed at all. However, if we have error blocks in the SCoP we already
2053 // assumed some parameter combinations cannot occure and removed them from the
2054 // domains, thus we cannot use the remaining domain to simplify the
2055 // assumptions.
2056 if (!S.hasErrorBlock()) {
2057 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2058 AssumptionContext =
2059 isl_set_gist_params(AssumptionContext, DomainParameters);
2060 }
2061
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002062 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2063 return AssumptionContext;
2064}
2065
2066void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002067 // The parameter constraints of the iteration domains give us a set of
2068 // constraints that need to hold for all cases where at least a single
2069 // statement iteration is executed in the whole scop. We now simplify the
2070 // assumed context under the assumption that such constraints hold and at
2071 // least a single statement iteration is executed. For cases where no
2072 // statement instances are executed, the assumptions we have taken about
2073 // the executed code do not matter and can be changed.
2074 //
2075 // WARNING: This only holds if the assumptions we have taken do not reduce
2076 // the set of statement instances that are executed. Otherwise we
2077 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002078 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002079 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002080 // performed. In such a case, modifying the run-time conditions and
2081 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002082 // to not be executed.
2083 //
2084 // Example:
2085 //
2086 // When delinearizing the following code:
2087 //
2088 // for (long i = 0; i < 100; i++)
2089 // for (long j = 0; j < m; j++)
2090 // A[i+p][j] = 1.0;
2091 //
2092 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002093 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002094 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002095 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002096 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002097}
2098
Tobias Grosserc80d6972016-09-02 06:33:33 +00002099/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002100static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002101 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2102 isl_pw_multi_aff *MinPMA, *MaxPMA;
2103 isl_pw_aff *LastDimAff;
2104 isl_aff *OneAff;
2105 unsigned Pos;
2106
Johannes Doerfert6296d952016-04-22 11:38:19 +00002107 Set = isl_set_remove_divs(Set);
2108
Michael Krusebc150122016-05-02 12:25:18 +00002109 if (isl_set_n_basic_set(Set) >= MaxDisjunctionsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002110 isl_set_free(Set);
2111 return isl_stat_error;
2112 }
2113
Johannes Doerfert9143d672014-09-27 11:02:39 +00002114 // Restrict the number of parameters involved in the access as the lexmin/
2115 // lexmax computation will take too long if this number is high.
2116 //
2117 // Experiments with a simple test case using an i7 4800MQ:
2118 //
2119 // #Parameters involved | Time (in sec)
2120 // 6 | 0.01
2121 // 7 | 0.04
2122 // 8 | 0.12
2123 // 9 | 0.40
2124 // 10 | 1.54
2125 // 11 | 6.78
2126 // 12 | 30.38
2127 //
2128 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2129 unsigned InvolvedParams = 0;
2130 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2131 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2132 InvolvedParams++;
2133
2134 if (InvolvedParams > RunTimeChecksMaxParameters) {
2135 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002136 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002137 }
2138 }
2139
Johannes Doerfertb164c792014-09-18 11:17:17 +00002140 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2141 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2142
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002143 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2144 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2145
Johannes Doerfertb164c792014-09-18 11:17:17 +00002146 // Adjust the last dimension of the maximal access by one as we want to
2147 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2148 // we test during code generation might now point after the end of the
2149 // allocated array but we will never dereference it anyway.
2150 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2151 "Assumed at least one output dimension");
2152 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2153 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2154 OneAff = isl_aff_zero_on_domain(
2155 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2156 OneAff = isl_aff_add_constant_si(OneAff, 1);
2157 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2158 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2159
2160 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2161
2162 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002163 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002164}
2165
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002166static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2167 isl_set *Domain = MA->getStatement()->getDomain();
2168 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2169 return isl_set_reset_tuple_id(Domain);
2170}
2171
Tobias Grosserc80d6972016-09-02 06:33:33 +00002172/// Wrapper function to calculate minimal/maximal accesses to each array.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002173static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002174 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002175 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002176
2177 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2178 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002179 Locations = isl_union_set_coalesce(Locations);
2180 Locations = isl_union_set_detect_equalities(Locations);
2181 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002182 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002183 isl_union_set_free(Locations);
2184 return Valid;
2185}
2186
Tobias Grosserc80d6972016-09-02 06:33:33 +00002187/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002188///
2189///{
2190
Tobias Grosserc80d6972016-09-02 06:33:33 +00002191/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002192static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2193 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2194 : RN->getNodeAs<BasicBlock>();
2195}
2196
Tobias Grosserc80d6972016-09-02 06:33:33 +00002197/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002198static inline BasicBlock *
2199getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002200 if (RN->isSubRegion()) {
2201 assert(idx == 0);
2202 return RN->getNodeAs<Region>()->getExit();
2203 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002204 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002205}
2206
Tobias Grosserc80d6972016-09-02 06:33:33 +00002207/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002208static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2209 if (!RN->isSubRegion())
2210 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2211
2212 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2213 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2214 while (L && NonAffineSubRegion->contains(L))
2215 L = L->getParentLoop();
2216 return L;
2217}
2218
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002219static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2220 if (!RN->isSubRegion())
2221 return 1;
2222
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002223 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002224 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002225}
2226
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002227static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2228 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002229 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002230 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002231 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002232 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002233 return true;
2234 return false;
2235}
2236
Johannes Doerfert96425c22015-08-30 21:13:53 +00002237///}
2238
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002239static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2240 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002241 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002242 isl_id *DimId =
2243 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2244 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2245}
2246
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002247__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002248 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002249}
2250
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002251__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002252 auto DIt = DomainMap.find(BB);
2253 if (DIt != DomainMap.end())
2254 return isl_set_copy(DIt->getSecond());
2255
2256 auto &RI = *R.getRegionInfo();
2257 auto *BBR = RI.getRegionFor(BB);
2258 while (BBR->getEntry() == BB)
2259 BBR = BBR->getParent();
2260 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002261}
2262
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002263bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002264
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002265 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002266 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002267 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2268 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002269 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002270
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002271 while (LD-- >= 0) {
2272 S = addDomainDimId(S, LD + 1, L);
2273 L = L->getParentLoop();
2274 }
2275
Johannes Doerferta3519512016-04-23 13:02:23 +00002276 // Initialize the invalid domain.
2277 auto *EntryStmt = getStmtFor(EntryBB);
2278 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2279
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002280 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002281
Johannes Doerfert432658d2016-01-26 11:01:41 +00002282 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002283 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002284
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002285 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002286 return false;
2287
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002288 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002289 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002290
2291 // Error blocks and blocks dominated by them have been assumed to never be
2292 // executed. Representing them in the Scop does not add any value. In fact,
2293 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002294 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002295 // will cause problems when building up a ScopStmt for them.
2296 // Furthermore, basic blocks dominated by error blocks may reference
2297 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002298 // can themselves not be constructed properly. To this end we will replace
2299 // the domains of error blocks and those only reachable via error blocks
2300 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002301 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002302 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002303 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002304 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002305
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002306 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002307}
2308
Michael Kruse586e5792016-07-08 12:38:28 +00002309// If the loop is nonaffine/boxed, return the first non-boxed surrounding loop
2310// for Polly. If the loop is affine, return the loop itself. Do not call
2311// `getSCEVAtScope()` on the result of `getFirstNonBoxedLoopFor()`, as we need
2312// to analyze the memory accesses of the nonaffine/boxed loops.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002313static Loop *getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI,
2314 const BoxedLoopsSetTy &BoxedLoops) {
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002315 auto *L = LI.getLoopFor(BB);
2316 while (BoxedLoops.count(L))
2317 L = L->getParentLoop();
2318 return L;
2319}
2320
Tobias Grosserc80d6972016-09-02 06:33:33 +00002321/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002322/// to be compatible to domains constructed for loop @p NewL.
2323///
2324/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2325/// edge from @p OldL to @p NewL.
2326static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2327 __isl_take isl_set *Dom,
2328 Loop *OldL, Loop *NewL) {
2329
2330 // If the loops are the same there is nothing to do.
2331 if (NewL == OldL)
2332 return Dom;
2333
2334 int OldDepth = S.getRelativeLoopDepth(OldL);
2335 int NewDepth = S.getRelativeLoopDepth(NewL);
2336 // If both loops are non-affine loops there is nothing to do.
2337 if (OldDepth == -1 && NewDepth == -1)
2338 return Dom;
2339
2340 // Distinguish three cases:
2341 // 1) The depth is the same but the loops are not.
2342 // => One loop was left one was entered.
2343 // 2) The depth increased from OldL to NewL.
2344 // => One loop was entered, none was left.
2345 // 3) The depth decreased from OldL to NewL.
2346 // => Loops were left were difference of the depths defines how many.
2347 if (OldDepth == NewDepth) {
2348 assert(OldL->getParentLoop() == NewL->getParentLoop());
2349 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2350 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2351 Dom = addDomainDimId(Dom, NewDepth, NewL);
2352 } else if (OldDepth < NewDepth) {
2353 assert(OldDepth + 1 == NewDepth);
2354 auto &R = S.getRegion();
2355 (void)R;
2356 assert(NewL->getParentLoop() == OldL ||
2357 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2358 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2359 Dom = addDomainDimId(Dom, NewDepth, NewL);
2360 } else {
2361 assert(OldDepth > NewDepth);
2362 int Diff = OldDepth - NewDepth;
2363 int NumDim = isl_set_n_dim(Dom);
2364 assert(NumDim >= Diff);
2365 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2366 }
2367
2368 return Dom;
2369}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002370
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002371bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2372 LoopInfo &LI) {
2373 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002374
2375 ReversePostOrderTraversal<Region *> RTraversal(R);
2376 for (auto *RN : RTraversal) {
2377
2378 // Recurse for affine subregions but go on for basic blocks and non-affine
2379 // subregions.
2380 if (RN->isSubRegion()) {
2381 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002382 if (!isNonAffineSubRegion(SubRegion)) {
2383 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002384 continue;
2385 }
2386 }
2387
2388 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2389 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002390 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002391 isl_set *&Domain = DomainMap[BB];
2392 assert(Domain && "Cannot propagate a nullptr");
2393
Johannes Doerferta3519512016-04-23 13:02:23 +00002394 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002395 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002396 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002397
Johannes Doerferta3519512016-04-23 13:02:23 +00002398 if (!IsInvalidBlock) {
2399 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002400 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002401 isl_set_free(InvalidDomain);
2402 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002403 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2404 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2405 AS_RESTRICTION);
2406 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002407 }
2408
Johannes Doerferta3519512016-04-23 13:02:23 +00002409 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002410 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002411 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002412 }
2413
Johannes Doerferta3519512016-04-23 13:02:23 +00002414 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002415 auto *TI = BB->getTerminator();
2416 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2417 for (unsigned u = 0; u < NumSuccs; u++) {
2418 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002419 auto *SuccStmt = getStmtFor(SuccBB);
2420
2421 // Skip successors outside the SCoP.
2422 if (!SuccStmt)
2423 continue;
2424
Johannes Doerferte4459a22016-04-25 13:34:50 +00002425 // Skip backedges.
2426 if (DT.dominates(SuccBB, BB))
2427 continue;
2428
Johannes Doerferta3519512016-04-23 13:02:23 +00002429 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2430 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2431 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2432 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2433 SuccInvalidDomain =
2434 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2435 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2436 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2437 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002438
Michael Krusebc150122016-05-02 12:25:18 +00002439 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002440 // In case this happens we will bail.
Michael Krusebc150122016-05-02 12:25:18 +00002441 if (NumConjucts < MaxDisjunctionsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002442 continue;
2443
Johannes Doerferta3519512016-04-23 13:02:23 +00002444 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002445 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002446 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002447 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002448
2449 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002450 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002451
2452 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002453}
2454
Johannes Doerfert642594a2016-04-04 07:57:39 +00002455void Scop::propagateDomainConstraintsToRegionExit(
2456 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002457 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002458
2459 // Check if the block @p BB is the entry of a region. If so we propagate it's
2460 // domain to the exit block of the region. Otherwise we are done.
2461 auto *RI = R.getRegionInfo();
2462 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2463 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002464 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002465 return;
2466
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002467 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002468 // Do not propagate the domain if there is a loop backedge inside the region
2469 // that would prevent the exit block from beeing executed.
2470 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002471 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002472 SmallVector<BasicBlock *, 4> LatchBBs;
2473 BBLoop->getLoopLatches(LatchBBs);
2474 for (auto *LatchBB : LatchBBs)
2475 if (BB != LatchBB && BBReg->contains(LatchBB))
2476 return;
2477 L = L->getParentLoop();
2478 }
2479
2480 auto *Domain = DomainMap[BB];
2481 assert(Domain && "Cannot propagate a nullptr");
2482
2483 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2484
2485 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2486 // adjust the domain before we can propagate it.
2487 auto *AdjustedDomain =
2488 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2489 auto *&ExitDomain = DomainMap[ExitBB];
2490
2491 // If the exit domain is not yet created we set it otherwise we "add" the
2492 // current domain.
2493 ExitDomain =
2494 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2495
Johannes Doerferta3519512016-04-23 13:02:23 +00002496 // Initialize the invalid domain.
2497 auto *ExitStmt = getStmtFor(ExitBB);
2498 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2499
Johannes Doerfert642594a2016-04-04 07:57:39 +00002500 FinishedExitBlocks.insert(ExitBB);
2501}
2502
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002503bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2504 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002505 // To create the domain for each block in R we iterate over all blocks and
2506 // subregions in R and propagate the conditions under which the current region
2507 // element is executed. To this end we iterate in reverse post order over R as
2508 // it ensures that we first visit all predecessors of a region node (either a
2509 // basic block or a subregion) before we visit the region node itself.
2510 // Initially, only the domain for the SCoP region entry block is set and from
2511 // there we propagate the current domain to all successors, however we add the
2512 // condition that the successor is actually executed next.
2513 // As we are only interested in non-loop carried constraints here we can
2514 // simply skip loop back edges.
2515
Johannes Doerfert642594a2016-04-04 07:57:39 +00002516 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002517 ReversePostOrderTraversal<Region *> RTraversal(R);
2518 for (auto *RN : RTraversal) {
2519
2520 // Recurse for affine subregions but go on for basic blocks and non-affine
2521 // subregions.
2522 if (RN->isSubRegion()) {
2523 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002524 if (!isNonAffineSubRegion(SubRegion)) {
2525 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002526 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002527 continue;
2528 }
2529 }
2530
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002531 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002532 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002533
Johannes Doerfert96425c22015-08-30 21:13:53 +00002534 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002535 TerminatorInst *TI = BB->getTerminator();
2536
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002537 if (isa<UnreachableInst>(TI))
2538 continue;
2539
Johannes Doerfertf5673802015-10-01 23:48:18 +00002540 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002541 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002542 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002543 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002544
Johannes Doerfert642594a2016-04-04 07:57:39 +00002545 auto *BBLoop = getRegionNodeLoop(RN, LI);
2546 // Propagate the domain from BB directly to blocks that have a superset
2547 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002548 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002549
2550 // If all successors of BB have been set a domain through the propagation
2551 // above we do not need to build condition sets but can just skip this
2552 // block. However, it is important to note that this is a local property
2553 // with regards to the region @p R. To this end FinishedExitBlocks is a
2554 // local variable.
2555 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2556 return FinishedExitBlocks.count(SuccBB);
2557 };
2558 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2559 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002560
2561 // Build the condition sets for the successor nodes of the current region
2562 // node. If it is a non-affine subregion we will always execute the single
2563 // exit node, hence the single entry node domain is the condition set. For
2564 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002565 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002566 if (RN->isSubRegion())
2567 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002568 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2569 ConditionSets))
2570 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002571
2572 // Now iterate over the successors and set their initial domain based on
2573 // their condition set. We skip back edges here and have to be careful when
2574 // we leave a loop not to keep constraints over a dimension that doesn't
2575 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002576 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002577 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002578 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002579 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002580
Johannes Doerfert535de032016-04-19 14:49:05 +00002581 auto *SuccStmt = getStmtFor(SuccBB);
2582 // Skip blocks outside the region.
2583 if (!SuccStmt) {
2584 isl_set_free(CondSet);
2585 continue;
2586 }
2587
Johannes Doerfert642594a2016-04-04 07:57:39 +00002588 // If we propagate the domain of some block to "SuccBB" we do not have to
2589 // adjust the domain.
2590 if (FinishedExitBlocks.count(SuccBB)) {
2591 isl_set_free(CondSet);
2592 continue;
2593 }
2594
Johannes Doerfert96425c22015-08-30 21:13:53 +00002595 // Skip back edges.
2596 if (DT.dominates(SuccBB, BB)) {
2597 isl_set_free(CondSet);
2598 continue;
2599 }
2600
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002601 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002602 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002603 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002604
2605 // Set the domain for the successor or merge it with an existing domain in
2606 // case there are multiple paths (without loop back edges) to the
2607 // successor block.
2608 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002609
Johannes Doerferta3519512016-04-23 13:02:23 +00002610 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002611 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002612 } else {
2613 // Initialize the invalid domain.
2614 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2615 SuccDomain = CondSet;
2616 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002617
Michael Krusebc150122016-05-02 12:25:18 +00002618 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002619 // In case this happens we will clean up and bail.
Michael Krusebc150122016-05-02 12:25:18 +00002620 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctionsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002621 continue;
2622
2623 invalidate(COMPLEXITY, DebugLoc());
2624 while (++u < ConditionSets.size())
2625 isl_set_free(ConditionSets[u]);
2626 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002627 }
2628 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002629
2630 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002631}
2632
Michael Krused56b90a2016-09-01 09:03:27 +00002633__isl_give isl_set *
2634Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2635 __isl_keep isl_set *Domain,
2636 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002637 // If @p BB is the ScopEntry we are done
2638 if (R.getEntry() == BB)
2639 return isl_set_universe(isl_set_get_space(Domain));
2640
2641 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002642 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002643
2644 // The region info of this function.
2645 auto &RI = *R.getRegionInfo();
2646
2647 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2648
2649 // A domain to collect all predecessor domains, thus all conditions under
2650 // which the block is executed. To this end we start with the empty domain.
2651 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2652
2653 // Set of regions of which the entry block domain has been propagated to BB.
2654 // all predecessors inside any of the regions can be skipped.
2655 SmallSet<Region *, 8> PropagatedRegions;
2656
2657 for (auto *PredBB : predecessors(BB)) {
2658 // Skip backedges.
2659 if (DT.dominates(BB, PredBB))
2660 continue;
2661
2662 // If the predecessor is in a region we used for propagation we can skip it.
2663 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2664 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2665 PredBBInRegion)) {
2666 continue;
2667 }
2668
2669 // Check if there is a valid region we can use for propagation, thus look
2670 // for a region that contains the predecessor and has @p BB as exit block.
2671 auto *PredR = RI.getRegionFor(PredBB);
2672 while (PredR->getExit() != BB && !PredR->contains(BB))
2673 PredR->getParent();
2674
2675 // If a valid region for propagation was found use the entry of that region
2676 // for propagation, otherwise the PredBB directly.
2677 if (PredR->getExit() == BB) {
2678 PredBB = PredR->getEntry();
2679 PropagatedRegions.insert(PredR);
2680 }
2681
Johannes Doerfert41cda152016-04-08 10:32:26 +00002682 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002683 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2684 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2685
2686 PredDom = isl_set_union(PredDom, PredBBDom);
2687 }
2688
2689 return PredDom;
2690}
2691
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002692bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2693 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002694 // Iterate over the region R and propagate the domain constrains from the
2695 // predecessors to the current node. In contrast to the
2696 // buildDomainsWithBranchConstraints function, this one will pull the domain
2697 // information from the predecessors instead of pushing it to the successors.
2698 // Additionally, we assume the domains to be already present in the domain
2699 // map here. However, we iterate again in reverse post order so we know all
2700 // predecessors have been visited before a block or non-affine subregion is
2701 // visited.
2702
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002703 ReversePostOrderTraversal<Region *> RTraversal(R);
2704 for (auto *RN : RTraversal) {
2705
2706 // Recurse for affine subregions but go on for basic blocks and non-affine
2707 // subregions.
2708 if (RN->isSubRegion()) {
2709 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002710 if (!isNonAffineSubRegion(SubRegion)) {
2711 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002712 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002713 continue;
2714 }
2715 }
2716
2717 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002718 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002719 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002720
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002721 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002722 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002723 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002724 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002725
Johannes Doerfert642594a2016-04-04 07:57:39 +00002726 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002727 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002728 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2729 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002730 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002731
2732 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002733}
2734
Tobias Grosserc80d6972016-09-02 06:33:33 +00002735/// Create a map to map from a given iteration to a subsequent iteration.
2736///
2737/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2738/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002739/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002740///
2741/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002742static __isl_give isl_map *
2743createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2744 auto *MapSpace = isl_space_map_from_set(SetSpace);
2745 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2746 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2747 if (u != Dim)
2748 NextIterationMap =
2749 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2750 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2751 C = isl_constraint_set_constant_si(C, 1);
2752 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2753 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2754 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2755 return NextIterationMap;
2756}
2757
Johannes Doerfert297c7202016-05-10 13:06:42 +00002758bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002759 int LoopDepth = getRelativeLoopDepth(L);
2760 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002761
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002762 BasicBlock *HeaderBB = L->getHeader();
2763 assert(DomainMap.count(HeaderBB));
2764 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002765
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002766 isl_map *NextIterationMap =
2767 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002768
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002769 isl_set *UnionBackedgeCondition =
2770 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002771
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002772 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2773 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002774
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002775 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002776
2777 // If the latch is only reachable via error statements we skip it.
2778 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2779 if (!LatchBBDom)
2780 continue;
2781
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002782 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002783
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002784 TerminatorInst *TI = LatchBB->getTerminator();
2785 BranchInst *BI = dyn_cast<BranchInst>(TI);
2786 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002787 BackedgeCondition = isl_set_copy(LatchBBDom);
2788 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002789 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002790 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002791 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
2792 ConditionSets))
2793 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002794
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002795 // Free the non back edge condition set as we do not need it.
2796 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002797
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002798 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002799 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002800
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002801 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2802 assert(LatchLoopDepth >= LoopDepth);
2803 BackedgeCondition =
2804 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2805 LatchLoopDepth - LoopDepth);
2806 UnionBackedgeCondition =
2807 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002808 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002809
2810 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2811 for (int i = 0; i < LoopDepth; i++)
2812 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2813
2814 isl_set *UnionBackedgeConditionComplement =
2815 isl_set_complement(UnionBackedgeCondition);
2816 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2817 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2818 UnionBackedgeConditionComplement =
2819 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2820 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2821 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2822
2823 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2824 HeaderBBDom = Parts.second;
2825
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002826 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2827 // the bounded assumptions to the context as they are already implied by the
2828 // <nsw> tag.
2829 if (Affinator.hasNSWAddRecForLoop(L)) {
2830 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002831 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002832 }
2833
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002834 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002835 recordAssumption(INFINITELOOP, UnboundedCtx,
2836 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002837 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002838}
2839
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002840MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
2841 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2842 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2843 if (!PointerBase)
2844 return nullptr;
2845
2846 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase->getValue());
2847 if (!PointerBaseInst)
2848 return nullptr;
2849
2850 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2851 if (!BasePtrStmt)
2852 return nullptr;
2853
2854 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2855}
2856
2857bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2858 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00002859 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
2860 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
2861 bool Hoistable = NHCtx != nullptr;
2862 isl_set_free(NHCtx);
2863 return !Hoistable;
2864 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002865
2866 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2867 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2868 if (auto *BasePtrInst = dyn_cast<Instruction>(PointerBase->getValue()))
2869 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00002870 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002871
2872 return false;
2873}
2874
Johannes Doerfert5210da52016-06-02 11:06:54 +00002875bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002876 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00002877 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002878
2879 if (buildAliasGroups(AA))
Johannes Doerfert5210da52016-06-02 11:06:54 +00002880 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002881
2882 // If a problem occurs while building the alias groups we need to delete
2883 // this SCoP and pretend it wasn't valid in the first place. To this end
2884 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002885 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002886
2887 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2888 << " could not be created as the number of parameters involved "
2889 "is too high. The SCoP will be "
2890 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2891 "the maximal number of parameters but be advised that the "
2892 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00002893 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002894}
2895
Johannes Doerfert9143d672014-09-27 11:02:39 +00002896bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002897 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002898 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002899 // for all memory accesses inside the SCoP.
2900 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002901 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002902 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002903 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002904 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002905 // if their access domains intersect, otherwise they are in different
2906 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002907 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002908 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002909 // and maximal accesses to each array of a group in read only and non
2910 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002911 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2912
2913 AliasSetTracker AST(AA);
2914
2915 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002916 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002917 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002918
2919 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002920 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002921 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2922 isl_set_free(StmtDomain);
2923 if (StmtDomainEmpty)
2924 continue;
2925
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002926 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002927 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002928 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002929 if (!MA->isRead())
2930 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002931 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002932 if (MA->isRead() && isa<MemTransferInst>(Acc))
2933 PtrToAcc[cast<MemTransferInst>(Acc)->getSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002934 else
2935 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002936 AST.add(Acc);
2937 }
2938 }
2939
2940 SmallVector<AliasGroupTy, 4> AliasGroups;
2941 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002942 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002943 continue;
2944 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002945 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002946 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002947 if (AG.size() < 2)
2948 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002949 AliasGroups.push_back(std::move(AG));
2950 }
2951
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002952 // Split the alias groups based on their domain.
2953 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2954 AliasGroupTy NewAG;
2955 AliasGroupTy &AG = AliasGroups[u];
2956 AliasGroupTy::iterator AGI = AG.begin();
2957 isl_set *AGDomain = getAccessDomain(*AGI);
2958 while (AGI != AG.end()) {
2959 MemoryAccess *MA = *AGI;
2960 isl_set *MADomain = getAccessDomain(MA);
2961 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2962 NewAG.push_back(MA);
2963 AGI = AG.erase(AGI);
2964 isl_set_free(MADomain);
2965 } else {
2966 AGDomain = isl_set_union(AGDomain, MADomain);
2967 AGI++;
2968 }
2969 }
2970 if (NewAG.size() > 1)
2971 AliasGroups.push_back(std::move(NewAG));
2972 isl_set_free(AGDomain);
2973 }
2974
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002975 auto &F = getFunction();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002976 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002977 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2978 for (AliasGroupTy &AG : AliasGroups) {
2979 NonReadOnlyBaseValues.clear();
2980 ReadOnlyPairs.clear();
2981
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002982 if (AG.size() < 2) {
2983 AG.clear();
2984 continue;
2985 }
2986
Johannes Doerfert13771732014-10-01 12:40:46 +00002987 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002988 emitOptimizationRemarkAnalysis(
2989 F.getContext(), DEBUG_TYPE, F,
2990 (*II)->getAccessInstruction()->getDebugLoc(),
2991 "Possibly aliasing pointer, use restrict keyword.");
2992
Johannes Doerfert13771732014-10-01 12:40:46 +00002993 Value *BaseAddr = (*II)->getBaseAddr();
2994 if (HasWriteAccess.count(BaseAddr)) {
2995 NonReadOnlyBaseValues.insert(BaseAddr);
2996 II++;
2997 } else {
2998 ReadOnlyPairs[BaseAddr].insert(*II);
2999 II = AG.erase(II);
3000 }
3001 }
3002
3003 // If we don't have read only pointers check if there are at least two
3004 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00003005 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003006 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00003007 continue;
3008 }
3009
3010 // If we don't have non read only pointers clear the alias group.
3011 if (NonReadOnlyBaseValues.empty()) {
3012 AG.clear();
3013 continue;
3014 }
3015
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003016 // Check if we have non-affine accesses left, if so bail out as we cannot
3017 // generate a good access range yet.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003018 for (auto *MA : AG) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003019 if (!MA->isAffine()) {
3020 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3021 return false;
3022 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003023 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
3024 addRequiredInvariantLoad(
3025 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3026 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003027 for (auto &ReadOnlyPair : ReadOnlyPairs)
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003028 for (auto *MA : ReadOnlyPair.second) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003029 if (!MA->isAffine()) {
3030 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3031 return false;
3032 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003033 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
3034 addRequiredInvariantLoad(
3035 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3036 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003037
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003038 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003039 MinMaxAliasGroups.emplace_back();
3040 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3041 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
3042 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3043 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003044
3045 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003046
3047 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00003048 for (MemoryAccess *MA : AG)
3049 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003050
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003051 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
3052 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003053
3054 // Bail out if the number of values we need to compare is too large.
3055 // This is important as the number of comparisions grows quadratically with
3056 // the number of values we need to compare.
Johannes Doerfert5210da52016-06-02 11:06:54 +00003057 if (!Valid || (MinMaxAccessesNonReadOnly.size() + ReadOnlyPairs.size() >
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003058 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003059 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003060
3061 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003062 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003063 Accesses = isl_union_map_empty(getParamSpace());
3064
3065 for (const auto &ReadOnlyPair : ReadOnlyPairs)
3066 for (MemoryAccess *MA : ReadOnlyPair.second)
3067 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
3068
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003069 Valid =
3070 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003071
3072 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003073 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003074 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003075
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003076 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003077}
3078
Tobias Grosserc80d6972016-09-02 06:33:33 +00003079/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003080static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003081 // Start with the smallest loop containing the entry and expand that
3082 // loop until it contains all blocks in the region. If there is a loop
3083 // containing all blocks in the region check if it is itself contained
3084 // and if so take the parent loop as it will be the smallest containing
3085 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003086 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003087 while (L) {
3088 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003089 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003090 AllContained &= L->contains(BB);
3091 if (AllContained)
3092 break;
3093 L = L->getParentLoop();
3094 }
3095
Johannes Doerfertef744432016-05-23 12:42:38 +00003096 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003097}
3098
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003099Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003100 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003101 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003102 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003103 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3104 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3105 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3106 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003107 if (IslOnErrorAbort)
3108 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003109 buildContext();
3110}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003111
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003112void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT,
3113 LoopInfo &LI) {
3114 buildInvariantEquivalenceClasses();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003115
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003116 if (!buildDomains(&R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003117 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003118
Johannes Doerfertff68f462016-04-19 14:49:42 +00003119 addUserAssumptions(AC, DT, LI);
3120
Johannes Doerfert26404542016-05-10 12:19:47 +00003121 // Remove empty statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003122 // Exit early in case there are no executable statements left in this scop.
Michael Kruse977d38b2016-07-22 17:31:17 +00003123 simplifySCoP(false);
Michael Kruseafe06702015-10-02 16:33:27 +00003124 if (Stmts.empty())
3125 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003126
Michael Krusecac948e2015-10-02 13:53:07 +00003127 // The ScopStmts now have enough information to initialize themselves.
3128 for (ScopStmt &Stmt : Stmts)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003129 Stmt.init(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00003130
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003131 // Check early for profitability. Afterwards it cannot change anymore,
3132 // only the runtime context could become infeasible.
3133 if (!isProfitable()) {
3134 invalidate(PROFITABLE, DebugLoc());
Tobias Grosser8286b832015-11-02 11:29:32 +00003135 return;
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003136 }
3137
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003138 buildSchedule(LI);
Tobias Grosser8286b832015-11-02 11:29:32 +00003139
3140 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003141 realignParams();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003142 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003143
3144 // After the context was fully constructed, thus all our knowledge about
3145 // the parameters is in there, we add all recorded assumptions to the
3146 // assumed/invalid context.
3147 addRecordedAssumptions();
3148
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003149 simplifyContexts();
Johannes Doerfert5210da52016-06-02 11:06:54 +00003150 if (!buildAliasChecks(AA))
3151 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003152
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003153 hoistInvariantLoads();
3154 verifyInvariantLoads();
Michael Kruse977d38b2016-07-22 17:31:17 +00003155 simplifySCoP(true);
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003156
3157 // Check late for a feasible runtime context because profitability did not
3158 // change.
3159 if (!hasFeasibleRuntimeContext()) {
3160 invalidate(PROFITABLE, DebugLoc());
3161 return;
3162 }
Tobias Grosser75805372011-04-29 06:27:02 +00003163}
3164
3165Scop::~Scop() {
3166 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003167 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003168 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003169 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003170
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003171 for (auto &It : ParameterIds)
3172 isl_id_free(It.second);
3173
Johannes Doerfert96425c22015-08-30 21:13:53 +00003174 for (auto It : DomainMap)
3175 isl_set_free(It.second);
3176
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003177 for (auto &AS : RecordedAssumptions)
3178 isl_set_free(AS.Set);
3179
Johannes Doerfertb164c792014-09-18 11:17:17 +00003180 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003181 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003182 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003183 isl_pw_multi_aff_free(MMA.first);
3184 isl_pw_multi_aff_free(MMA.second);
3185 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003186 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003187 isl_pw_multi_aff_free(MMA.first);
3188 isl_pw_multi_aff_free(MMA.second);
3189 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003190 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003191
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003192 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003193 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003194
3195 // Explicitly release all Scop objects and the underlying isl objects before
3196 // we relase the isl context.
3197 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003198 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003199 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003200 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003201 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003202}
3203
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003204void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003205 // Check all array accesses for each base pointer and find a (virtual) element
3206 // size for the base pointer that divides all access functions.
3207 for (auto &Stmt : *this)
3208 for (auto *Access : Stmt) {
3209 if (!Access->isArrayKind())
3210 continue;
3211 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
3212 ScopArrayInfo::MK_Array)];
3213 if (SAI->getNumberOfDimensions() != 1)
3214 continue;
3215 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3216 auto *Subscript = Access->getSubscript(0);
3217 while (!isDivisible(Subscript, DivisibleSize, *SE))
3218 DivisibleSize /= 2;
3219 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3220 SAI->updateElementType(Ty);
3221 }
3222
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003223 for (auto &Stmt : *this)
3224 for (auto &Access : Stmt)
3225 Access->updateDimensionality();
3226}
3227
Michael Kruse977d38b2016-07-22 17:31:17 +00003228void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003229 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3230 ScopStmt &Stmt = *StmtIt;
3231
Johannes Doerfert26404542016-05-10 12:19:47 +00003232 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003233 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003234 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003235
Johannes Doerferteca9e892015-11-03 16:54:49 +00003236 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003237 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003238 bool OnlyRead = true;
3239 for (MemoryAccess *MA : Stmt) {
3240 if (MA->isRead())
3241 continue;
3242
3243 OnlyRead = false;
3244 break;
3245 }
3246
3247 RemoveStmt = OnlyRead;
3248 }
3249
Johannes Doerfert26404542016-05-10 12:19:47 +00003250 if (!RemoveStmt) {
3251 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003252 continue;
3253 }
3254
Johannes Doerfert26404542016-05-10 12:19:47 +00003255 // Remove the statement because it is unnecessary.
3256 if (Stmt.isRegionStmt())
3257 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3258 StmtMap.erase(BB);
3259 else
3260 StmtMap.erase(Stmt.getBasicBlock());
3261
3262 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003263 }
3264}
3265
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003266InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003267 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3268 if (!LInst)
3269 return nullptr;
3270
3271 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3272 LInst = cast<LoadInst>(Rep);
3273
Johannes Doerfert96e54712016-02-07 17:30:13 +00003274 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003275 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003276 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003277 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003278 continue;
3279
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003280 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003281 for (auto *MA : MAs)
3282 if (MA->getAccessInstruction() == Val)
3283 return &IAClass;
3284 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003285
3286 return nullptr;
3287}
3288
Tobias Grosserc80d6972016-09-02 06:33:33 +00003289/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003290static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003291 bool MAInvalidCtxIsEmpty,
3292 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003293 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3294 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3295 // TODO: We can provide more information for better but more expensive
3296 // results.
3297 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3298 LInst->getAlignment(), DL))
3299 return false;
3300
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003301 // If the location might be overwritten we do not hoist it unconditionally.
3302 //
3303 // TODO: This is probably to conservative.
3304 if (!NonHoistableCtxIsEmpty)
3305 return false;
3306
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003307 // If a dereferencable load is in a statement that is modeled precisely we can
3308 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003309 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003310 return true;
3311
3312 // Even if the statement is not modeled precisely we can hoist the load if it
3313 // does not involve any parameters that might have been specilized by the
3314 // statement domain.
3315 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3316 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3317 return false;
3318 return true;
3319}
3320
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003321void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003322
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003323 if (InvMAs.empty())
3324 return;
3325
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003326 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003327 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003328
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003329 // Get the context under which the statement is executed but remove the error
3330 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003331 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003332 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003333
Michael Krusebc150122016-05-02 12:25:18 +00003334 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctionsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003335 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003336 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3337 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003338 for (auto &InvMA : InvMAs)
3339 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003340 return;
3341 }
3342
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003343 // Project out all parameters that relate to loads in the statement. Otherwise
3344 // we could have cyclic dependences on the constraints under which the
3345 // hoisted loads are executed and we could not determine an order in which to
3346 // pre-load them. This happens because not only lower bounds are part of the
3347 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003348 for (auto &InvMA : InvMAs) {
3349 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003350 Instruction *AccInst = MA->getAccessInstruction();
3351 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003352 SetVector<Value *> Values;
3353 for (const SCEV *Parameter : Parameters) {
3354 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003355 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003356 if (!Values.count(AccInst))
3357 continue;
3358
3359 if (isl_id *ParamId = getIdForParam(Parameter)) {
3360 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3361 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3362 isl_id_free(ParamId);
3363 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003364 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003365 }
3366 }
3367
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003368 for (auto &InvMA : InvMAs) {
3369 auto *MA = InvMA.MA;
3370 auto *NHCtx = InvMA.NonHoistableCtx;
3371
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003372 // Check for another invariant access that accesses the same location as
3373 // MA and if found consolidate them. Otherwise create a new equivalence
3374 // class at the end of InvariantEquivClasses.
3375 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003376 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003377 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3378
Johannes Doerfert85676e32016-04-23 14:32:34 +00003379 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003380 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003381 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3382
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003383 isl_set *MACtx;
3384 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003385 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3386 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003387 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003388 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003389 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003390 } else {
3391 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003392 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003393 MACtx = isl_set_gist_params(MACtx, getContext());
3394 }
3395
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003396 bool Consolidated = false;
3397 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003398 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003399 continue;
3400
Johannes Doerfertdf880232016-03-03 12:26:58 +00003401 // If the pointer and the type is equal check if the access function wrt.
3402 // to the domain is equal too. It can happen that the domain fixes
3403 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003404 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003405 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003406 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003407 if (!MAs.empty()) {
3408 auto *LastMA = MAs.front();
3409
3410 auto *AR = isl_map_range(MA->getAccessRelation());
3411 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3412 bool SameAR = isl_set_is_equal(AR, LastAR);
3413 isl_set_free(AR);
3414 isl_set_free(LastAR);
3415
3416 if (!SameAR)
3417 continue;
3418 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003419
3420 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003421 MAs.push_front(MA);
3422
Johannes Doerfertdf880232016-03-03 12:26:58 +00003423 Consolidated = true;
3424
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003425 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003426 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003427 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003428 IAClassDomainCtx =
3429 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003430 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003431 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003432 break;
3433 }
3434
3435 if (Consolidated)
3436 continue;
3437
3438 // If we did not consolidate MA, thus did not find an equivalence class
3439 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003440 InvariantEquivClasses.emplace_back(
3441 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003442 }
3443
3444 isl_set_free(DomainCtx);
3445}
3446
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003447__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3448 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003449 // TODO: Loads that are not loop carried, hence are in a statement with
3450 // zero iterators, are by construction invariant, though we
3451 // currently "hoist" them anyway. This is necessary because we allow
3452 // them to be treated as parameters (e.g., in conditions) and our code
3453 // generation would otherwise use the old value.
3454
3455 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003456 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003457
3458 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003459 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003460
3461 // Skip accesses that have an invariant base pointer which is defined but
3462 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3463 // returns a pointer that is used as a base address. However, as we want
3464 // to hoist indirect pointers, we allow the base pointer to be defined in
3465 // the region if it is also a memory access. Each ScopArrayInfo object
3466 // that has a base pointer origin has a base pointer that is loaded and
3467 // that it is invariant, thus it will be hoisted too. However, if there is
3468 // no base pointer origin we check that the base pointer is defined
3469 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003470 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003471 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003472 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003473
3474 // Skip accesses in non-affine subregions as they might not be executed
3475 // under the same condition as the entry of the non-affine subregion.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003476 if (BB != LI->getParent())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003477 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003478
3479 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003480 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003481
3482 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3483 Stmt.getNumIterators())) {
3484 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003485 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003486 }
3487
3488 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3489 isl_set *AccessRange = isl_map_range(AccessRelation);
3490
3491 isl_union_map *Written = isl_union_map_intersect_range(
3492 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003493 auto *WrittenCtx = isl_union_map_params(Written);
3494 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003495
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003496 if (!IsWritten)
3497 return WrittenCtx;
3498
3499 WrittenCtx = isl_set_remove_divs(WrittenCtx);
3500 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctionsInDomain;
3501 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3502 isl_set_free(WrittenCtx);
3503 return nullptr;
3504 }
3505
3506 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3507 AS_RESTRICTION);
3508 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003509}
3510
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003511void Scop::verifyInvariantLoads() {
3512 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003513 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003514 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003515 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003516 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003517 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3518 return;
3519 }
3520 }
3521}
3522
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003523void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003524 if (!PollyInvariantLoadHoisting)
3525 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003526
Tobias Grosser0865e7752016-02-29 07:29:42 +00003527 isl_union_map *Writes = getWrites();
3528 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003529 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003530
Tobias Grosser0865e7752016-02-29 07:29:42 +00003531 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003532 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3533 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003534
3535 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003536 for (auto InvMA : InvariantAccesses)
3537 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003538 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003539 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003540 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003541}
3542
Roman Gareevd7754a12016-07-30 09:25:51 +00003543const ScopArrayInfo *Scop::getOrCreateScopArrayInfo(
3544 Value *BasePtr, Type *ElementType, ArrayRef<const SCEV *> Sizes,
3545 ScopArrayInfo::MemoryKind Kind, const char *BaseName) {
3546 assert((BasePtr || BaseName) &&
3547 "BasePtr and BaseName can not be nullptr at the same time.");
3548 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3549 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3550 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003551 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003552 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003553 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003554 DL, this, BaseName));
3555 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003556 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003557 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003558 // In case of mismatching array sizes, we bail out by setting the run-time
3559 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003560 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003561 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003562 }
Tobias Grosserab671442015-05-23 05:58:27 +00003563 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003564}
3565
Roman Gareevd7754a12016-07-30 09:25:51 +00003566const ScopArrayInfo *
3567Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3568 const std::vector<unsigned> &Sizes) {
3569 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3570 std::vector<const SCEV *> SCEVSizes;
3571
3572 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003573 if (size)
3574 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3575 else
3576 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003577
3578 auto *SAI =
3579 getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3580 ScopArrayInfo::MK_Array, BaseName.c_str());
3581 return SAI;
3582}
3583
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003584const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003585 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003586 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003587 assert(SAI && "No ScopArrayInfo available for this base pointer");
3588 return SAI;
3589}
3590
Tobias Grosser74394f02013-01-14 22:40:23 +00003591std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003592
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003593std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003594 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003595 return stringFromIslObj(AssumedContext);
3596}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003597
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003598std::string Scop::getInvalidContextStr() const {
3599 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003600}
Tobias Grosser75805372011-04-29 06:27:02 +00003601
3602std::string Scop::getNameStr() const {
3603 std::string ExitName, EntryName;
3604 raw_string_ostream ExitStr(ExitName);
3605 raw_string_ostream EntryStr(EntryName);
3606
Tobias Grosserf240b482014-01-09 10:42:15 +00003607 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003608 EntryStr.str();
3609
3610 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003611 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003612 ExitStr.str();
3613 } else
3614 ExitName = "FunctionExit";
3615
3616 return EntryName + "---" + ExitName;
3617}
3618
Tobias Grosser74394f02013-01-14 22:40:23 +00003619__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003620__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003621 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003622}
3623
Tobias Grossere86109f2013-10-29 21:05:49 +00003624__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003625 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003626 return isl_set_copy(AssumedContext);
3627}
3628
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003629bool Scop::isProfitable() const {
3630 if (PollyProcessUnprofitable)
3631 return true;
3632
3633 if (!hasFeasibleRuntimeContext())
3634 return false;
3635
3636 if (isEmpty())
3637 return false;
3638
3639 unsigned OptimizableStmtsOrLoops = 0;
3640 for (auto &Stmt : *this) {
3641 if (Stmt.getNumIterators() == 0)
3642 continue;
3643
3644 bool ContainsArrayAccs = false;
3645 bool ContainsScalarAccs = false;
3646 for (auto *MA : Stmt) {
3647 if (MA->isRead())
3648 continue;
3649 ContainsArrayAccs |= MA->isArrayKind();
3650 ContainsScalarAccs |= MA->isScalarKind();
3651 }
3652
3653 if (ContainsArrayAccs && !ContainsScalarAccs)
3654 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3655 }
3656
3657 return OptimizableStmtsOrLoops > 1;
3658}
3659
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003660bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003661 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003662 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003663 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3664 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3665 isl_set_is_subset(PositiveContext, NegativeContext));
3666 isl_set_free(PositiveContext);
3667 if (!IsFeasible) {
3668 isl_set_free(NegativeContext);
3669 return false;
3670 }
3671
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003672 auto *DomainContext = isl_union_set_params(getDomains());
3673 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003674 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003675 isl_set_free(NegativeContext);
3676 isl_set_free(DomainContext);
3677
Johannes Doerfert43788c52015-08-20 05:58:56 +00003678 return IsFeasible;
3679}
3680
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003681static std::string toString(AssumptionKind Kind) {
3682 switch (Kind) {
3683 case ALIASING:
3684 return "No-aliasing";
3685 case INBOUNDS:
3686 return "Inbounds";
3687 case WRAPPING:
3688 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00003689 case UNSIGNED:
3690 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003691 case COMPLEXITY:
3692 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003693 case PROFITABLE:
3694 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003695 case ERRORBLOCK:
3696 return "No-error";
3697 case INFINITELOOP:
3698 return "Finite loop";
3699 case INVARIANTLOAD:
3700 return "Invariant load";
3701 case DELINEARIZATION:
3702 return "Delinearization";
3703 }
3704 llvm_unreachable("Unknown AssumptionKind!");
3705}
3706
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003707bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
3708 if (Sign == AS_ASSUMPTION) {
3709 if (isl_set_is_subset(Context, Set))
3710 return false;
3711
3712 if (isl_set_is_subset(AssumedContext, Set))
3713 return false;
3714 } else {
3715 if (isl_set_is_disjoint(Set, Context))
3716 return false;
3717
3718 if (isl_set_is_subset(Set, InvalidContext))
3719 return false;
3720 }
3721 return true;
3722}
3723
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003724bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3725 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003726 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
3727 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003728
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003729 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003730 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3731 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003732 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003733 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003734}
3735
3736void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003737 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003738 // Simplify the assumptions/restrictions first.
3739 Set = isl_set_gist_params(Set, getContext());
3740
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003741 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3742 isl_set_free(Set);
3743 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003744 }
3745
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003746 if (Sign == AS_ASSUMPTION) {
3747 AssumedContext = isl_set_intersect(AssumedContext, Set);
3748 AssumedContext = isl_set_coalesce(AssumedContext);
3749 } else {
3750 InvalidContext = isl_set_union(InvalidContext, Set);
3751 InvalidContext = isl_set_coalesce(InvalidContext);
3752 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003753}
3754
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003755void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003756 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
3757 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003758}
3759
3760void Scop::addRecordedAssumptions() {
3761 while (!RecordedAssumptions.empty()) {
3762 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003763
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003764 if (!AS.BB) {
3765 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
3766 continue;
3767 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003768
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003769 // If the domain was deleted the assumptions are void.
3770 isl_set *Dom = getDomainConditions(AS.BB);
3771 if (!Dom) {
3772 isl_set_free(AS.Set);
3773 continue;
3774 }
3775
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003776 // If a basic block was given use its domain to simplify the assumption.
3777 // In case of restrictions we know they only have to hold on the domain,
3778 // thus we can intersect them with the domain of the block. However, for
3779 // assumptions the domain has to imply them, thus:
3780 // _ _____
3781 // Dom => S <==> A v B <==> A - B
3782 //
3783 // To avoid the complement we will register A - B as a restricton not an
3784 // assumption.
3785 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003786 if (AS.Sign == AS_RESTRICTION)
3787 S = isl_set_params(isl_set_intersect(S, Dom));
3788 else /* (AS.Sign == AS_ASSUMPTION) */
3789 S = isl_set_params(isl_set_subtract(Dom, S));
3790
3791 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003792 }
3793}
3794
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003795void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003796 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003797}
3798
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003799__isl_give isl_set *Scop::getInvalidContext() const {
3800 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003801}
3802
Tobias Grosser75805372011-04-29 06:27:02 +00003803void Scop::printContext(raw_ostream &OS) const {
3804 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003805 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003806
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003807 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003808 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003809
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003810 OS.indent(4) << "Invalid Context:\n";
3811 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003812
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003813 unsigned Dim = 0;
3814 for (const SCEV *Parameter : Parameters)
3815 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003816}
3817
Johannes Doerfertb164c792014-09-18 11:17:17 +00003818void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003819 int noOfGroups = 0;
3820 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003821 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003822 noOfGroups += 1;
3823 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003824 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003825 }
3826
Tobias Grosserbb853c22015-07-25 12:31:03 +00003827 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003828 if (MinMaxAliasGroups.empty()) {
3829 OS.indent(8) << "n/a\n";
3830 return;
3831 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003832
Tobias Grosserbb853c22015-07-25 12:31:03 +00003833 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003834
3835 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003836 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003837 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003838 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003839 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3840 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003841 }
3842 OS << " ]]\n";
3843 }
3844
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003845 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003846 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003847 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003848 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003849 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3850 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003851 }
3852 OS << " ]]\n";
3853 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003854 }
3855}
3856
Tobias Grosser75805372011-04-29 06:27:02 +00003857void Scop::printStatements(raw_ostream &OS) const {
3858 OS << "Statements {\n";
3859
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003860 for (const ScopStmt &Stmt : *this)
3861 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003862
3863 OS.indent(4) << "}\n";
3864}
3865
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003866void Scop::printArrayInfo(raw_ostream &OS) const {
3867 OS << "Arrays {\n";
3868
Tobias Grosserab671442015-05-23 05:58:27 +00003869 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00003870 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003871
3872 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003873
3874 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3875
3876 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00003877 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003878
3879 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003880}
3881
Tobias Grosser75805372011-04-29 06:27:02 +00003882void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003883 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003884 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003885 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003886 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003887 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003888 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003889 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003890 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003891 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003892 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003893 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
3894 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003895 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003896 }
3897 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003898 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003899 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003900 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003901 printStatements(OS.indent(4));
3902}
3903
3904void Scop::dump() const { print(dbgs()); }
3905
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003906isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003907
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003908__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
3909 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003910 // First try to use the SCEVAffinator to generate a piecewise defined
3911 // affine function from @p E in the context of @p BB. If that tasks becomes to
3912 // complex the affinator might return a nullptr. In such a case we invalidate
3913 // the SCoP and return a dummy value. This way we do not need to add error
3914 // handling cdoe to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003915 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003916 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00003917 // TODO: We could use a heuristic and either use:
3918 // SCEVAffinator::takeNonNegativeAssumption
3919 // or
3920 // SCEVAffinator::interpretAsUnsigned
3921 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003922 if (NonNegative)
3923 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003924 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003925 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003926
3927 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
3928 invalidate(COMPLEXITY, DL);
3929 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003930}
3931
Tobias Grosser808cd692015-07-14 09:33:13 +00003932__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003933 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003934
Tobias Grosser808cd692015-07-14 09:33:13 +00003935 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003936 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003937
3938 return Domain;
3939}
3940
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003941__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
3942 PWACtx PWAC = getPwAff(E, BB);
3943 isl_set_free(PWAC.second);
3944 return PWAC.first;
3945}
3946
Tobias Grossere5a35142015-11-12 14:07:09 +00003947__isl_give isl_union_map *
3948Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3949 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003950
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003951 for (ScopStmt &Stmt : *this) {
3952 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003953 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003954 continue;
3955
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003956 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003957 isl_map *AccessDomain = MA->getAccessRelation();
3958 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003959 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003960 }
3961 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003962 return isl_union_map_coalesce(Accesses);
3963}
3964
3965__isl_give isl_union_map *Scop::getMustWrites() {
3966 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003967}
3968
3969__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003970 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003971}
3972
Tobias Grosser37eb4222014-02-20 21:43:54 +00003973__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003974 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003975}
3976
3977__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003978 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003979}
3980
Tobias Grosser2ac23382015-11-12 14:07:13 +00003981__isl_give isl_union_map *Scop::getAccesses() {
3982 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3983}
3984
Roman Gareevb3224ad2016-09-14 06:26:09 +00003985// Check whether @p Node is an extension node.
3986//
3987// @return true if @p Node is an extension node.
3988isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
3989 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
3990 return isl_bool_error;
3991 else
3992 return isl_bool_true;
3993}
3994
3995bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
3996 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
3997 nullptr) == isl_stat_error;
3998}
3999
Tobias Grosser808cd692015-07-14 09:33:13 +00004000__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004001 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004002 if (containsExtensionNode(Tree)) {
4003 isl_schedule_free(Tree);
4004 return nullptr;
4005 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004006 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004007 isl_schedule_free(Tree);
4008 return S;
4009}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004010
Tobias Grosser808cd692015-07-14 09:33:13 +00004011__isl_give isl_schedule *Scop::getScheduleTree() const {
4012 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4013 getDomains());
4014}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004015
Tobias Grosser808cd692015-07-14 09:33:13 +00004016void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4017 auto *S = isl_schedule_from_domain(getDomains());
4018 S = isl_schedule_insert_partial_schedule(
4019 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4020 isl_schedule_free(Schedule);
4021 Schedule = S;
4022}
4023
4024void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4025 isl_schedule_free(Schedule);
4026 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004027}
4028
4029bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4030 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004031 for (ScopStmt &Stmt : *this) {
4032 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004033 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4034 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4035
4036 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4037 isl_union_set_free(StmtDomain);
4038 isl_union_set_free(NewStmtDomain);
4039 continue;
4040 }
4041
4042 Changed = true;
4043
4044 isl_union_set_free(StmtDomain);
4045 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4046
4047 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004048 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004049 isl_union_set_free(NewStmtDomain);
4050 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004051 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004052 }
4053 isl_union_set_free(Domain);
4054 return Changed;
4055}
4056
Tobias Grosser75805372011-04-29 06:27:02 +00004057ScalarEvolution *Scop::getSE() const { return SE; }
4058
Tobias Grosser808cd692015-07-14 09:33:13 +00004059struct MapToDimensionDataTy {
4060 int N;
4061 isl_union_pw_multi_aff *Res;
4062};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004063
Tobias Grosserc80d6972016-09-02 06:33:33 +00004064// Create a function that maps the elements of 'Set' to its N-th dimension and
4065// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004066//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004067// @param Set The input set.
4068// @param User->N The dimension to map to.
4069// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004070//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004071// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004072static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4073 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4074 int Dim;
4075 isl_space *Space;
4076 isl_pw_multi_aff *PMA;
4077
4078 Dim = isl_set_dim(Set, isl_dim_set);
4079 Space = isl_set_get_space(Set);
4080 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4081 Dim - Data->N);
4082 if (Data->N > 1)
4083 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4084 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4085
4086 isl_set_free(Set);
4087
4088 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004089}
4090
Tobias Grosserc80d6972016-09-02 06:33:33 +00004091// Create an isl_multi_union_aff that defines an identity mapping from the
4092// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004093//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004094// # Example:
4095//
4096// Domain: { A[i,j]; B[i,j,k] }
4097// N: 1
4098//
4099// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4100//
4101// @param USet A union set describing the elements for which to generate a
4102// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004103// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004104// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004105static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004106mapToDimension(__isl_take isl_union_set *USet, int N) {
4107 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004108 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004109 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004110
Tobias Grosser808cd692015-07-14 09:33:13 +00004111 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004112
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004113 auto *Space = isl_union_set_get_space(USet);
4114 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004115
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004116 Data = {N, PwAff};
4117
4118 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004119 (void)Res;
4120
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004121 assert(Res == isl_stat_ok);
4122
4123 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004124 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4125}
4126
Tobias Grosser316b5b22015-11-11 19:28:14 +00004127void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00004128 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00004129 Stmts.emplace_back(*this, *BB);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004130 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004131 StmtMap[BB] = Stmt;
4132 } else {
4133 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00004134 Stmts.emplace_back(*this, *R);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004135 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004136 for (BasicBlock *BB : R->blocks())
4137 StmtMap[BB] = Stmt;
4138 }
Tobias Grosser808cd692015-07-14 09:33:13 +00004139}
4140
Roman Gareevb3224ad2016-09-14 06:26:09 +00004141ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4142 __isl_take isl_map *TargetRel,
4143 __isl_take isl_set *Domain) {
4144 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4145 CopyStmtsNum++;
4146 return &(Stmts.back());
4147}
4148
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004149void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004150 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004151 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004152 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004153 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4154 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004155}
4156
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004157/// To generate a schedule for the elements in a Region we traverse the Region
4158/// in reverse-post-order and add the contained RegionNodes in traversal order
4159/// to the schedule of the loop that is currently at the top of the LoopStack.
4160/// For loop-free codes, this results in a correct sequential ordering.
4161///
4162/// Example:
4163/// bb1(0)
4164/// / \.
4165/// bb2(1) bb3(2)
4166/// \ / \.
4167/// bb4(3) bb5(4)
4168/// \ /
4169/// bb6(5)
4170///
4171/// Including loops requires additional processing. Whenever a loop header is
4172/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4173/// from an empty schedule, we first process all RegionNodes that are within
4174/// this loop and complete the sequential schedule at this loop-level before
4175/// processing about any other nodes. To implement this
4176/// loop-nodes-first-processing, the reverse post-order traversal is
4177/// insufficient. Hence, we additionally check if the traversal yields
4178/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4179/// These region-nodes are then queue and only traverse after the all nodes
4180/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004181void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004182 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004183
4184 ReversePostOrderTraversal<Region *> RTraversal(R);
4185 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4186 std::deque<RegionNode *> DelayList;
4187 bool LastRNWaiting = false;
4188
4189 // Iterate over the region @p R in reverse post-order but queue
4190 // sub-regions/blocks iff they are not part of the last encountered but not
4191 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4192 // that we queued the last sub-region/block from the reverse post-order
4193 // iterator. If it is set we have to explore the next sub-region/block from
4194 // the iterator (if any) to guarantee progress. If it is not set we first try
4195 // the next queued sub-region/blocks.
4196 while (!WorkList.empty() || !DelayList.empty()) {
4197 RegionNode *RN;
4198
4199 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4200 RN = WorkList.front();
4201 WorkList.pop_front();
4202 LastRNWaiting = false;
4203 } else {
4204 RN = DelayList.front();
4205 DelayList.pop_front();
4206 }
4207
4208 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004209 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004210 L = OuterScopLoop;
4211
Tobias Grosser151ae322016-04-03 19:36:52 +00004212 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004213 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004214 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004215 LastRNWaiting = true;
4216 DelayList.push_back(RN);
4217 continue;
4218 }
4219 LoopStack.push_back({L, nullptr, 0});
4220 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004221 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004222 }
4223
4224 return;
4225}
4226
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004227void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004228
Tobias Grosser8362c262016-01-06 15:30:06 +00004229 if (RN->isSubRegion()) {
4230 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004231 if (!isNonAffineSubRegion(LocalRegion)) {
4232 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004233 return;
4234 }
4235 }
Michael Kruse046dde42015-08-10 13:01:57 +00004236
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004237 auto &LoopData = LoopStack.back();
4238 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004239
Michael Kruse6f7721f2016-02-24 22:08:19 +00004240 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004241 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4242 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004243 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004244 }
4245
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004246 // Check if we just processed the last node in this loop. If we did, finalize
4247 // the loop by:
4248 //
4249 // - adding new schedule dimensions
4250 // - folding the resulting schedule into the parent loop schedule
4251 // - dropping the loop schedule from the LoopStack.
4252 //
4253 // Then continue to check surrounding loops, which might also have been
4254 // completed by this node.
4255 while (LoopData.L &&
4256 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004257 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004258 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004259
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004260 LoopStack.pop_back();
4261 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004262
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004263 if (Schedule) {
4264 auto *Domain = isl_schedule_get_domain(Schedule);
4265 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4266 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4267 NextLoopData.Schedule =
4268 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004269 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004270
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004271 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4272 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004273 }
Tobias Grosser75805372011-04-29 06:27:02 +00004274}
4275
Michael Kruse6f7721f2016-02-24 22:08:19 +00004276ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004277 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004278 if (StmtMapIt == StmtMap.end())
4279 return nullptr;
4280 return StmtMapIt->second;
4281}
4282
Michael Kruse6f7721f2016-02-24 22:08:19 +00004283ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4284 if (RN->isSubRegion())
4285 return getStmtFor(RN->getNodeAs<Region>());
4286 return getStmtFor(RN->getNodeAs<BasicBlock>());
4287}
4288
4289ScopStmt *Scop::getStmtFor(Region *R) const {
4290 ScopStmt *Stmt = getStmtFor(R->getEntry());
4291 assert(!Stmt || Stmt->getRegion() == R);
4292 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004293}
4294
Johannes Doerfert96425c22015-08-30 21:13:53 +00004295int Scop::getRelativeLoopDepth(const Loop *L) const {
4296 Loop *OuterLoop =
4297 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4298 if (!OuterLoop)
4299 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004300 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4301}
4302
Roman Gareevd7754a12016-07-30 09:25:51 +00004303ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4304 for (auto &SAI : arrays()) {
4305 if (SAI->getName() == BaseName)
4306 return SAI;
4307 }
4308 return nullptr;
4309}
4310
Johannes Doerfert99191c72016-05-31 09:41:04 +00004311//===----------------------------------------------------------------------===//
4312void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4313 AU.addRequired<LoopInfoWrapperPass>();
4314 AU.addRequired<RegionInfoPass>();
4315 AU.addRequired<DominatorTreeWrapperPass>();
4316 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4317 AU.addRequiredTransitive<ScopDetection>();
4318 AU.addRequired<AAResultsWrapperPass>();
4319 AU.addRequired<AssumptionCacheTracker>();
4320 AU.setPreservesAll();
4321}
4322
4323bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4324 auto &SD = getAnalysis<ScopDetection>();
4325
4326 if (!SD.isMaxRegionInScop(*R))
4327 return false;
4328
4329 Function *F = R->getEntry()->getParent();
4330 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4331 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4332 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4333 auto const &DL = F->getParent()->getDataLayout();
4334 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4335 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
4336
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004337 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4338 S = SB.getScop(); // take ownership of scop object
Tobias Grosser75805372011-04-29 06:27:02 +00004339 return false;
4340}
4341
Johannes Doerfert99191c72016-05-31 09:41:04 +00004342void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004343 if (S)
4344 S->print(OS);
4345 else
4346 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004347}
Tobias Grosser75805372011-04-29 06:27:02 +00004348
Johannes Doerfert99191c72016-05-31 09:41:04 +00004349char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004350
Johannes Doerfert99191c72016-05-31 09:41:04 +00004351Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4352
4353INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004354 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004355 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004356INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004357INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004358INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004359INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004360INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004361INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004362INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004363INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004364 "Polly - Create polyhedral description of Scops", false,
4365 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004366
4367//===----------------------------------------------------------------------===//
4368void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4369 AU.addRequired<LoopInfoWrapperPass>();
4370 AU.addRequired<RegionInfoPass>();
4371 AU.addRequired<DominatorTreeWrapperPass>();
4372 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4373 AU.addRequiredTransitive<ScopDetection>();
4374 AU.addRequired<AAResultsWrapperPass>();
4375 AU.addRequired<AssumptionCacheTracker>();
4376 AU.setPreservesAll();
4377}
4378
4379bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4380 auto &SD = getAnalysis<ScopDetection>();
4381
4382 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4383 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4384 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4385 auto const &DL = F.getParent()->getDataLayout();
4386 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4387 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4388
4389 /// Create polyhedral descripton of scops for all the valid regions of a
4390 /// function.
4391 for (auto &It : SD) {
4392 Region *R = const_cast<Region *>(It);
4393 if (!SD.isMaxRegionInScop(*R))
4394 continue;
4395
4396 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004397 std::unique_ptr<Scop> S = SB.getScop();
4398 if (!S)
4399 continue;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004400 bool Inserted =
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004401 RegionToScopMap.insert(std::make_pair(R, std::move(S))).second;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004402 assert(Inserted && "Building Scop for the same region twice!");
4403 (void)Inserted;
4404 }
4405 return false;
4406}
4407
4408void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4409 for (auto &It : RegionToScopMap) {
4410 if (It.second)
4411 It.second->print(OS);
4412 else
4413 OS << "Invalid Scop!\n";
4414 }
4415}
4416
4417char ScopInfoWrapperPass::ID = 0;
4418
4419Pass *polly::createScopInfoWrapperPassPass() {
4420 return new ScopInfoWrapperPass();
4421}
4422
4423INITIALIZE_PASS_BEGIN(
4424 ScopInfoWrapperPass, "polly-function-scops",
4425 "Polly - Create polyhedral description of all Scops of a function", false,
4426 false);
4427INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
4428INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
4429INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4430INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4431INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4432INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4433INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4434INITIALIZE_PASS_END(
4435 ScopInfoWrapperPass, "polly-function-scops",
4436 "Polly - Create polyhedral description of all Scops of a function", false,
4437 false)