blob: 9b15a1d8cd7ef224ff65998e279d59f7a40a7642 [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
Johannes Doerfert81aa6e82016-11-18 14:37:08 +000064STATISTIC(AssumptionsAliasing, "Number of aliasing assumptions taken.");
65STATISTIC(AssumptionsInbounds, "Number of inbounds assumptions taken.");
66STATISTIC(AssumptionsWrapping, "Number of wrapping assumptions taken.");
67STATISTIC(AssumptionsUnsigned, "Number of unsigned assumptions taken.");
68STATISTIC(AssumptionsComplexity, "Number of too complex SCoPs.");
69STATISTIC(AssumptionsUnprofitable, "Number of unprofitable SCoPs.");
70STATISTIC(AssumptionsErrorBlock, "Number of error block assumptions taken.");
71STATISTIC(AssumptionsInfiniteLoop, "Number of bounded loop assumptions taken.");
72STATISTIC(AssumptionsInvariantLoad,
Johannes Doerfertcd195322016-11-17 21:41:08 +000073 "Number of invariant loads assumptions taken.");
Johannes Doerfert81aa6e82016-11-18 14:37:08 +000074STATISTIC(AssumptionsDelinearization,
Johannes Doerfertcd195322016-11-17 21:41:08 +000075 "Number of delinearization assumptions taken.");
76
Tobias Grosser75dc40c2015-12-20 13:31:48 +000077// The maximal number of basic sets we allow during domain construction to
78// be created. More complex scops will result in very high compile time and
79// are also unlikely to result in good code
Michael Krusebc150122016-05-02 12:25:18 +000080static int const MaxDisjunctionsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +000081
Johannes Doerfert2f705842016-04-12 16:09:44 +000082static cl::opt<bool> PollyRemarksMinimal(
83 "polly-remarks-minimal",
84 cl::desc("Do not emit remarks about assumptions that are known"),
85 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
86
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000087// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000088// operations can overflow easily. Additive reductions and bit operations
89// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000090static cl::opt<bool> DisableMultiplicativeReductions(
91 "polly-disable-multiplicative-reductions",
92 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
93 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000094
Johannes Doerfert9143d672014-09-27 11:02:39 +000095static cl::opt<unsigned> RunTimeChecksMaxParameters(
96 "polly-rtc-max-parameters",
97 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
98 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
99
Tobias Grosser71500722015-03-28 15:11:14 +0000100static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
101 "polly-rtc-max-arrays-per-group",
102 cl::desc("The maximal number of arrays to compare in each alias group."),
103 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000104
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000105static cl::opt<std::string> UserContextStr(
106 "polly-context", cl::value_desc("isl parameter set"),
107 cl::desc("Provide additional constraints on the context parameters"),
108 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000109
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000110static cl::opt<bool> DetectReductions("polly-detect-reductions",
111 cl::desc("Detect and exploit reductions"),
112 cl::Hidden, cl::ZeroOrMore,
113 cl::init(true), cl::cat(PollyCategory));
114
Tobias Grosser2937b592016-04-29 11:43:20 +0000115static cl::opt<bool>
116 IslOnErrorAbort("polly-on-isl-error-abort",
117 cl::desc("Abort if an isl error is encountered"),
118 cl::init(true), cl::cat(PollyCategory));
119
Michael Kruse6ab44762016-10-04 17:33:39 +0000120static cl::opt<bool> UnprofitableScalarAccs(
121 "polly-unprofitable-scalar-accs",
122 cl::desc("Count statements with scalar accesses as not optimizable"),
123 cl::Hidden, cl::init(true), cl::cat(PollyCategory));
124
Michael Kruse7bf39442015-09-10 12:46:52 +0000125//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000126
Michael Kruse046dde42015-08-10 13:01:57 +0000127// Create a sequence of two schedules. Either argument may be null and is
128// interpreted as the empty schedule. Can also return null if both schedules are
129// empty.
130static __isl_give isl_schedule *
131combineInSequence(__isl_take isl_schedule *Prev,
132 __isl_take isl_schedule *Succ) {
133 if (!Prev)
134 return Succ;
135 if (!Succ)
136 return Prev;
137
138 return isl_schedule_sequence(Prev, Succ);
139}
140
Johannes Doerferte7044942015-02-24 11:58:30 +0000141static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
142 const ConstantRange &Range,
143 int dim,
144 enum isl_dim_type type) {
145 isl_val *V;
146 isl_ctx *ctx = isl_set_get_ctx(S);
147
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000148 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
149 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000150 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000151 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
152
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000153 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000154 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000155 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000156 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000157 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
158
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000159 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000160 return isl_set_union(SLB, SUB);
161 else
162 return isl_set_intersect(SLB, SUB);
163}
164
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000165static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
166 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
167 if (!BasePtrLI)
168 return nullptr;
169
Johannes Doerfert952b5302016-05-23 12:40:48 +0000170 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000171 return nullptr;
172
173 ScalarEvolution &SE = *S->getSE();
174
175 auto *OriginBaseSCEV =
176 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
177 if (!OriginBaseSCEV)
178 return nullptr;
179
180 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
181 if (!OriginBaseSCEVUnknown)
182 return nullptr;
183
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000184 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000185 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000186}
187
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000188ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000189 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000190 const DataLayout &DL, Scop *S,
191 const char *BaseName)
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000192 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000193 std::string BasePtrName =
Roman Gareevd7754a12016-07-30 09:25:51 +0000194 BaseName ? BaseName : getIslCompatibleName("MemRef_", BasePtr,
195 Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000196 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000197
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000198 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000199
Michael Kruseca7cbcc2016-10-04 17:33:34 +0000200 if (!BasePtr || Kind != MK_Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000201 BasePtrOriginSAI = nullptr;
202 return;
203 }
204
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000205 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
206 if (BasePtrOriginSAI)
207 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000208}
209
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000210__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000211 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000212 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
213 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
214 return Space;
215}
216
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000217bool ScopArrayInfo::isReadOnly() {
218 isl_union_set *WriteSet = isl_union_map_range(S.getWrites());
219 isl_space *Space = getSpace();
220 WriteSet = isl_union_set_intersect(
221 WriteSet, isl_union_set_from_set(isl_set_universe(Space)));
222
223 bool IsReadOnly = isl_union_set_is_empty(WriteSet);
224 isl_union_set_free(WriteSet);
225
226 return IsReadOnly;
227}
228
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000229void ScopArrayInfo::updateElementType(Type *NewElementType) {
230 if (NewElementType == ElementType)
231 return;
232
Tobias Grosserd840fc72016-02-04 13:18:42 +0000233 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
234 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
235
Johannes Doerferta7920982016-02-25 14:08:48 +0000236 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000237 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000238
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000239 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
240 ElementType = NewElementType;
241 } else {
242 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
243 ElementType = IntegerType::get(ElementType->getContext(), GCD);
244 }
245}
246
247bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000248 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
249 int ExtraDimsNew = NewSizes.size() - SharedDims;
250 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000251
252 for (int i = 0; i < SharedDims; i++) {
Michael Kruse19c9d992016-09-13 09:56:05 +0000253 auto *NewSize = NewSizes[i + ExtraDimsNew];
254 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
Roman Gareevf5aff702016-09-12 17:08:31 +0000255 if (NewSize && KnownSize && NewSize != KnownSize)
Tobias Grosser8286b832015-11-02 11:29:32 +0000256 return false;
Roman Gareevf5aff702016-09-12 17:08:31 +0000257 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000258
259 if (DimensionSizes.size() >= NewSizes.size())
260 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000261
262 DimensionSizes.clear();
263 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
264 NewSizes.end());
265 for (isl_pw_aff *Size : DimensionSizesPw)
266 isl_pw_aff_free(Size);
267 DimensionSizesPw.clear();
268 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000269 if (!Expr) {
270 DimensionSizesPw.push_back(nullptr);
271 continue;
272 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000273 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000274 DimensionSizesPw.push_back(Size);
275 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000276 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000277}
278
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000279ScopArrayInfo::~ScopArrayInfo() {
280 isl_id_free(Id);
281 for (isl_pw_aff *Size : DimensionSizesPw)
282 isl_pw_aff_free(Size);
283}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000284
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000285std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
286
287int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000288 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000289}
290
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000291__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
292 return isl_id_copy(Id);
293}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000294
295void ScopArrayInfo::dump() const { print(errs()); }
296
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000297void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000298 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000299 unsigned u = 0;
300 if (getNumberOfDimensions() > 0 && !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000301 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000302 u++;
303 }
304 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000305 OS << "[";
306
Tobias Grosser26253842015-11-10 14:24:21 +0000307 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000308 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000309 OS << " " << Size << " ";
310 isl_pw_aff_free(Size);
311 } else {
312 OS << *getDimensionSize(u);
313 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000314
315 OS << "]";
316 }
317
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000318 OS << ";";
319
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000320 if (BasePtrOriginSAI)
321 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
322
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000323 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000324}
325
326const ScopArrayInfo *
327ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
328 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
329 assert(Id && "Output dimension didn't have an ID");
330 return getFromId(Id);
331}
332
Michael Krused56b90a2016-09-01 09:03:27 +0000333const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000334 void *User = isl_id_get_user(Id);
335 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
336 isl_id_free(Id);
337 return SAI;
338}
339
Michael Kruse3b425ff2016-04-11 14:34:08 +0000340void MemoryAccess::wrapConstantDimensions() {
341 auto *SAI = getScopArrayInfo();
342 auto *ArraySpace = SAI->getSpace();
343 auto *Ctx = isl_space_get_ctx(ArraySpace);
344 unsigned DimsArray = SAI->getNumberOfDimensions();
345
346 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
347 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
348 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
349
350 // Begin with last dimension, to iteratively carry into higher dimensions.
351 for (int i = DimsArray - 1; i > 0; i--) {
352 auto *DimSize = SAI->getDimensionSize(i);
353 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
354
355 // This transformation is not applicable to dimensions with dynamic size.
356 if (!DimSizeCst)
357 continue;
358
359 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
360 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
361 isl_dim_set, i);
362 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
363 isl_dim_set, i - 1);
364
365 // Compute: index % size
366 // Modulo must apply in the divide of the previous iteration, if any.
367 auto *Modulo = isl_aff_copy(Var);
368 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
369 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
370
371 // Compute: floor(index / size)
372 auto *Divide = Var;
373 Divide = isl_aff_div(
374 Divide,
375 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
376 Divide = isl_aff_floor(Divide);
377 Divide = isl_aff_add(Divide, PrevVar);
378 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
379
380 // Apply Modulo and Divide.
381 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
382 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
383 }
384
385 // Apply all modulo/divides on the accesses.
386 AccessRelation =
387 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
388 AccessRelation = isl_map_detect_equalities(AccessRelation);
389 isl_local_space_free(LArraySpace);
390}
391
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000392void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000393 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000394 auto *ArraySpace = SAI->getSpace();
395 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000396 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000397
398 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
399 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
400 auto DimsMissing = DimsArray - DimsAccess;
401
Michael Kruse375cb5f2016-02-24 22:08:24 +0000402 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000403 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000404 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000405 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000406
Johannes Doerferta90943d2016-02-21 16:37:25 +0000407 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000408 isl_set_universe(AccessSpace),
409 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000410
411 for (unsigned i = 0; i < DimsMissing; i++)
412 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
413
414 for (unsigned i = DimsMissing; i < DimsArray; i++)
415 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
416
417 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000418
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000419 // For the non delinearized arrays, divide the access function of the last
420 // subscript by the size of the elements in the array.
421 //
422 // A stride one array access in C expressed as A[i] is expressed in
423 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
424 // two subsequent values of 'i' index two values that are stored next to
425 // each other in memory. By this division we make this characteristic
426 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000427 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000428 // that divides the offsets of all accesses to this base pointer.
429 if (DimsAccess == 1) {
430 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
431 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
432 }
433
Michael Kruse3b425ff2016-04-11 14:34:08 +0000434 // We currently do this only if we added at least one dimension, which means
435 // some dimension's indices have not been specified, an indicator that some
436 // index values have been added together.
437 // TODO: Investigate general usefulness; Effect on unit tests is to make index
438 // expressions more complicated.
439 if (DimsMissing)
440 wrapConstantDimensions();
441
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000442 if (!isAffine())
443 computeBoundsOnAccessRelation(ArrayElemSize);
444
Tobias Grosserd840fc72016-02-04 13:18:42 +0000445 // Introduce multi-element accesses in case the type loaded by this memory
446 // access is larger than the canonical element type of the array.
447 //
448 // An access ((float *)A)[i] to an array char *A is modeled as
449 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000450 if (ElemBytes > ArrayElemSize) {
451 assert(ElemBytes % ArrayElemSize == 0 &&
452 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000453 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000454 isl_set_universe(isl_space_copy(ArraySpace)),
455 isl_set_universe(isl_space_copy(ArraySpace)));
456 for (unsigned i = 0; i < DimsArray - 1; i++)
457 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
458
Tobias Grosserd840fc72016-02-04 13:18:42 +0000459 isl_constraint *C;
460 isl_local_space *LS;
461
462 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000463 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
464
465 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
466 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000467 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000468 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
469 Map = isl_map_add_constraint(Map, C);
470
471 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000472 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000473 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
474 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
475 Map = isl_map_add_constraint(Map, C);
476 AccessRelation = isl_map_apply_range(AccessRelation, Map);
477 }
478
479 isl_space_free(ArraySpace);
480
Roman Gareev10595a12016-01-08 14:01:59 +0000481 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000482}
483
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000484const std::string
485MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
486 switch (RT) {
487 case MemoryAccess::RT_NONE:
488 llvm_unreachable("Requested a reduction operator string for a memory "
489 "access which isn't a reduction");
490 case MemoryAccess::RT_ADD:
491 return "+";
492 case MemoryAccess::RT_MUL:
493 return "*";
494 case MemoryAccess::RT_BOR:
495 return "|";
496 case MemoryAccess::RT_BXOR:
497 return "^";
498 case MemoryAccess::RT_BAND:
499 return "&";
500 }
501 llvm_unreachable("Unknown reduction type");
502 return "";
503}
504
Tobias Grosserc80d6972016-09-02 06:33:33 +0000505/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000506static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
507 const Instruction *Load) {
508 if (!BinOp)
509 return MemoryAccess::RT_NONE;
510 switch (BinOp->getOpcode()) {
511 case Instruction::FAdd:
512 if (!BinOp->hasUnsafeAlgebra())
513 return MemoryAccess::RT_NONE;
514 // Fall through
515 case Instruction::Add:
516 return MemoryAccess::RT_ADD;
517 case Instruction::Or:
518 return MemoryAccess::RT_BOR;
519 case Instruction::Xor:
520 return MemoryAccess::RT_BXOR;
521 case Instruction::And:
522 return MemoryAccess::RT_BAND;
523 case Instruction::FMul:
524 if (!BinOp->hasUnsafeAlgebra())
525 return MemoryAccess::RT_NONE;
526 // Fall through
527 case Instruction::Mul:
528 if (DisableMultiplicativeReductions)
529 return MemoryAccess::RT_NONE;
530 return MemoryAccess::RT_MUL;
531 default:
532 return MemoryAccess::RT_NONE;
533 }
534}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000535
Tobias Grosser75805372011-04-29 06:27:02 +0000536MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000537 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000538 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000539 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000540 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000541}
542
Michael Kruse2fa35192016-09-01 19:53:31 +0000543const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000544 isl_id *ArrayId = getArrayId();
545 void *User = isl_id_get_user(ArrayId);
546 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
547 isl_id_free(ArrayId);
548 return SAI;
549}
550
Michael Kruse2fa35192016-09-01 19:53:31 +0000551const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
552 isl_id *ArrayId = getLatestArrayId();
553 void *User = isl_id_get_user(ArrayId);
554 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
555 isl_id_free(ArrayId);
556 return SAI;
557}
558
559__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000560 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
561}
562
Michael Kruse2fa35192016-09-01 19:53:31 +0000563__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
564 if (!hasNewAccessRelation())
565 return getOriginalArrayId();
566 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
567}
568
Tobias Grosserd840fc72016-02-04 13:18:42 +0000569__isl_give isl_map *MemoryAccess::getAddressFunction() const {
570 return isl_map_lexmin(getAccessRelation());
571}
572
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000573__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
574 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000575 isl_map *Schedule, *ScheduledAccRel;
576 isl_union_set *UDomain;
577
578 UDomain = isl_union_set_from_set(getStatement()->getDomain());
579 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
580 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000581 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000582 return isl_pw_multi_aff_from_map(ScheduledAccRel);
583}
584
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000585__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000586 return isl_map_copy(AccessRelation);
587}
588
Johannes Doerferta99130f2014-10-13 12:58:03 +0000589std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000590 return stringFromIslObj(AccessRelation);
591}
592
Johannes Doerferta99130f2014-10-13 12:58:03 +0000593__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000594 return isl_map_get_space(AccessRelation);
595}
596
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000597__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000598 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000599}
600
Tobias Grosser6f730082015-09-05 07:46:47 +0000601std::string MemoryAccess::getNewAccessRelationStr() const {
602 return stringFromIslObj(NewAccessRelation);
603}
604
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000605__isl_give isl_basic_map *
606MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000607 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000608 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000609
Tobias Grosser084d8f72012-05-29 09:29:44 +0000610 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000611 isl_basic_set_universe(Statement->getDomainSpace()),
612 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000613}
614
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000615// Formalize no out-of-bound access assumption
616//
617// When delinearizing array accesses we optimistically assume that the
618// delinearized accesses do not access out of bound locations (the subscript
619// expression of each array evaluates for each statement instance that is
620// executed to a value that is larger than zero and strictly smaller than the
621// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000622// dimension for which we do not need to assume any upper bound. At this point
623// we formalize this assumption to ensure that at code generation time the
624// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000625//
626// To find the set of constraints necessary to avoid out of bound accesses, we
627// first build the set of data locations that are not within array bounds. We
628// then apply the reverse access relation to obtain the set of iterations that
629// may contain invalid accesses and reduce this set of iterations to the ones
630// that are actually executed by intersecting them with the domain of the
631// statement. If we now project out all loop dimensions, we obtain a set of
632// parameters that may cause statement instances to be executed that may
633// possibly yield out of bound memory accesses. The complement of these
634// constraints is the set of constraints that needs to be assumed to ensure such
635// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000636void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000637 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000638 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000639 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000640 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000641 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
642 isl_pw_aff *Var =
643 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
644 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
645
646 isl_set *DimOutside;
647
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000648 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000649 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000650 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
651 isl_space_dim(Space, isl_dim_set));
652 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
653 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000654
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000655 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000656
657 Outside = isl_set_union(Outside, DimOutside);
658 }
659
660 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
661 Outside = isl_set_intersect(Outside, Statement->getDomain());
662 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000663
664 // Remove divs to avoid the construction of overly complicated assumptions.
665 // Doing so increases the set of parameter combinations that are assumed to
666 // not appear. This is always save, but may make the resulting run-time check
667 // bail out more often than strictly necessary.
668 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000669 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000670 const auto &Loc = getAccessInstruction()
671 ? getAccessInstruction()->getDebugLoc()
672 : DebugLoc();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000673 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
674 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000675 isl_space_free(Space);
676}
677
Johannes Doerfertcea61932016-02-21 19:13:19 +0000678void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000679 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000680 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000681
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000682 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000683 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000684
685 isl_map *LengthMap;
686 if (Subscripts[1] == nullptr) {
687 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
688 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000689 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000690 LengthMap = isl_map_from_pw_aff(LengthPWA);
691 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
692 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
693 }
694 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
695 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000696 SubscriptMap =
697 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000698 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
699 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
700 getStatement()->getDomainId());
701}
702
Johannes Doerferte7044942015-02-24 11:58:30 +0000703void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
704 ScalarEvolution *SE = Statement->getParent()->getSE();
705
Johannes Doerfertcea61932016-02-21 19:13:19 +0000706 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000707 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000708 return;
709
710 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000711 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
712 return;
713
714 auto *PtrSCEV = SE->getSCEV(Ptr);
715 if (isa<SCEVCouldNotCompute>(PtrSCEV))
716 return;
717
718 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
719 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
720 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
721
722 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
723 if (Range.isFullSet())
724 return;
725
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000726 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000727 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000728 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000729 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000730 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000731
732 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000733 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000734
735 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
736 AccessRange =
737 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
738 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
739}
740
Michael Krusee2bccbb2015-09-18 19:59:43 +0000741__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000742 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000743 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000744
745 for (int i = Size - 2; i >= 0; --i) {
746 isl_space *Space;
747 isl_map *MapOne, *MapTwo;
Roman Gareevf5aff702016-09-12 17:08:31 +0000748 isl_pw_aff *DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000749
750 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
751 isl_pw_aff_free(DimSize);
752 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
753
754 Space = isl_map_get_space(AccessRelation);
755 Space = isl_space_map_from_set(isl_space_range(Space));
756 Space = isl_space_align_params(Space, SpaceSize);
757
758 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
759 isl_id_free(ParamId);
760
761 MapOne = isl_map_universe(isl_space_copy(Space));
762 for (int j = 0; j < Size; ++j)
763 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
764 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
765
766 MapTwo = isl_map_universe(isl_space_copy(Space));
767 for (int j = 0; j < Size; ++j)
768 if (j < i || j > i + 1)
769 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
770
771 isl_local_space *LS = isl_local_space_from_space(Space);
772 isl_constraint *C;
773 C = isl_equality_alloc(isl_local_space_copy(LS));
774 C = isl_constraint_set_constant_si(C, -1);
775 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
776 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
777 MapTwo = isl_map_add_constraint(MapTwo, C);
778 C = isl_equality_alloc(LS);
779 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
780 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
781 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
782 MapTwo = isl_map_add_constraint(MapTwo, C);
783 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
784
785 MapOne = isl_map_union(MapOne, MapTwo);
786 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
787 }
788 return AccessRelation;
789}
790
Tobias Grosserc80d6972016-09-02 06:33:33 +0000791/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000792static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000793 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000794 if (Size == 1)
795 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000796
797 // Only one factor needs to be divisible.
798 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
799 for (auto *FactorExpr : MulExpr->operands())
800 if (isDivisible(FactorExpr, Size, SE))
801 return true;
802 return false;
803 }
804
805 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
806 // to be divisble.
807 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
808 for (auto *OpExpr : NAryExpr->operands())
809 if (!isDivisible(OpExpr, Size, SE))
810 return false;
811 return true;
812 }
813
814 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
815 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
816 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
817 return MulSCEV == Expr;
818}
819
Michael Krusee2bccbb2015-09-18 19:59:43 +0000820void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
821 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000822
Johannes Doerfert85676e32016-04-23 14:32:34 +0000823 // Initialize the invalid domain which describes all iterations for which the
824 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000825 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
826 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
827 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000828
Michael Krusee2bccbb2015-09-18 19:59:43 +0000829 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000830 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000831
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000832 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
833 buildMemIntrinsicAccessRelation();
834 AccessRelation =
835 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
836 return;
837 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000838
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000839 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000840 // We overapproximate non-affine accesses with a possible access to the
841 // whole array. For read accesses it does not make a difference, if an
842 // access must or may happen. However, for write accesses it is important to
843 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000844 if (!AccessRelation)
845 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
846
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000847 AccessRelation =
848 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000849 return;
850 }
851
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000852 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000853 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000854
Michael Krusee2bccbb2015-09-18 19:59:43 +0000855 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000856 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000857 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000858 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000859 }
860
Roman Gareevf5aff702016-09-12 17:08:31 +0000861 if (Sizes.size() >= 2 && !isa<SCEVConstant>(Sizes[1]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000862 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000863
Tobias Grosser79baa212014-04-10 08:38:02 +0000864 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000865 AccessRelation = isl_map_set_tuple_id(
866 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000867 AccessRelation =
868 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
869
Tobias Grosseraa660a92015-03-30 00:07:50 +0000870 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000871 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000872}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000873
Michael Krusecac948e2015-10-02 13:53:07 +0000874MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000875 AccessType AccType, Value *BaseAddress,
876 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000877 ArrayRef<const SCEV *> Subscripts,
878 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000879 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000880 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Johannes Doerfert85676e32016-04-23 14:32:34 +0000881 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
882 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()),
883 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000884 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000885 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000886 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000887 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000888
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000889 std::string IdName =
890 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000891 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
892}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000893
Roman Gareevb3224ad2016-09-14 06:26:09 +0000894MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
895 __isl_take isl_map *AccRel)
896 : Kind(ScopArrayInfo::MemoryKind::MK_Array), AccType(AccType),
897 RedType(RT_NONE), Statement(Stmt), InvalidDomain(nullptr),
898 AccessInstruction(nullptr), IsAffine(true), AccessRelation(nullptr),
899 NewAccessRelation(AccRel) {
900 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
901 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
902 Sizes.push_back(nullptr);
903 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
904 Sizes.push_back(SAI->getDimensionSize(i));
905 ElementType = SAI->getElementType();
906 BaseAddr = SAI->getBasePtr();
907 BaseName = SAI->getName();
908 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
909 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
910
911 std::string IdName =
912 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
913 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
914}
915
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000916void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +0000917 auto *Ctx = Statement->getParent()->getContext();
918 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
919 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +0000920}
921
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000922const std::string MemoryAccess::getReductionOperatorStr() const {
923 return MemoryAccess::getReductionOperatorStr(getReductionType());
924}
925
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000926__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
927
Johannes Doerfertf6183392014-07-01 20:52:51 +0000928raw_ostream &polly::operator<<(raw_ostream &OS,
929 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000930 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000931 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000932 else
933 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000934 return OS;
935}
936
Tobias Grosser75805372011-04-29 06:27:02 +0000937void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000938 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000939 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000940 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000941 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000942 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000943 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000944 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000945 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000946 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000947 break;
948 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000949 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000950 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000951 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000952 if (hasNewAccessRelation())
953 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000954}
955
Tobias Grosser74394f02013-01-14 22:40:23 +0000956void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000957
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000958__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
959 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000960 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +0000961 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
962 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
963 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000964 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000965}
966
Tobias Grosser75805372011-04-29 06:27:02 +0000967// Create a map in the size of the provided set domain, that maps from the
968// one element of the provided set domain to another element of the provided
969// set domain.
970// The mapping is limited to all points that are equal in all but the last
971// dimension and for which the last dimension of the input is strict smaller
972// than the last dimension of the output.
973//
974// getEqualAndLarger(set[i0, i1, ..., iX]):
975//
976// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
977// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
978//
Tobias Grosser2a526fe2016-09-08 11:18:56 +0000979static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000980 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000981 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000982 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000983
984 // Set all but the last dimension to be equal for the input and output
985 //
986 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
987 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000988 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000989 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000990
991 // Set the last dimension of the input to be strict smaller than the
992 // last dimension of the output.
993 //
994 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000995 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
996 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000997 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000998}
999
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001000__isl_give isl_set *
1001MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001002 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +00001003 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +00001004 isl_space *Space = isl_space_range(isl_map_get_space(S));
1005 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001006
Sebastian Popa00a0292012-12-18 07:46:06 +00001007 S = isl_map_reverse(S);
1008 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001009
Sebastian Popa00a0292012-12-18 07:46:06 +00001010 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1011 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1012 NextScatt = isl_map_apply_domain(NextScatt, S);
1013 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001014
Sebastian Popa00a0292012-12-18 07:46:06 +00001015 isl_set *Deltas = isl_map_deltas(NextScatt);
1016 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001017}
1018
Sebastian Popa00a0292012-12-18 07:46:06 +00001019bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001020 int StrideWidth) const {
1021 isl_set *Stride, *StrideX;
1022 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001023
Sebastian Popa00a0292012-12-18 07:46:06 +00001024 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001025 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001026 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1027 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1028 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1029 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001030 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001031
Tobias Grosser28dd4862012-01-24 16:42:16 +00001032 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001033 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001034
Tobias Grosser28dd4862012-01-24 16:42:16 +00001035 return IsStrideX;
1036}
1037
Michael Krused56b90a2016-09-01 09:03:27 +00001038bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001039 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001040}
1041
Michael Krused56b90a2016-09-01 09:03:27 +00001042bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001043 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001044}
1045
Michael Krused56b90a2016-09-01 09:03:27 +00001046void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001047 assert(NewAccess);
1048
1049#ifndef NDEBUG
1050 // Check domain space compatibility.
1051 auto *NewSpace = isl_map_get_space(NewAccess);
1052 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1053 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1054 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1055 isl_space_free(NewDomainSpace);
1056 isl_space_free(OriginalDomainSpace);
1057
1058 // Check whether there is an access for every statement instance.
1059 auto *StmtDomain = getStatement()->getDomain();
1060 StmtDomain = isl_set_intersect_params(
1061 StmtDomain, getStatement()->getParent()->getContext());
1062 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1063 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1064 "Partial accesses not supported");
1065 isl_set_free(NewDomain);
1066 isl_set_free(StmtDomain);
1067
1068 // Check whether access dimensions correspond to number of dimensions of the
1069 // accesses array.
1070 auto *NewAccessSpace = isl_space_range(NewSpace);
1071 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1072 "Must specify the array that is accessed");
1073 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1074 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1075 assert(SAI && "Must set a ScopArrayInfo");
1076 assert(!SAI->getBasePtrOriginSAI() &&
1077 "Indirect array not supported by codegen");
1078 auto Dims = SAI->getNumberOfDimensions();
1079 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1080 "Access dims must match array dims");
1081 isl_space_free(NewAccessSpace);
1082 isl_id_free(NewArrayId);
1083#endif
1084
Tobias Grosser166c4222015-09-05 07:46:40 +00001085 isl_map_free(NewAccessRelation);
1086 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001087}
Tobias Grosser75805372011-04-29 06:27:02 +00001088
1089//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001090
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001091__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001092 isl_set *Domain = getDomain();
1093 if (isl_set_is_empty(Domain)) {
1094 isl_set_free(Domain);
1095 return isl_map_from_aff(
1096 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1097 }
1098 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001099 if (!Schedule) {
1100 isl_set_free(Domain);
1101 return nullptr;
1102 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001103 Schedule = isl_union_map_intersect_domain(
1104 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1105 if (isl_union_map_is_empty(Schedule)) {
1106 isl_set_free(Domain);
1107 isl_union_map_free(Schedule);
1108 return isl_map_from_aff(
1109 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1110 }
1111 auto *M = isl_map_from_union_map(Schedule);
1112 M = isl_map_coalesce(M);
1113 M = isl_map_gist_domain(M, Domain);
1114 M = isl_map_coalesce(M);
1115 return M;
1116}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001117
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001118__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1119 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001120 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1121 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001122}
1123
Tobias Grosser37eb4222014-02-20 21:43:54 +00001124void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1125 assert(isl_set_is_subset(NewDomain, Domain) &&
1126 "New domain is not a subset of old domain!");
1127 isl_set_free(Domain);
1128 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001129}
1130
Michael Krusecac948e2015-10-02 13:53:07 +00001131void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001132 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001133 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001134 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001135
Tobias Grossera535dff2015-12-13 19:59:01 +00001136 ScopArrayInfo::MemoryKind Ty;
1137 if (Access->isPHIKind())
1138 Ty = ScopArrayInfo::MK_PHI;
1139 else if (Access->isExitPHIKind())
1140 Ty = ScopArrayInfo::MK_ExitPHI;
1141 else if (Access->isValueKind())
1142 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001143 else
Tobias Grossera535dff2015-12-13 19:59:01 +00001144 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001145
Johannes Doerfertadeab372016-02-07 13:57:32 +00001146 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1147 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001148 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001149 }
1150}
1151
Michael Krusecac948e2015-10-02 13:53:07 +00001152void ScopStmt::addAccess(MemoryAccess *Access) {
1153 Instruction *AccessInst = Access->getAccessInstruction();
1154
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001155 if (Access->isArrayKind()) {
1156 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1157 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001158 } else if (Access->isValueKind() && Access->isWrite()) {
1159 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001160 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001161 assert(!ValueWrites.lookup(AccessVal));
1162
1163 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001164 } else if (Access->isValueKind() && Access->isRead()) {
1165 Value *AccessVal = Access->getAccessValue();
1166 assert(!ValueReads.lookup(AccessVal));
1167
1168 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001169 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1170 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1171 assert(!PHIWrites.lookup(PHI));
1172
1173 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001174 }
1175
1176 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001177}
1178
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001179void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001180 for (MemoryAccess *MA : *this)
1181 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001182
Johannes Doerferta60ad842016-05-10 12:18:22 +00001183 auto *Ctx = Parent.getContext();
1184 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1185 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001186}
1187
Tobias Grosserc80d6972016-09-02 06:33:33 +00001188/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001189static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1190 void *User) {
1191 isl_set **BoundedParts = static_cast<isl_set **>(User);
1192 if (isl_basic_set_is_bounded(BSet))
1193 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1194 else
1195 isl_basic_set_free(BSet);
1196 return isl_stat_ok;
1197}
1198
Tobias Grosserc80d6972016-09-02 06:33:33 +00001199/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001200static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1201 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1202 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1203 isl_set_free(S);
1204 return BoundedParts;
1205}
1206
Tobias Grosserc80d6972016-09-02 06:33:33 +00001207/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001208///
1209/// @returns A separation of @p S into first an unbounded then a bounded subset,
1210/// both with regards to the dimension @p Dim.
1211static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1212partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1213
1214 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001215 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001216
1217 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001218 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001219
1220 // Remove dimensions that are greater than Dim as they are not interesting.
1221 assert(NumDimsS >= Dim + 1);
1222 OnlyDimS =
1223 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1224
1225 // Create artificial parametric upper bounds for dimensions smaller than Dim
1226 // as we are not interested in them.
1227 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1228 for (unsigned u = 0; u < Dim; u++) {
1229 isl_constraint *C = isl_inequality_alloc(
1230 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1231 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1232 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1233 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1234 }
1235
1236 // Collect all bounded parts of OnlyDimS.
1237 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1238
1239 // Create the dimensions greater than Dim again.
1240 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1241 NumDimsS - Dim - 1);
1242
1243 // Remove the artificial upper bound parameters again.
1244 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1245
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001246 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001247 return std::make_pair(UnboundedParts, BoundedParts);
1248}
1249
Tobias Grosserc80d6972016-09-02 06:33:33 +00001250/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001251static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1252 __isl_take isl_set *To) {
1253 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1254 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1255 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1256 }
1257 return To;
1258}
1259
Tobias Grosserc80d6972016-09-02 06:33:33 +00001260/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001261static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001262 __isl_take isl_pw_aff *L,
1263 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001264 switch (Pred) {
1265 case ICmpInst::ICMP_EQ:
1266 return isl_pw_aff_eq_set(L, R);
1267 case ICmpInst::ICMP_NE:
1268 return isl_pw_aff_ne_set(L, R);
1269 case ICmpInst::ICMP_SLT:
1270 return isl_pw_aff_lt_set(L, R);
1271 case ICmpInst::ICMP_SLE:
1272 return isl_pw_aff_le_set(L, R);
1273 case ICmpInst::ICMP_SGT:
1274 return isl_pw_aff_gt_set(L, R);
1275 case ICmpInst::ICMP_SGE:
1276 return isl_pw_aff_ge_set(L, R);
1277 case ICmpInst::ICMP_ULT:
1278 return isl_pw_aff_lt_set(L, R);
1279 case ICmpInst::ICMP_UGT:
1280 return isl_pw_aff_gt_set(L, R);
1281 case ICmpInst::ICMP_ULE:
1282 return isl_pw_aff_le_set(L, R);
1283 case ICmpInst::ICMP_UGE:
1284 return isl_pw_aff_ge_set(L, R);
1285 default:
1286 llvm_unreachable("Non integer predicate not supported");
1287 }
1288}
1289
Tobias Grosserc80d6972016-09-02 06:33:33 +00001290/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001291///
1292/// Helper function that will make sure the dimensions of the result have the
1293/// same isl_id's as the @p Domain.
1294static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1295 __isl_take isl_pw_aff *L,
1296 __isl_take isl_pw_aff *R,
1297 __isl_keep isl_set *Domain) {
1298 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1299 return setDimensionIds(Domain, ConsequenceCondSet);
1300}
1301
Tobias Grosserc80d6972016-09-02 06:33:33 +00001302/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001303///
1304/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001305/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1306/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001307static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001308buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1309 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001310 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1311
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001312 Value *Condition = getConditionFromTerminator(SI);
1313 assert(Condition && "No condition for switch");
1314
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001315 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001316 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001317 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001318 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001319
1320 unsigned NumSuccessors = SI->getNumSuccessors();
1321 ConditionSets.resize(NumSuccessors);
1322 for (auto &Case : SI->cases()) {
1323 unsigned Idx = Case.getSuccessorIndex();
1324 ConstantInt *CaseValue = Case.getCaseValue();
1325
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001326 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001327 isl_set *CaseConditionSet =
1328 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1329 ConditionSets[Idx] = isl_set_coalesce(
1330 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1331 }
1332
1333 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1334 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1335 for (unsigned u = 2; u < NumSuccessors; u++)
1336 ConditionSetUnion =
1337 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1338 ConditionSets[0] = setDimensionIds(
1339 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1340
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001341 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001342
1343 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001344}
1345
Tobias Grosserc80d6972016-09-02 06:33:33 +00001346/// Build the conditions sets for the branch condition @p Condition in
1347/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001348///
1349/// This will fill @p ConditionSets with the conditions under which control
1350/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001351/// have as many elements as @p TI has successors. If @p TI is nullptr the
1352/// context under which @p Condition is true/false will be returned as the
1353/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001354static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001355buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1356 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001357 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1358
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001359 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001360 isl_set *ConsequenceCondSet = nullptr;
1361 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1362 if (CCond->isZero())
1363 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1364 else
1365 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1366 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1367 auto Opcode = BinOp->getOpcode();
1368 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1369
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001370 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1371 ConditionSets) &&
1372 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1373 ConditionSets);
1374 if (!Valid) {
1375 while (!ConditionSets.empty())
1376 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001377 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001378 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001379
1380 isl_set_free(ConditionSets.pop_back_val());
1381 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1382 isl_set_free(ConditionSets.pop_back_val());
1383 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1384
1385 if (Opcode == Instruction::And)
1386 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1387 else
1388 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1389 } else {
1390 auto *ICond = dyn_cast<ICmpInst>(Condition);
1391 assert(ICond &&
1392 "Condition of exiting branch was neither constant nor ICmp!");
1393
1394 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001395 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001396 // For unsigned comparisons we assumed the signed bit of neither operand
1397 // to be set. The comparison is equal to a signed comparison under this
1398 // assumption.
1399 bool NonNeg = ICond->isUnsigned();
1400 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1401 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001402 ConsequenceCondSet =
1403 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1404 }
1405
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001406 // If no terminator was given we are only looking for parameter constraints
1407 // under which @p Condition is true/false.
1408 if (!TI)
1409 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001410 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001411 ConsequenceCondSet = isl_set_coalesce(
1412 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001413
Johannes Doerfertb2885792016-04-26 09:20:41 +00001414 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001415 bool TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001416 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001417
Michael Krusef7a4a942016-05-02 12:25:36 +00001418 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001419 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1420 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001421 TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001422 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001423 }
1424
Michael Krusef7a4a942016-05-02 12:25:36 +00001425 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001426 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001427 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001428 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001429 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001430 }
1431
1432 ConditionSets.push_back(ConsequenceCondSet);
1433 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001434
1435 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001436}
1437
Tobias Grosserc80d6972016-09-02 06:33:33 +00001438/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001439///
1440/// This will fill @p ConditionSets with the conditions under which control
1441/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1442/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001443static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001444buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001445 __isl_keep isl_set *Domain,
1446 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1447
1448 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001449 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001450
1451 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1452
1453 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001454 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001455 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001456 }
1457
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001458 Value *Condition = getConditionFromTerminator(TI);
1459 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001460
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001461 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001462}
1463
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001464void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001465 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001466
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001467 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001468 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001469}
1470
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001471void ScopStmt::collectSurroundingLoops() {
1472 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1473 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1474 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1475 isl_id_free(DimId);
1476 }
1477}
1478
Michael Kruse9d080092015-09-11 21:41:48 +00001479ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerferta3519512016-04-23 13:02:23 +00001480 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1481 R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001482
Tobias Grosser16c44032015-07-09 07:31:45 +00001483 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001484}
1485
Michael Kruse9d080092015-09-11 21:41:48 +00001486ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerferta3519512016-04-23 13:02:23 +00001487 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1488 R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001489
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001490 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001491}
1492
Roman Gareevb3224ad2016-09-14 06:26:09 +00001493ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1494 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1495 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1496 R(nullptr), Build(nullptr) {
1497 BaseName = getIslCompatibleName("CopyStmt_", "",
1498 std::to_string(parent.getCopyStmtsNum()));
1499 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1500 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1501 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1502 auto *Access =
1503 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1504 parent.addAccessFunction(Access);
1505 addAccess(Access);
1506 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1507 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1508 parent.addAccessFunction(Access);
1509 addAccess(Access);
1510}
1511
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001512void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001513 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001514
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001515 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001516 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001517 buildAccessRelations();
1518
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001519 if (DetectReductions)
1520 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001521}
1522
Tobias Grosserc80d6972016-09-02 06:33:33 +00001523/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001524///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001525/// Check if the stored value for @p StoreMA is a binary operator with one or
1526/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001527/// used only once (by @p StoreMA) and its load operands are also used only
1528/// once, we have found a possible reduction chain. It starts at an operand
1529/// load and includes the binary operator and @p StoreMA.
1530///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001531/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001532/// escape this block or into any other store except @p StoreMA.
1533void ScopStmt::collectCandiateReductionLoads(
1534 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1535 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1536 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001537 return;
1538
1539 // Skip if there is not one binary operator between the load and the store
1540 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001541 if (!BinOp)
1542 return;
1543
1544 // Skip if the binary operators has multiple uses
1545 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001546 return;
1547
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001548 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001549 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1550 return;
1551
Johannes Doerfert9890a052014-07-01 00:32:29 +00001552 // Skip if the binary operator is outside the current SCoP
1553 if (BinOp->getParent() != Store->getParent())
1554 return;
1555
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001556 // Skip if it is a multiplicative reduction and we disabled them
1557 if (DisableMultiplicativeReductions &&
1558 (BinOp->getOpcode() == Instruction::Mul ||
1559 BinOp->getOpcode() == Instruction::FMul))
1560 return;
1561
Johannes Doerferte58a0122014-06-27 20:31:28 +00001562 // Check the binary operator operands for a candidate load
1563 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1564 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1565 if (!PossibleLoad0 && !PossibleLoad1)
1566 return;
1567
1568 // A load is only a candidate if it cannot escape (thus has only this use)
1569 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001570 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001571 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001572 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001573 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001574 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001575}
1576
Tobias Grosserc80d6972016-09-02 06:33:33 +00001577/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001578///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001579/// Iterate over all store memory accesses and check for valid binary reduction
1580/// like chains. For all candidates we check if they have the same base address
1581/// and there are no other accesses which overlap with them. The base address
1582/// check rules out impossible reductions candidates early. The overlap check,
1583/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001584/// guarantees that none of the intermediate results will escape during
1585/// execution of the loop nest. We basically check here that no other memory
1586/// access can access the same memory as the potential reduction.
1587void ScopStmt::checkForReductions() {
1588 SmallVector<MemoryAccess *, 2> Loads;
1589 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1590
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001591 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001592 // stores and collecting possible reduction loads.
1593 for (MemoryAccess *StoreMA : MemAccs) {
1594 if (StoreMA->isRead())
1595 continue;
1596
1597 Loads.clear();
1598 collectCandiateReductionLoads(StoreMA, Loads);
1599 for (MemoryAccess *LoadMA : Loads)
1600 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1601 }
1602
1603 // Then check each possible candidate pair.
1604 for (const auto &CandidatePair : Candidates) {
1605 bool Valid = true;
1606 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1607 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1608
1609 // Skip those with obviously unequal base addresses.
1610 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1611 isl_map_free(LoadAccs);
1612 isl_map_free(StoreAccs);
1613 continue;
1614 }
1615
1616 // And check if the remaining for overlap with other memory accesses.
1617 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1618 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1619 isl_set *AllAccs = isl_map_range(AllAccsRel);
1620
1621 for (MemoryAccess *MA : MemAccs) {
1622 if (MA == CandidatePair.first || MA == CandidatePair.second)
1623 continue;
1624
1625 isl_map *AccRel =
1626 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1627 isl_set *Accs = isl_map_range(AccRel);
1628
Tobias Grosser55a7af72016-09-08 14:08:07 +00001629 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001630 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1631 Valid = Valid && isl_set_is_empty(OverlapAccs);
1632 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001633 } else {
1634 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001635 }
1636 }
1637
1638 isl_set_free(AllAccs);
1639 if (!Valid)
1640 continue;
1641
Johannes Doerfertf6183392014-07-01 20:52:51 +00001642 const LoadInst *Load =
1643 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1644 MemoryAccess::ReductionType RT =
1645 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1646
Johannes Doerferte58a0122014-06-27 20:31:28 +00001647 // If no overlapping access was found we mark the load and store as
1648 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001649 CandidatePair.first->markAsReductionLike(RT);
1650 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001651 }
Tobias Grosser75805372011-04-29 06:27:02 +00001652}
1653
Tobias Grosser74394f02013-01-14 22:40:23 +00001654std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001655
Tobias Grosser54839312015-04-21 11:37:25 +00001656std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001657 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001658 if (!S)
1659 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001660 auto Str = stringFromIslObj(S);
1661 isl_map_free(S);
1662 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001663}
1664
Johannes Doerferta3519512016-04-23 13:02:23 +00001665void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1666 isl_set_free(InvalidDomain);
1667 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001668}
1669
Michael Kruse375cb5f2016-02-24 22:08:24 +00001670BasicBlock *ScopStmt::getEntryBlock() const {
1671 if (isBlockStmt())
1672 return getBasicBlock();
1673 return getRegion()->getEntry();
1674}
1675
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001676unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001677
Tobias Grosser75805372011-04-29 06:27:02 +00001678const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1679
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001680Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001681 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001682}
1683
Tobias Grosser74394f02013-01-14 22:40:23 +00001684isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001685
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001686__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001687
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001688__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001689 return isl_set_get_space(Domain);
1690}
1691
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001692__isl_give isl_id *ScopStmt::getDomainId() const {
1693 return isl_set_get_tuple_id(Domain);
1694}
Tobias Grossercd95b772012-08-30 11:49:38 +00001695
Johannes Doerfert7c013572016-04-12 09:57:34 +00001696ScopStmt::~ScopStmt() {
1697 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001698 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001699}
Tobias Grosser75805372011-04-29 06:27:02 +00001700
1701void ScopStmt::print(raw_ostream &OS) const {
1702 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001703 OS.indent(12) << "Domain :=\n";
1704
1705 if (Domain) {
1706 OS.indent(16) << getDomainStr() << ";\n";
1707 } else
1708 OS.indent(16) << "n/a\n";
1709
Tobias Grosser54839312015-04-21 11:37:25 +00001710 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001711
1712 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001713 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001714 } else
1715 OS.indent(16) << "n/a\n";
1716
Tobias Grosser083d3d32014-06-28 08:59:45 +00001717 for (MemoryAccess *Access : MemAccs)
1718 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001719}
1720
1721void ScopStmt::dump() const { print(dbgs()); }
1722
Michael Kruse10071822016-05-23 14:45:58 +00001723void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
1724 // Remove the memory accesses from this statement
1725 // together with all scalar accesses that were caused by it.
Michael Krusead28e5a2016-01-26 13:33:15 +00001726 // MK_Value READs have no access instruction, hence would not be removed by
1727 // this function. However, it is only used for invariant LoadInst accesses,
1728 // its arguments are always affine, hence synthesizable, and therefore there
1729 // are no MK_Value READ accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001730 auto Predicate = [&](MemoryAccess *Acc) {
1731 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1732 };
1733 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1734 MemAccs.end());
1735 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001736}
1737
Tobias Grosser75805372011-04-29 06:27:02 +00001738//===----------------------------------------------------------------------===//
1739/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001740
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001741void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001742 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1743 isl_set_free(Context);
1744 Context = NewContext;
1745}
1746
Tobias Grosserc80d6972016-09-02 06:33:33 +00001747/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001748struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001749 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001750 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001751
1752public:
1753 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001754 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001755
1756 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1757 ValueToValueMap &VMap) {
1758 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1759 return SSPR.visit(E);
1760 }
1761
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001762 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1763 auto *Start = visit(E->getStart());
1764 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1765 visit(E->getStepRecurrence(SE)),
1766 E->getLoop(), SCEV::FlagAnyWrap);
1767 return SE.getAddExpr(Start, AddRec);
1768 }
1769
1770 const SCEV *visitUnknown(const SCEVUnknown *E) {
1771 if (auto *NewValue = VMap.lookup(E->getValue()))
1772 return SE.getUnknown(NewValue);
1773 return E;
1774 }
1775};
1776
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001777const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001778 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001779}
1780
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001781void Scop::createParameterId(const SCEV *Parameter) {
1782 assert(Parameters.count(Parameter));
1783 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001784
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001785 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001786
Tobias Grosser8f99c162011-11-15 11:38:55 +00001787 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1788 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001789
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001790 // If this parameter references a specific Value and this value has a name
1791 // we use this name as it is likely to be unique and more useful than just
1792 // a number.
1793 if (Val->hasName())
1794 ParameterName = Val->getName();
1795 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001796 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001797 if (LoadOrigin->hasName()) {
1798 ParameterName += "_loaded_from_";
1799 ParameterName +=
1800 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1801 }
1802 }
1803 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001804
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001805 ParameterName = getIslCompatibleName("", ParameterName, "");
1806
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001807 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1808 const_cast<void *>((const void *)Parameter));
1809 ParameterIds[Parameter] = Id;
1810}
1811
1812void Scop::addParams(const ParameterSetTy &NewParameters) {
1813 for (const SCEV *Parameter : NewParameters) {
1814 // Normalize the SCEV to get the representing element for an invariant load.
1815 Parameter = extractConstantFactor(Parameter, *SE).second;
1816 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1817
1818 if (Parameters.insert(Parameter))
1819 createParameterId(Parameter);
1820 }
1821}
1822
1823__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1824 // Normalize the SCEV to get the representing element for an invariant load.
1825 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1826 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001827}
Tobias Grosser75805372011-04-29 06:27:02 +00001828
Michael Krused56b90a2016-09-01 09:03:27 +00001829__isl_give isl_set *
1830Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001831 isl_set *DomainContext = isl_union_set_params(getDomains());
1832 return isl_set_intersect_params(C, DomainContext);
1833}
1834
Johannes Doerferte0b08072016-05-23 12:43:44 +00001835bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1836 return DT.dominates(BB, getEntry());
1837}
1838
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001839void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1840 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001841 auto &F = getFunction();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001842 for (auto &Assumption : AC.assumptions()) {
1843 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1844 if (!CI || CI->getNumArgOperands() != 1)
1845 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001846
Johannes Doerfert952b5302016-05-23 12:40:48 +00001847 bool InScop = contains(CI);
Johannes Doerferte0b08072016-05-23 12:43:44 +00001848 if (!InScop && !isDominatedBy(DT, CI->getParent()))
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001849 continue;
1850
Michael Kruse09eb4452016-03-03 22:10:47 +00001851 auto *L = LI.getLoopFor(CI->getParent());
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001852 auto *Val = CI->getArgOperand(0);
Johannes Doerfertf560b3d2016-04-25 13:33:07 +00001853 ParameterSetTy DetectedParams;
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001854 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001855 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1856 CI->getDebugLoc(),
1857 "Non-affine user assumption ignored.");
1858 continue;
1859 }
1860
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001861 // Collect all newly introduced parameters.
1862 ParameterSetTy NewParams;
1863 for (auto *Param : DetectedParams) {
1864 Param = extractConstantFactor(Param, *SE).second;
1865 Param = getRepresentingInvariantLoadSCEV(Param);
1866 if (Parameters.count(Param))
1867 continue;
1868 NewParams.insert(Param);
1869 }
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001870
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001871 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001872 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
1873 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
1874 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001875 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
1876 isl_set_free(Dom);
1877
1878 if (!Valid)
Johannes Doerfert297c7202016-05-10 13:06:42 +00001879 continue;
1880
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001881 isl_set *AssumptionCtx = nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001882 if (InScop) {
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001883 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
1884 isl_set_free(ConditionSets[0]);
1885 } else {
1886 AssumptionCtx = isl_set_complement(ConditionSets[1]);
1887 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
1888 }
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001889
1890 // Project out newly introduced parameters as they are not otherwise useful.
1891 if (!NewParams.empty()) {
1892 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
1893 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
1894 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
1895 isl_id_free(Id);
1896
1897 if (!NewParams.count(Param))
1898 continue;
1899
1900 AssumptionCtx =
1901 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
1902 }
1903 }
1904
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001905 emitOptimizationRemarkAnalysis(
1906 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1907 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1908 Context = isl_set_intersect(Context, AssumptionCtx);
1909 }
1910}
1911
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001912void Scop::addUserContext() {
1913 if (UserContextStr.empty())
1914 return;
1915
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001916 isl_set *UserContext =
1917 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001918 isl_space *Space = getParamSpace();
1919 if (isl_space_dim(Space, isl_dim_param) !=
1920 isl_set_dim(UserContext, isl_dim_param)) {
1921 auto SpaceStr = isl_space_to_str(Space);
1922 errs() << "Error: the context provided in -polly-context has not the same "
1923 << "number of dimensions than the computed context. Due to this "
1924 << "mismatch, the -polly-context option is ignored. Please provide "
1925 << "the context in the parameter space: " << SpaceStr << ".\n";
1926 free(SpaceStr);
1927 isl_set_free(UserContext);
1928 isl_space_free(Space);
1929 return;
1930 }
1931
1932 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001933 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1934 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001935
1936 if (strcmp(NameContext, NameUserContext) != 0) {
1937 auto SpaceStr = isl_space_to_str(Space);
1938 errs() << "Error: the name of dimension " << i
1939 << " provided in -polly-context "
1940 << "is '" << NameUserContext << "', but the name in the computed "
1941 << "context is '" << NameContext
1942 << "'. Due to this name mismatch, "
1943 << "the -polly-context option is ignored. Please provide "
1944 << "the context in the parameter space: " << SpaceStr << ".\n";
1945 free(SpaceStr);
1946 isl_set_free(UserContext);
1947 isl_space_free(Space);
1948 return;
1949 }
1950
1951 UserContext =
1952 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1953 isl_space_get_dim_id(Space, isl_dim_param, i));
1954 }
1955
1956 Context = isl_set_intersect(Context, UserContext);
1957 isl_space_free(Space);
1958}
1959
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001960void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001961 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001962
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001963 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001964 for (LoadInst *LInst : RIL) {
1965 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1966
Johannes Doerfert96e54712016-02-07 17:30:13 +00001967 Type *Ty = LInst->getType();
1968 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001969 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001970 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001971 continue;
1972 }
1973
1974 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00001975 InvariantEquivClasses.emplace_back(
1976 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001977 }
1978}
1979
Tobias Grosser6be480c2011-11-08 15:41:13 +00001980void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001981 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001982 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001983 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00001984 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001985}
1986
Tobias Grosser18daaca2012-05-22 10:47:27 +00001987void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001988 unsigned PDim = 0;
1989 for (auto *Parameter : Parameters) {
1990 ConstantRange SRange = SE->getSignedRange(Parameter);
1991 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001992 }
1993}
1994
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001995void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001996 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001997 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001998
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001999 unsigned PDim = 0;
2000 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002001 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002002 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002003 }
2004
2005 // Align the parameters of all data structures to the model.
2006 Context = isl_set_align_params(Context, Space);
2007
Johannes Doerferta60ad842016-05-10 12:18:22 +00002008 // As all parameters are known add bounds to them.
2009 addParameterBounds();
2010
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002011 for (ScopStmt &Stmt : *this)
2012 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002013
2014 // Simplify the schedule according to the context too.
2015 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002016}
2017
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002018static __isl_give isl_set *
2019simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2020 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002021 // If we modelt all blocks in the SCoP that have side effects we can simplify
2022 // the context with the constraints that are needed for anything to be
2023 // executed at all. However, if we have error blocks in the SCoP we already
2024 // assumed some parameter combinations cannot occure and removed them from the
2025 // domains, thus we cannot use the remaining domain to simplify the
2026 // assumptions.
2027 if (!S.hasErrorBlock()) {
2028 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2029 AssumptionContext =
2030 isl_set_gist_params(AssumptionContext, DomainParameters);
2031 }
2032
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002033 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2034 return AssumptionContext;
2035}
2036
2037void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002038 // The parameter constraints of the iteration domains give us a set of
2039 // constraints that need to hold for all cases where at least a single
2040 // statement iteration is executed in the whole scop. We now simplify the
2041 // assumed context under the assumption that such constraints hold and at
2042 // least a single statement iteration is executed. For cases where no
2043 // statement instances are executed, the assumptions we have taken about
2044 // the executed code do not matter and can be changed.
2045 //
2046 // WARNING: This only holds if the assumptions we have taken do not reduce
2047 // the set of statement instances that are executed. Otherwise we
2048 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002049 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002050 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002051 // performed. In such a case, modifying the run-time conditions and
2052 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002053 // to not be executed.
2054 //
2055 // Example:
2056 //
2057 // When delinearizing the following code:
2058 //
2059 // for (long i = 0; i < 100; i++)
2060 // for (long j = 0; j < m; j++)
2061 // A[i+p][j] = 1.0;
2062 //
2063 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002064 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002065 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002066 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002067 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002068}
2069
Tobias Grosserc80d6972016-09-02 06:33:33 +00002070/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002071static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002072 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2073 isl_pw_multi_aff *MinPMA, *MaxPMA;
2074 isl_pw_aff *LastDimAff;
2075 isl_aff *OneAff;
2076 unsigned Pos;
2077
Johannes Doerfert6296d952016-04-22 11:38:19 +00002078 Set = isl_set_remove_divs(Set);
2079
Michael Krusebc150122016-05-02 12:25:18 +00002080 if (isl_set_n_basic_set(Set) >= MaxDisjunctionsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002081 isl_set_free(Set);
2082 return isl_stat_error;
2083 }
2084
Johannes Doerfert9143d672014-09-27 11:02:39 +00002085 // Restrict the number of parameters involved in the access as the lexmin/
2086 // lexmax computation will take too long if this number is high.
2087 //
2088 // Experiments with a simple test case using an i7 4800MQ:
2089 //
2090 // #Parameters involved | Time (in sec)
2091 // 6 | 0.01
2092 // 7 | 0.04
2093 // 8 | 0.12
2094 // 9 | 0.40
2095 // 10 | 1.54
2096 // 11 | 6.78
2097 // 12 | 30.38
2098 //
2099 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2100 unsigned InvolvedParams = 0;
2101 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2102 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2103 InvolvedParams++;
2104
2105 if (InvolvedParams > RunTimeChecksMaxParameters) {
2106 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002107 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002108 }
2109 }
2110
Johannes Doerfertb164c792014-09-18 11:17:17 +00002111 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2112 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2113
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002114 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2115 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2116
Johannes Doerfertb164c792014-09-18 11:17:17 +00002117 // Adjust the last dimension of the maximal access by one as we want to
2118 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2119 // we test during code generation might now point after the end of the
2120 // allocated array but we will never dereference it anyway.
2121 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2122 "Assumed at least one output dimension");
2123 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2124 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2125 OneAff = isl_aff_zero_on_domain(
2126 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2127 OneAff = isl_aff_add_constant_si(OneAff, 1);
2128 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2129 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2130
2131 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2132
2133 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002134 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002135}
2136
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002137static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2138 isl_set *Domain = MA->getStatement()->getDomain();
2139 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2140 return isl_set_reset_tuple_id(Domain);
2141}
2142
Tobias Grosserc80d6972016-09-02 06:33:33 +00002143/// Wrapper function to calculate minimal/maximal accesses to each array.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002144static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002145 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002146 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002147
2148 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2149 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002150 Locations = isl_union_set_coalesce(Locations);
2151 Locations = isl_union_set_detect_equalities(Locations);
2152 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002153 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002154 isl_union_set_free(Locations);
2155 return Valid;
2156}
2157
Tobias Grosserc80d6972016-09-02 06:33:33 +00002158/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002159///
2160///{
2161
Tobias Grosserc80d6972016-09-02 06:33:33 +00002162/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002163static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2164 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2165 : RN->getNodeAs<BasicBlock>();
2166}
2167
Tobias Grosserc80d6972016-09-02 06:33:33 +00002168/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002169static inline BasicBlock *
2170getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002171 if (RN->isSubRegion()) {
2172 assert(idx == 0);
2173 return RN->getNodeAs<Region>()->getExit();
2174 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002175 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002176}
2177
Tobias Grosserc80d6972016-09-02 06:33:33 +00002178/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002179static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2180 if (!RN->isSubRegion())
2181 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2182
2183 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2184 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2185 while (L && NonAffineSubRegion->contains(L))
2186 L = L->getParentLoop();
2187 return L;
2188}
2189
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002190static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2191 if (!RN->isSubRegion())
2192 return 1;
2193
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002194 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002195 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002196}
2197
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002198static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2199 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002200 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002201 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002202 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002203 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002204 return true;
2205 return false;
2206}
2207
Johannes Doerfert96425c22015-08-30 21:13:53 +00002208///}
2209
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002210static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2211 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002212 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002213 isl_id *DimId =
2214 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2215 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2216}
2217
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002218__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002219 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002220}
2221
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002222__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002223 auto DIt = DomainMap.find(BB);
2224 if (DIt != DomainMap.end())
2225 return isl_set_copy(DIt->getSecond());
2226
2227 auto &RI = *R.getRegionInfo();
2228 auto *BBR = RI.getRegionFor(BB);
2229 while (BBR->getEntry() == BB)
2230 BBR = BBR->getParent();
2231 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002232}
2233
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002234bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002235
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002236 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002237 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002238 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2239 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002240 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002241
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002242 while (LD-- >= 0) {
2243 S = addDomainDimId(S, LD + 1, L);
2244 L = L->getParentLoop();
2245 }
2246
Johannes Doerferta3519512016-04-23 13:02:23 +00002247 // Initialize the invalid domain.
2248 auto *EntryStmt = getStmtFor(EntryBB);
2249 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2250
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002251 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002252
Johannes Doerfert432658d2016-01-26 11:01:41 +00002253 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002254 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002255
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002256 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002257 return false;
2258
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002259 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002260 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002261
2262 // Error blocks and blocks dominated by them have been assumed to never be
2263 // executed. Representing them in the Scop does not add any value. In fact,
2264 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002265 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002266 // will cause problems when building up a ScopStmt for them.
2267 // Furthermore, basic blocks dominated by error blocks may reference
2268 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002269 // can themselves not be constructed properly. To this end we will replace
2270 // the domains of error blocks and those only reachable via error blocks
2271 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002272 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002273 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002274 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002275 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002276
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002277 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002278}
2279
Michael Kruse586e5792016-07-08 12:38:28 +00002280// If the loop is nonaffine/boxed, return the first non-boxed surrounding loop
2281// for Polly. If the loop is affine, return the loop itself. Do not call
2282// `getSCEVAtScope()` on the result of `getFirstNonBoxedLoopFor()`, as we need
2283// to analyze the memory accesses of the nonaffine/boxed loops.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002284static Loop *getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI,
2285 const BoxedLoopsSetTy &BoxedLoops) {
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002286 auto *L = LI.getLoopFor(BB);
2287 while (BoxedLoops.count(L))
2288 L = L->getParentLoop();
2289 return L;
2290}
2291
Tobias Grosserc80d6972016-09-02 06:33:33 +00002292/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002293/// to be compatible to domains constructed for loop @p NewL.
2294///
2295/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2296/// edge from @p OldL to @p NewL.
2297static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2298 __isl_take isl_set *Dom,
2299 Loop *OldL, Loop *NewL) {
2300
2301 // If the loops are the same there is nothing to do.
2302 if (NewL == OldL)
2303 return Dom;
2304
2305 int OldDepth = S.getRelativeLoopDepth(OldL);
2306 int NewDepth = S.getRelativeLoopDepth(NewL);
2307 // If both loops are non-affine loops there is nothing to do.
2308 if (OldDepth == -1 && NewDepth == -1)
2309 return Dom;
2310
2311 // Distinguish three cases:
2312 // 1) The depth is the same but the loops are not.
2313 // => One loop was left one was entered.
2314 // 2) The depth increased from OldL to NewL.
2315 // => One loop was entered, none was left.
2316 // 3) The depth decreased from OldL to NewL.
2317 // => Loops were left were difference of the depths defines how many.
2318 if (OldDepth == NewDepth) {
2319 assert(OldL->getParentLoop() == NewL->getParentLoop());
2320 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2321 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2322 Dom = addDomainDimId(Dom, NewDepth, NewL);
2323 } else if (OldDepth < NewDepth) {
2324 assert(OldDepth + 1 == NewDepth);
2325 auto &R = S.getRegion();
2326 (void)R;
2327 assert(NewL->getParentLoop() == OldL ||
2328 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2329 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2330 Dom = addDomainDimId(Dom, NewDepth, NewL);
2331 } else {
2332 assert(OldDepth > NewDepth);
2333 int Diff = OldDepth - NewDepth;
2334 int NumDim = isl_set_n_dim(Dom);
2335 assert(NumDim >= Diff);
2336 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2337 }
2338
2339 return Dom;
2340}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002341
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002342bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2343 LoopInfo &LI) {
2344 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002345
2346 ReversePostOrderTraversal<Region *> RTraversal(R);
2347 for (auto *RN : RTraversal) {
2348
2349 // Recurse for affine subregions but go on for basic blocks and non-affine
2350 // subregions.
2351 if (RN->isSubRegion()) {
2352 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002353 if (!isNonAffineSubRegion(SubRegion)) {
2354 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002355 continue;
2356 }
2357 }
2358
2359 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2360 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002361 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002362 isl_set *&Domain = DomainMap[BB];
2363 assert(Domain && "Cannot propagate a nullptr");
2364
Johannes Doerferta3519512016-04-23 13:02:23 +00002365 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002366 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002367 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002368
Johannes Doerferta3519512016-04-23 13:02:23 +00002369 if (!IsInvalidBlock) {
2370 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002371 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002372 isl_set_free(InvalidDomain);
2373 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002374 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2375 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2376 AS_RESTRICTION);
2377 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002378 }
2379
Johannes Doerferta3519512016-04-23 13:02:23 +00002380 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002381 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002382 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002383 }
2384
Johannes Doerferta3519512016-04-23 13:02:23 +00002385 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002386 auto *TI = BB->getTerminator();
2387 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2388 for (unsigned u = 0; u < NumSuccs; u++) {
2389 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002390 auto *SuccStmt = getStmtFor(SuccBB);
2391
2392 // Skip successors outside the SCoP.
2393 if (!SuccStmt)
2394 continue;
2395
Johannes Doerferte4459a22016-04-25 13:34:50 +00002396 // Skip backedges.
2397 if (DT.dominates(SuccBB, BB))
2398 continue;
2399
Johannes Doerferta3519512016-04-23 13:02:23 +00002400 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2401 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2402 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2403 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2404 SuccInvalidDomain =
2405 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2406 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2407 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2408 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002409
Michael Krusebc150122016-05-02 12:25:18 +00002410 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002411 // In case this happens we will bail.
Michael Krusebc150122016-05-02 12:25:18 +00002412 if (NumConjucts < MaxDisjunctionsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002413 continue;
2414
Johannes Doerferta3519512016-04-23 13:02:23 +00002415 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002416 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002417 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002418 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002419
2420 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002421 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002422
2423 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002424}
2425
Johannes Doerfert642594a2016-04-04 07:57:39 +00002426void Scop::propagateDomainConstraintsToRegionExit(
2427 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002428 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002429
2430 // Check if the block @p BB is the entry of a region. If so we propagate it's
2431 // domain to the exit block of the region. Otherwise we are done.
2432 auto *RI = R.getRegionInfo();
2433 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2434 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002435 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002436 return;
2437
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002438 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002439 // Do not propagate the domain if there is a loop backedge inside the region
2440 // that would prevent the exit block from beeing executed.
2441 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002442 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002443 SmallVector<BasicBlock *, 4> LatchBBs;
2444 BBLoop->getLoopLatches(LatchBBs);
2445 for (auto *LatchBB : LatchBBs)
2446 if (BB != LatchBB && BBReg->contains(LatchBB))
2447 return;
2448 L = L->getParentLoop();
2449 }
2450
2451 auto *Domain = DomainMap[BB];
2452 assert(Domain && "Cannot propagate a nullptr");
2453
2454 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2455
2456 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2457 // adjust the domain before we can propagate it.
2458 auto *AdjustedDomain =
2459 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2460 auto *&ExitDomain = DomainMap[ExitBB];
2461
2462 // If the exit domain is not yet created we set it otherwise we "add" the
2463 // current domain.
2464 ExitDomain =
2465 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2466
Johannes Doerferta3519512016-04-23 13:02:23 +00002467 // Initialize the invalid domain.
2468 auto *ExitStmt = getStmtFor(ExitBB);
2469 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2470
Johannes Doerfert642594a2016-04-04 07:57:39 +00002471 FinishedExitBlocks.insert(ExitBB);
2472}
2473
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002474bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2475 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002476 // To create the domain for each block in R we iterate over all blocks and
2477 // subregions in R and propagate the conditions under which the current region
2478 // element is executed. To this end we iterate in reverse post order over R as
2479 // it ensures that we first visit all predecessors of a region node (either a
2480 // basic block or a subregion) before we visit the region node itself.
2481 // Initially, only the domain for the SCoP region entry block is set and from
2482 // there we propagate the current domain to all successors, however we add the
2483 // condition that the successor is actually executed next.
2484 // As we are only interested in non-loop carried constraints here we can
2485 // simply skip loop back edges.
2486
Johannes Doerfert642594a2016-04-04 07:57:39 +00002487 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002488 ReversePostOrderTraversal<Region *> RTraversal(R);
2489 for (auto *RN : RTraversal) {
2490
2491 // Recurse for affine subregions but go on for basic blocks and non-affine
2492 // subregions.
2493 if (RN->isSubRegion()) {
2494 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002495 if (!isNonAffineSubRegion(SubRegion)) {
2496 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002497 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002498 continue;
2499 }
2500 }
2501
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002502 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002503 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002504
Johannes Doerfert96425c22015-08-30 21:13:53 +00002505 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002506 TerminatorInst *TI = BB->getTerminator();
2507
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002508 if (isa<UnreachableInst>(TI))
2509 continue;
2510
Johannes Doerfertf5673802015-10-01 23:48:18 +00002511 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002512 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002513 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002514 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002515
Johannes Doerfert642594a2016-04-04 07:57:39 +00002516 auto *BBLoop = getRegionNodeLoop(RN, LI);
2517 // Propagate the domain from BB directly to blocks that have a superset
2518 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002519 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002520
2521 // If all successors of BB have been set a domain through the propagation
2522 // above we do not need to build condition sets but can just skip this
2523 // block. However, it is important to note that this is a local property
2524 // with regards to the region @p R. To this end FinishedExitBlocks is a
2525 // local variable.
2526 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2527 return FinishedExitBlocks.count(SuccBB);
2528 };
2529 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2530 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002531
2532 // Build the condition sets for the successor nodes of the current region
2533 // node. If it is a non-affine subregion we will always execute the single
2534 // exit node, hence the single entry node domain is the condition set. For
2535 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002536 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002537 if (RN->isSubRegion())
2538 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002539 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2540 ConditionSets))
2541 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002542
2543 // Now iterate over the successors and set their initial domain based on
2544 // their condition set. We skip back edges here and have to be careful when
2545 // we leave a loop not to keep constraints over a dimension that doesn't
2546 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002547 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002548 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002549 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002550 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002551
Johannes Doerfert535de032016-04-19 14:49:05 +00002552 auto *SuccStmt = getStmtFor(SuccBB);
2553 // Skip blocks outside the region.
2554 if (!SuccStmt) {
2555 isl_set_free(CondSet);
2556 continue;
2557 }
2558
Johannes Doerfert642594a2016-04-04 07:57:39 +00002559 // If we propagate the domain of some block to "SuccBB" we do not have to
2560 // adjust the domain.
2561 if (FinishedExitBlocks.count(SuccBB)) {
2562 isl_set_free(CondSet);
2563 continue;
2564 }
2565
Johannes Doerfert96425c22015-08-30 21:13:53 +00002566 // Skip back edges.
2567 if (DT.dominates(SuccBB, BB)) {
2568 isl_set_free(CondSet);
2569 continue;
2570 }
2571
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002572 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002573 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002574 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002575
2576 // Set the domain for the successor or merge it with an existing domain in
2577 // case there are multiple paths (without loop back edges) to the
2578 // successor block.
2579 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002580
Johannes Doerferta3519512016-04-23 13:02:23 +00002581 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002582 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002583 } else {
2584 // Initialize the invalid domain.
2585 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2586 SuccDomain = CondSet;
2587 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002588
Michael Krusebc150122016-05-02 12:25:18 +00002589 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002590 // In case this happens we will clean up and bail.
Michael Krusebc150122016-05-02 12:25:18 +00002591 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctionsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002592 continue;
2593
2594 invalidate(COMPLEXITY, DebugLoc());
2595 while (++u < ConditionSets.size())
2596 isl_set_free(ConditionSets[u]);
2597 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002598 }
2599 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002600
2601 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002602}
2603
Michael Krused56b90a2016-09-01 09:03:27 +00002604__isl_give isl_set *
2605Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2606 __isl_keep isl_set *Domain,
2607 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002608 // If @p BB is the ScopEntry we are done
2609 if (R.getEntry() == BB)
2610 return isl_set_universe(isl_set_get_space(Domain));
2611
2612 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002613 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002614
2615 // The region info of this function.
2616 auto &RI = *R.getRegionInfo();
2617
2618 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2619
2620 // A domain to collect all predecessor domains, thus all conditions under
2621 // which the block is executed. To this end we start with the empty domain.
2622 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2623
2624 // Set of regions of which the entry block domain has been propagated to BB.
2625 // all predecessors inside any of the regions can be skipped.
2626 SmallSet<Region *, 8> PropagatedRegions;
2627
2628 for (auto *PredBB : predecessors(BB)) {
2629 // Skip backedges.
2630 if (DT.dominates(BB, PredBB))
2631 continue;
2632
2633 // If the predecessor is in a region we used for propagation we can skip it.
2634 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2635 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2636 PredBBInRegion)) {
2637 continue;
2638 }
2639
2640 // Check if there is a valid region we can use for propagation, thus look
2641 // for a region that contains the predecessor and has @p BB as exit block.
2642 auto *PredR = RI.getRegionFor(PredBB);
2643 while (PredR->getExit() != BB && !PredR->contains(BB))
2644 PredR->getParent();
2645
2646 // If a valid region for propagation was found use the entry of that region
2647 // for propagation, otherwise the PredBB directly.
2648 if (PredR->getExit() == BB) {
2649 PredBB = PredR->getEntry();
2650 PropagatedRegions.insert(PredR);
2651 }
2652
Johannes Doerfert41cda152016-04-08 10:32:26 +00002653 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002654 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2655 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2656
2657 PredDom = isl_set_union(PredDom, PredBBDom);
2658 }
2659
2660 return PredDom;
2661}
2662
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002663bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2664 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002665 // Iterate over the region R and propagate the domain constrains from the
2666 // predecessors to the current node. In contrast to the
2667 // buildDomainsWithBranchConstraints function, this one will pull the domain
2668 // information from the predecessors instead of pushing it to the successors.
2669 // Additionally, we assume the domains to be already present in the domain
2670 // map here. However, we iterate again in reverse post order so we know all
2671 // predecessors have been visited before a block or non-affine subregion is
2672 // visited.
2673
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002674 ReversePostOrderTraversal<Region *> RTraversal(R);
2675 for (auto *RN : RTraversal) {
2676
2677 // Recurse for affine subregions but go on for basic blocks and non-affine
2678 // subregions.
2679 if (RN->isSubRegion()) {
2680 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002681 if (!isNonAffineSubRegion(SubRegion)) {
2682 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002683 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002684 continue;
2685 }
2686 }
2687
2688 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002689 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002690 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002691
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002692 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002693 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002694 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002695 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002696
Johannes Doerfert642594a2016-04-04 07:57:39 +00002697 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002698 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002699 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2700 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002701 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002702
2703 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002704}
2705
Tobias Grosserc80d6972016-09-02 06:33:33 +00002706/// Create a map to map from a given iteration to a subsequent iteration.
2707///
2708/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2709/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002710/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002711///
2712/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002713static __isl_give isl_map *
2714createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2715 auto *MapSpace = isl_space_map_from_set(SetSpace);
2716 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2717 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2718 if (u != Dim)
2719 NextIterationMap =
2720 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2721 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2722 C = isl_constraint_set_constant_si(C, 1);
2723 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2724 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2725 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2726 return NextIterationMap;
2727}
2728
Johannes Doerfert297c7202016-05-10 13:06:42 +00002729bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002730 int LoopDepth = getRelativeLoopDepth(L);
2731 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002732
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002733 BasicBlock *HeaderBB = L->getHeader();
2734 assert(DomainMap.count(HeaderBB));
2735 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002736
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002737 isl_map *NextIterationMap =
2738 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002739
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002740 isl_set *UnionBackedgeCondition =
2741 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002742
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002743 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2744 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002745
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002746 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002747
2748 // If the latch is only reachable via error statements we skip it.
2749 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2750 if (!LatchBBDom)
2751 continue;
2752
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002753 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002754
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002755 TerminatorInst *TI = LatchBB->getTerminator();
2756 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00002757 assert(BI && "Only branch instructions allowed in loop latches");
2758
2759 if (BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002760 BackedgeCondition = isl_set_copy(LatchBBDom);
2761 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002762 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002763 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002764 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
Michael Krusee1dc3872016-11-03 15:19:41 +00002765 ConditionSets)) {
2766 isl_map_free(NextIterationMap);
2767 isl_set_free(UnionBackedgeCondition);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002768 return false;
Michael Krusee1dc3872016-11-03 15:19:41 +00002769 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002770
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002771 // Free the non back edge condition set as we do not need it.
2772 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002773
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002774 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002775 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002776
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002777 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2778 assert(LatchLoopDepth >= LoopDepth);
2779 BackedgeCondition =
2780 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2781 LatchLoopDepth - LoopDepth);
2782 UnionBackedgeCondition =
2783 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002784 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002785
2786 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2787 for (int i = 0; i < LoopDepth; i++)
2788 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2789
2790 isl_set *UnionBackedgeConditionComplement =
2791 isl_set_complement(UnionBackedgeCondition);
2792 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2793 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2794 UnionBackedgeConditionComplement =
2795 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2796 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2797 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2798
2799 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2800 HeaderBBDom = Parts.second;
2801
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002802 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2803 // the bounded assumptions to the context as they are already implied by the
2804 // <nsw> tag.
2805 if (Affinator.hasNSWAddRecForLoop(L)) {
2806 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002807 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002808 }
2809
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002810 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002811 recordAssumption(INFINITELOOP, UnboundedCtx,
2812 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002813 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002814}
2815
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002816MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
2817 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2818 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2819 if (!PointerBase)
2820 return nullptr;
2821
2822 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase->getValue());
2823 if (!PointerBaseInst)
2824 return nullptr;
2825
2826 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2827 if (!BasePtrStmt)
2828 return nullptr;
2829
2830 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2831}
2832
2833bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2834 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00002835 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
2836 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
2837 bool Hoistable = NHCtx != nullptr;
2838 isl_set_free(NHCtx);
2839 return !Hoistable;
2840 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002841
2842 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2843 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2844 if (auto *BasePtrInst = dyn_cast<Instruction>(PointerBase->getValue()))
2845 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00002846 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002847
2848 return false;
2849}
2850
Johannes Doerfert5210da52016-06-02 11:06:54 +00002851bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002852 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00002853 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002854
Johannes Doerfertcd195322016-11-17 21:41:08 +00002855 if (buildAliasGroups(AA)) {
2856 // Aliasing assumptions do not go through addAssumption but we still want to
2857 // collect statistics so we do it here explicitly.
2858 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00002859 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00002860 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00002861 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002862
2863 // If a problem occurs while building the alias groups we need to delete
2864 // this SCoP and pretend it wasn't valid in the first place. To this end
2865 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002866 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002867
2868 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2869 << " could not be created as the number of parameters involved "
2870 "is too high. The SCoP will be "
2871 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2872 "the maximal number of parameters but be advised that the "
2873 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00002874 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002875}
2876
Johannes Doerfert9143d672014-09-27 11:02:39 +00002877bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002878 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002879 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002880 // for all memory accesses inside the SCoP.
2881 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002882 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002883 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002884 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002885 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002886 // if their access domains intersect, otherwise they are in different
2887 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002888 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002889 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002890 // and maximal accesses to each array of a group in read only and non
2891 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002892 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2893
2894 AliasSetTracker AST(AA);
2895
2896 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002897 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002898 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002899
2900 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002901 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002902 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2903 isl_set_free(StmtDomain);
2904 if (StmtDomainEmpty)
2905 continue;
2906
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002907 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002908 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002909 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002910 if (!MA->isRead())
2911 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002912 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002913 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00002914 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002915 else
2916 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002917 AST.add(Acc);
2918 }
2919 }
2920
2921 SmallVector<AliasGroupTy, 4> AliasGroups;
2922 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002923 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002924 continue;
2925 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002926 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002927 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002928 if (AG.size() < 2)
2929 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002930 AliasGroups.push_back(std::move(AG));
2931 }
2932
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002933 // Split the alias groups based on their domain.
2934 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2935 AliasGroupTy NewAG;
2936 AliasGroupTy &AG = AliasGroups[u];
2937 AliasGroupTy::iterator AGI = AG.begin();
2938 isl_set *AGDomain = getAccessDomain(*AGI);
2939 while (AGI != AG.end()) {
2940 MemoryAccess *MA = *AGI;
2941 isl_set *MADomain = getAccessDomain(MA);
2942 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2943 NewAG.push_back(MA);
2944 AGI = AG.erase(AGI);
2945 isl_set_free(MADomain);
2946 } else {
2947 AGDomain = isl_set_union(AGDomain, MADomain);
2948 AGI++;
2949 }
2950 }
2951 if (NewAG.size() > 1)
2952 AliasGroups.push_back(std::move(NewAG));
2953 isl_set_free(AGDomain);
2954 }
2955
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002956 auto &F = getFunction();
Mandeep Singh Grang48e7add2016-10-21 17:29:10 +00002957 MapVector<const Value *, SmallSetVector<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002958 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2959 for (AliasGroupTy &AG : AliasGroups) {
2960 NonReadOnlyBaseValues.clear();
2961 ReadOnlyPairs.clear();
2962
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002963 if (AG.size() < 2) {
2964 AG.clear();
2965 continue;
2966 }
2967
Johannes Doerfert13771732014-10-01 12:40:46 +00002968 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002969 emitOptimizationRemarkAnalysis(
2970 F.getContext(), DEBUG_TYPE, F,
2971 (*II)->getAccessInstruction()->getDebugLoc(),
2972 "Possibly aliasing pointer, use restrict keyword.");
2973
Johannes Doerfert13771732014-10-01 12:40:46 +00002974 Value *BaseAddr = (*II)->getBaseAddr();
2975 if (HasWriteAccess.count(BaseAddr)) {
2976 NonReadOnlyBaseValues.insert(BaseAddr);
2977 II++;
2978 } else {
2979 ReadOnlyPairs[BaseAddr].insert(*II);
2980 II = AG.erase(II);
2981 }
2982 }
2983
2984 // If we don't have read only pointers check if there are at least two
2985 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002986 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002987 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002988 continue;
2989 }
2990
2991 // If we don't have non read only pointers clear the alias group.
2992 if (NonReadOnlyBaseValues.empty()) {
2993 AG.clear();
2994 continue;
2995 }
2996
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002997 // Check if we have non-affine accesses left, if so bail out as we cannot
2998 // generate a good access range yet.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002999 for (auto *MA : AG) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003000 if (!MA->isAffine()) {
3001 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3002 return false;
3003 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003004 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
3005 addRequiredInvariantLoad(
3006 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3007 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003008 for (auto &ReadOnlyPair : ReadOnlyPairs)
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003009 for (auto *MA : ReadOnlyPair.second) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003010 if (!MA->isAffine()) {
3011 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3012 return false;
3013 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003014 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
3015 addRequiredInvariantLoad(
3016 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3017 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003018
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003019 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003020 MinMaxAliasGroups.emplace_back();
3021 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3022 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
3023 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3024 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003025
3026 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003027
3028 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00003029 for (MemoryAccess *MA : AG)
3030 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003031
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003032 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
3033 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003034
3035 // Bail out if the number of values we need to compare is too large.
3036 // This is important as the number of comparisions grows quadratically with
3037 // the number of values we need to compare.
Johannes Doerfert5210da52016-06-02 11:06:54 +00003038 if (!Valid || (MinMaxAccessesNonReadOnly.size() + ReadOnlyPairs.size() >
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003039 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003040 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003041
3042 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003043 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003044 Accesses = isl_union_map_empty(getParamSpace());
3045
3046 for (const auto &ReadOnlyPair : ReadOnlyPairs)
3047 for (MemoryAccess *MA : ReadOnlyPair.second)
3048 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
3049
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003050 Valid =
3051 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003052
3053 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003054 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003055 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003056
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003057 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003058}
3059
Tobias Grosserc80d6972016-09-02 06:33:33 +00003060/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003061static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003062 // Start with the smallest loop containing the entry and expand that
3063 // loop until it contains all blocks in the region. If there is a loop
3064 // containing all blocks in the region check if it is itself contained
3065 // and if so take the parent loop as it will be the smallest containing
3066 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003067 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003068 while (L) {
3069 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003070 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003071 AllContained &= L->contains(BB);
3072 if (AllContained)
3073 break;
3074 L = L->getParentLoop();
3075 }
3076
Johannes Doerfertef744432016-05-23 12:42:38 +00003077 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003078}
3079
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003080Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003081 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003082 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003083 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003084 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3085 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3086 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3087 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003088 if (IslOnErrorAbort)
3089 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003090 buildContext();
3091}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003092
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003093void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT,
3094 LoopInfo &LI) {
3095 buildInvariantEquivalenceClasses();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003096
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003097 if (!buildDomains(&R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003098 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003099
Johannes Doerfertff68f462016-04-19 14:49:42 +00003100 addUserAssumptions(AC, DT, LI);
3101
Johannes Doerfert26404542016-05-10 12:19:47 +00003102 // Remove empty statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003103 // Exit early in case there are no executable statements left in this scop.
Michael Kruse977d38b2016-07-22 17:31:17 +00003104 simplifySCoP(false);
Michael Kruseafe06702015-10-02 16:33:27 +00003105 if (Stmts.empty())
3106 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003107
Michael Krusecac948e2015-10-02 13:53:07 +00003108 // The ScopStmts now have enough information to initialize themselves.
3109 for (ScopStmt &Stmt : Stmts)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003110 Stmt.init(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00003111
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003112 // Check early for profitability. Afterwards it cannot change anymore,
3113 // only the runtime context could become infeasible.
3114 if (!isProfitable()) {
3115 invalidate(PROFITABLE, DebugLoc());
Tobias Grosser8286b832015-11-02 11:29:32 +00003116 return;
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003117 }
3118
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003119 buildSchedule(LI);
Tobias Grosser8286b832015-11-02 11:29:32 +00003120
3121 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003122 realignParams();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003123 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003124
3125 // After the context was fully constructed, thus all our knowledge about
3126 // the parameters is in there, we add all recorded assumptions to the
3127 // assumed/invalid context.
3128 addRecordedAssumptions();
3129
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003130 simplifyContexts();
Johannes Doerfert5210da52016-06-02 11:06:54 +00003131 if (!buildAliasChecks(AA))
3132 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003133
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003134 hoistInvariantLoads();
3135 verifyInvariantLoads();
Michael Kruse977d38b2016-07-22 17:31:17 +00003136 simplifySCoP(true);
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003137
3138 // Check late for a feasible runtime context because profitability did not
3139 // change.
3140 if (!hasFeasibleRuntimeContext()) {
3141 invalidate(PROFITABLE, DebugLoc());
3142 return;
3143 }
Tobias Grosser75805372011-04-29 06:27:02 +00003144}
3145
3146Scop::~Scop() {
3147 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003148 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003149 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003150 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003151
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003152 for (auto &It : ParameterIds)
3153 isl_id_free(It.second);
3154
Johannes Doerfert96425c22015-08-30 21:13:53 +00003155 for (auto It : DomainMap)
3156 isl_set_free(It.second);
3157
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003158 for (auto &AS : RecordedAssumptions)
3159 isl_set_free(AS.Set);
3160
Johannes Doerfertb164c792014-09-18 11:17:17 +00003161 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003162 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003163 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003164 isl_pw_multi_aff_free(MMA.first);
3165 isl_pw_multi_aff_free(MMA.second);
3166 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003167 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003168 isl_pw_multi_aff_free(MMA.first);
3169 isl_pw_multi_aff_free(MMA.second);
3170 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003171 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003172
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003173 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003174 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003175
3176 // Explicitly release all Scop objects and the underlying isl objects before
3177 // we relase the isl context.
3178 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003179 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003180 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003181 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003182 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003183}
3184
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003185void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003186 // Check all array accesses for each base pointer and find a (virtual) element
3187 // size for the base pointer that divides all access functions.
3188 for (auto &Stmt : *this)
3189 for (auto *Access : Stmt) {
3190 if (!Access->isArrayKind())
3191 continue;
3192 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
3193 ScopArrayInfo::MK_Array)];
3194 if (SAI->getNumberOfDimensions() != 1)
3195 continue;
3196 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3197 auto *Subscript = Access->getSubscript(0);
3198 while (!isDivisible(Subscript, DivisibleSize, *SE))
3199 DivisibleSize /= 2;
3200 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3201 SAI->updateElementType(Ty);
3202 }
3203
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003204 for (auto &Stmt : *this)
3205 for (auto &Access : Stmt)
3206 Access->updateDimensionality();
3207}
3208
Michael Kruse977d38b2016-07-22 17:31:17 +00003209void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003210 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3211 ScopStmt &Stmt = *StmtIt;
3212
Johannes Doerfert26404542016-05-10 12:19:47 +00003213 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003214 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003215 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003216
Johannes Doerferteca9e892015-11-03 16:54:49 +00003217 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003218 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003219 bool OnlyRead = true;
3220 for (MemoryAccess *MA : Stmt) {
3221 if (MA->isRead())
3222 continue;
3223
3224 OnlyRead = false;
3225 break;
3226 }
3227
3228 RemoveStmt = OnlyRead;
3229 }
3230
Johannes Doerfert26404542016-05-10 12:19:47 +00003231 if (!RemoveStmt) {
3232 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003233 continue;
3234 }
3235
Johannes Doerfert26404542016-05-10 12:19:47 +00003236 // Remove the statement because it is unnecessary.
3237 if (Stmt.isRegionStmt())
3238 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3239 StmtMap.erase(BB);
3240 else
3241 StmtMap.erase(Stmt.getBasicBlock());
3242
3243 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003244 }
3245}
3246
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003247InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003248 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3249 if (!LInst)
3250 return nullptr;
3251
3252 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3253 LInst = cast<LoadInst>(Rep);
3254
Johannes Doerfert96e54712016-02-07 17:30:13 +00003255 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003256 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003257 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003258 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003259 continue;
3260
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003261 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003262 for (auto *MA : MAs)
3263 if (MA->getAccessInstruction() == Val)
3264 return &IAClass;
3265 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003266
3267 return nullptr;
3268}
3269
Tobias Grosserc80d6972016-09-02 06:33:33 +00003270/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003271static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003272 bool MAInvalidCtxIsEmpty,
3273 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003274 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3275 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3276 // TODO: We can provide more information for better but more expensive
3277 // results.
3278 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3279 LInst->getAlignment(), DL))
3280 return false;
3281
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003282 // If the location might be overwritten we do not hoist it unconditionally.
3283 //
3284 // TODO: This is probably to conservative.
3285 if (!NonHoistableCtxIsEmpty)
3286 return false;
3287
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003288 // If a dereferencable load is in a statement that is modeled precisely we can
3289 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003290 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003291 return true;
3292
3293 // Even if the statement is not modeled precisely we can hoist the load if it
3294 // does not involve any parameters that might have been specilized by the
3295 // statement domain.
3296 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3297 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3298 return false;
3299 return true;
3300}
3301
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003302void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003303
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003304 if (InvMAs.empty())
3305 return;
3306
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003307 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003308 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003309
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003310 // Get the context under which the statement is executed but remove the error
3311 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003312 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003313 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003314
Michael Krusebc150122016-05-02 12:25:18 +00003315 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctionsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003316 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003317 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3318 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003319 for (auto &InvMA : InvMAs)
3320 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003321 return;
3322 }
3323
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003324 // Project out all parameters that relate to loads in the statement. Otherwise
3325 // we could have cyclic dependences on the constraints under which the
3326 // hoisted loads are executed and we could not determine an order in which to
3327 // pre-load them. This happens because not only lower bounds are part of the
3328 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003329 for (auto &InvMA : InvMAs) {
3330 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003331 Instruction *AccInst = MA->getAccessInstruction();
3332 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003333 SetVector<Value *> Values;
3334 for (const SCEV *Parameter : Parameters) {
3335 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003336 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003337 if (!Values.count(AccInst))
3338 continue;
3339
3340 if (isl_id *ParamId = getIdForParam(Parameter)) {
3341 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3342 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3343 isl_id_free(ParamId);
3344 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003345 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003346 }
3347 }
3348
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003349 for (auto &InvMA : InvMAs) {
3350 auto *MA = InvMA.MA;
3351 auto *NHCtx = InvMA.NonHoistableCtx;
3352
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003353 // Check for another invariant access that accesses the same location as
3354 // MA and if found consolidate them. Otherwise create a new equivalence
3355 // class at the end of InvariantEquivClasses.
3356 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003357 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003358 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3359
Johannes Doerfert85676e32016-04-23 14:32:34 +00003360 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003361 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003362 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3363
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003364 isl_set *MACtx;
3365 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003366 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3367 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003368 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003369 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003370 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003371 } else {
3372 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003373 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003374 MACtx = isl_set_gist_params(MACtx, getContext());
3375 }
3376
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003377 bool Consolidated = false;
3378 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003379 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003380 continue;
3381
Johannes Doerfertdf880232016-03-03 12:26:58 +00003382 // If the pointer and the type is equal check if the access function wrt.
3383 // to the domain is equal too. It can happen that the domain fixes
3384 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003385 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003386 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003387 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003388 if (!MAs.empty()) {
3389 auto *LastMA = MAs.front();
3390
3391 auto *AR = isl_map_range(MA->getAccessRelation());
3392 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3393 bool SameAR = isl_set_is_equal(AR, LastAR);
3394 isl_set_free(AR);
3395 isl_set_free(LastAR);
3396
3397 if (!SameAR)
3398 continue;
3399 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003400
3401 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003402 MAs.push_front(MA);
3403
Johannes Doerfertdf880232016-03-03 12:26:58 +00003404 Consolidated = true;
3405
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003406 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003407 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003408 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003409 IAClassDomainCtx =
3410 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003411 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003412 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003413 break;
3414 }
3415
3416 if (Consolidated)
3417 continue;
3418
3419 // If we did not consolidate MA, thus did not find an equivalence class
3420 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003421 InvariantEquivClasses.emplace_back(
3422 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003423 }
3424
3425 isl_set_free(DomainCtx);
3426}
3427
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003428__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3429 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003430 // TODO: Loads that are not loop carried, hence are in a statement with
3431 // zero iterators, are by construction invariant, though we
3432 // currently "hoist" them anyway. This is necessary because we allow
3433 // them to be treated as parameters (e.g., in conditions) and our code
3434 // generation would otherwise use the old value.
3435
3436 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003437 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003438
Johannes Doerfertc9765462016-11-17 22:11:56 +00003439 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3440 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003441 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003442
3443 // Skip accesses that have an invariant base pointer which is defined but
3444 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3445 // returns a pointer that is used as a base address. However, as we want
3446 // to hoist indirect pointers, we allow the base pointer to be defined in
3447 // the region if it is also a memory access. Each ScopArrayInfo object
3448 // that has a base pointer origin has a base pointer that is loaded and
3449 // that it is invariant, thus it will be hoisted too. However, if there is
3450 // no base pointer origin we check that the base pointer is defined
3451 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003452 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003453 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003454 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003455
3456 // Skip accesses in non-affine subregions as they might not be executed
3457 // under the same condition as the entry of the non-affine subregion.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003458 if (BB != LI->getParent())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003459 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003460
3461 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003462 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003463
3464 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3465 Stmt.getNumIterators())) {
3466 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003467 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003468 }
3469
3470 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3471 isl_set *AccessRange = isl_map_range(AccessRelation);
3472
3473 isl_union_map *Written = isl_union_map_intersect_range(
3474 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003475 auto *WrittenCtx = isl_union_map_params(Written);
3476 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003477
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003478 if (!IsWritten)
3479 return WrittenCtx;
3480
3481 WrittenCtx = isl_set_remove_divs(WrittenCtx);
3482 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctionsInDomain;
3483 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3484 isl_set_free(WrittenCtx);
3485 return nullptr;
3486 }
3487
3488 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3489 AS_RESTRICTION);
3490 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003491}
3492
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003493void Scop::verifyInvariantLoads() {
3494 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003495 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003496 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003497 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003498 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003499 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3500 return;
3501 }
3502 }
3503}
3504
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003505void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003506 if (!PollyInvariantLoadHoisting)
3507 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003508
Tobias Grosser0865e7752016-02-29 07:29:42 +00003509 isl_union_map *Writes = getWrites();
3510 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003511 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003512
Tobias Grosser0865e7752016-02-29 07:29:42 +00003513 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003514 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3515 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003516
3517 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003518 for (auto InvMA : InvariantAccesses)
3519 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003520 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003521 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003522 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003523}
3524
Roman Gareevd7754a12016-07-30 09:25:51 +00003525const ScopArrayInfo *Scop::getOrCreateScopArrayInfo(
3526 Value *BasePtr, Type *ElementType, ArrayRef<const SCEV *> Sizes,
3527 ScopArrayInfo::MemoryKind Kind, const char *BaseName) {
3528 assert((BasePtr || BaseName) &&
3529 "BasePtr and BaseName can not be nullptr at the same time.");
3530 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3531 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3532 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003533 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003534 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003535 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003536 DL, this, BaseName));
3537 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003538 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003539 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003540 // In case of mismatching array sizes, we bail out by setting the run-time
3541 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003542 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003543 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003544 }
Tobias Grosserab671442015-05-23 05:58:27 +00003545 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003546}
3547
Roman Gareevd7754a12016-07-30 09:25:51 +00003548const ScopArrayInfo *
3549Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3550 const std::vector<unsigned> &Sizes) {
3551 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3552 std::vector<const SCEV *> SCEVSizes;
3553
3554 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003555 if (size)
3556 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3557 else
3558 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003559
3560 auto *SAI =
3561 getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3562 ScopArrayInfo::MK_Array, BaseName.c_str());
3563 return SAI;
3564}
3565
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003566const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003567 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003568 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003569 assert(SAI && "No ScopArrayInfo available for this base pointer");
3570 return SAI;
3571}
3572
Tobias Grosser74394f02013-01-14 22:40:23 +00003573std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003574
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003575std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003576 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003577 return stringFromIslObj(AssumedContext);
3578}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003579
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003580std::string Scop::getInvalidContextStr() const {
3581 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003582}
Tobias Grosser75805372011-04-29 06:27:02 +00003583
3584std::string Scop::getNameStr() const {
3585 std::string ExitName, EntryName;
3586 raw_string_ostream ExitStr(ExitName);
3587 raw_string_ostream EntryStr(EntryName);
3588
Tobias Grosserf240b482014-01-09 10:42:15 +00003589 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003590 EntryStr.str();
3591
3592 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003593 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003594 ExitStr.str();
3595 } else
3596 ExitName = "FunctionExit";
3597
3598 return EntryName + "---" + ExitName;
3599}
3600
Tobias Grosser74394f02013-01-14 22:40:23 +00003601__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003602__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003603 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003604}
3605
Tobias Grossere86109f2013-10-29 21:05:49 +00003606__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003607 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003608 return isl_set_copy(AssumedContext);
3609}
3610
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003611bool Scop::isProfitable() const {
3612 if (PollyProcessUnprofitable)
3613 return true;
3614
3615 if (!hasFeasibleRuntimeContext())
3616 return false;
3617
3618 if (isEmpty())
3619 return false;
3620
3621 unsigned OptimizableStmtsOrLoops = 0;
3622 for (auto &Stmt : *this) {
3623 if (Stmt.getNumIterators() == 0)
3624 continue;
3625
3626 bool ContainsArrayAccs = false;
3627 bool ContainsScalarAccs = false;
3628 for (auto *MA : Stmt) {
3629 if (MA->isRead())
3630 continue;
3631 ContainsArrayAccs |= MA->isArrayKind();
3632 ContainsScalarAccs |= MA->isScalarKind();
3633 }
3634
Michael Kruse6ab44762016-10-04 17:33:39 +00003635 if (!UnprofitableScalarAccs || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003636 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3637 }
3638
3639 return OptimizableStmtsOrLoops > 1;
3640}
3641
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003642bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003643 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003644 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003645 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3646 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3647 isl_set_is_subset(PositiveContext, NegativeContext));
3648 isl_set_free(PositiveContext);
3649 if (!IsFeasible) {
3650 isl_set_free(NegativeContext);
3651 return false;
3652 }
3653
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003654 auto *DomainContext = isl_union_set_params(getDomains());
3655 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003656 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003657 isl_set_free(NegativeContext);
3658 isl_set_free(DomainContext);
3659
Johannes Doerfert43788c52015-08-20 05:58:56 +00003660 return IsFeasible;
3661}
3662
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003663static std::string toString(AssumptionKind Kind) {
3664 switch (Kind) {
3665 case ALIASING:
3666 return "No-aliasing";
3667 case INBOUNDS:
3668 return "Inbounds";
3669 case WRAPPING:
3670 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00003671 case UNSIGNED:
3672 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003673 case COMPLEXITY:
3674 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003675 case PROFITABLE:
3676 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003677 case ERRORBLOCK:
3678 return "No-error";
3679 case INFINITELOOP:
3680 return "Finite loop";
3681 case INVARIANTLOAD:
3682 return "Invariant load";
3683 case DELINEARIZATION:
3684 return "Delinearization";
3685 }
3686 llvm_unreachable("Unknown AssumptionKind!");
3687}
3688
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003689bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
3690 if (Sign == AS_ASSUMPTION) {
3691 if (isl_set_is_subset(Context, Set))
3692 return false;
3693
3694 if (isl_set_is_subset(AssumedContext, Set))
3695 return false;
3696 } else {
3697 if (isl_set_is_disjoint(Set, Context))
3698 return false;
3699
3700 if (isl_set_is_subset(Set, InvalidContext))
3701 return false;
3702 }
3703 return true;
3704}
3705
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003706bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3707 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003708 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
3709 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003710
Johannes Doerfertb3265a32016-11-17 22:08:40 +00003711 // Do never emit trivial assumptions as they only clutter the output.
3712 if (!PollyRemarksMinimal) {
3713 isl_set *Univ = nullptr;
3714 if (Sign == AS_ASSUMPTION)
3715 Univ = isl_set_universe(isl_set_get_space(Set));
3716
3717 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
3718 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
3719 isl_set_free(Univ);
3720
3721 if (IsTrivial)
3722 return false;
3723 }
3724
Johannes Doerfertcd195322016-11-17 21:41:08 +00003725 switch (Kind) {
3726 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003727 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003728 break;
3729 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003730 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003731 break;
3732 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003733 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003734 break;
3735 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003736 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003737 break;
3738 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003739 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003740 break;
3741 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003742 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003743 break;
3744 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003745 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003746 break;
3747 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003748 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003749 break;
3750 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003751 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003752 break;
3753 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003754 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003755 break;
3756 }
3757
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003758 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003759 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3760 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003761 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003762 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003763}
3764
3765void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003766 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003767 // Simplify the assumptions/restrictions first.
3768 Set = isl_set_gist_params(Set, getContext());
3769
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003770 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3771 isl_set_free(Set);
3772 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003773 }
3774
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003775 if (Sign == AS_ASSUMPTION) {
3776 AssumedContext = isl_set_intersect(AssumedContext, Set);
3777 AssumedContext = isl_set_coalesce(AssumedContext);
3778 } else {
3779 InvalidContext = isl_set_union(InvalidContext, Set);
3780 InvalidContext = isl_set_coalesce(InvalidContext);
3781 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003782}
3783
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003784void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003785 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00003786 assert((isl_set_is_params(Set) || BB) &&
3787 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003788 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003789}
3790
3791void Scop::addRecordedAssumptions() {
3792 while (!RecordedAssumptions.empty()) {
3793 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003794
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003795 if (!AS.BB) {
3796 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
3797 continue;
3798 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003799
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003800 // If the domain was deleted the assumptions are void.
3801 isl_set *Dom = getDomainConditions(AS.BB);
3802 if (!Dom) {
3803 isl_set_free(AS.Set);
3804 continue;
3805 }
3806
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003807 // If a basic block was given use its domain to simplify the assumption.
3808 // In case of restrictions we know they only have to hold on the domain,
3809 // thus we can intersect them with the domain of the block. However, for
3810 // assumptions the domain has to imply them, thus:
3811 // _ _____
3812 // Dom => S <==> A v B <==> A - B
3813 //
3814 // To avoid the complement we will register A - B as a restricton not an
3815 // assumption.
3816 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003817 if (AS.Sign == AS_RESTRICTION)
3818 S = isl_set_params(isl_set_intersect(S, Dom));
3819 else /* (AS.Sign == AS_ASSUMPTION) */
3820 S = isl_set_params(isl_set_subtract(Dom, S));
3821
3822 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003823 }
3824}
3825
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003826void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003827 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003828}
3829
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003830__isl_give isl_set *Scop::getInvalidContext() const {
3831 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003832}
3833
Tobias Grosser75805372011-04-29 06:27:02 +00003834void Scop::printContext(raw_ostream &OS) const {
3835 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003836 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003837
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003838 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003839 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003840
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003841 OS.indent(4) << "Invalid Context:\n";
3842 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003843
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003844 unsigned Dim = 0;
3845 for (const SCEV *Parameter : Parameters)
3846 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003847}
3848
Johannes Doerfertb164c792014-09-18 11:17:17 +00003849void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003850 int noOfGroups = 0;
3851 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003852 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003853 noOfGroups += 1;
3854 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003855 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003856 }
3857
Tobias Grosserbb853c22015-07-25 12:31:03 +00003858 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003859 if (MinMaxAliasGroups.empty()) {
3860 OS.indent(8) << "n/a\n";
3861 return;
3862 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003863
Tobias Grosserbb853c22015-07-25 12:31:03 +00003864 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003865
3866 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003867 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003868 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003869 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003870 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3871 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003872 }
3873 OS << " ]]\n";
3874 }
3875
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003876 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003877 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003878 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003879 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003880 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3881 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003882 }
3883 OS << " ]]\n";
3884 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003885 }
3886}
3887
Tobias Grosser75805372011-04-29 06:27:02 +00003888void Scop::printStatements(raw_ostream &OS) const {
3889 OS << "Statements {\n";
3890
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003891 for (const ScopStmt &Stmt : *this)
3892 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003893
3894 OS.indent(4) << "}\n";
3895}
3896
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003897void Scop::printArrayInfo(raw_ostream &OS) const {
3898 OS << "Arrays {\n";
3899
Tobias Grosserab671442015-05-23 05:58:27 +00003900 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00003901 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003902
3903 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003904
3905 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3906
3907 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00003908 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003909
3910 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003911}
3912
Tobias Grosser75805372011-04-29 06:27:02 +00003913void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003914 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003915 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003916 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003917 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003918 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003919 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003920 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003921 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003922 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003923 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003924 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
3925 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003926 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003927 }
3928 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003929 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003930 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003931 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003932 printStatements(OS.indent(4));
3933}
3934
3935void Scop::dump() const { print(dbgs()); }
3936
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003937isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003938
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003939__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
3940 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003941 // First try to use the SCEVAffinator to generate a piecewise defined
3942 // affine function from @p E in the context of @p BB. If that tasks becomes to
3943 // complex the affinator might return a nullptr. In such a case we invalidate
3944 // the SCoP and return a dummy value. This way we do not need to add error
3945 // handling cdoe to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003946 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003947 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00003948 // TODO: We could use a heuristic and either use:
3949 // SCEVAffinator::takeNonNegativeAssumption
3950 // or
3951 // SCEVAffinator::interpretAsUnsigned
3952 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003953 if (NonNegative)
3954 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003955 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003956 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003957
3958 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
3959 invalidate(COMPLEXITY, DL);
3960 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003961}
3962
Tobias Grosser808cd692015-07-14 09:33:13 +00003963__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003964 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003965
Tobias Grosser808cd692015-07-14 09:33:13 +00003966 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003967 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003968
3969 return Domain;
3970}
3971
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003972__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
3973 PWACtx PWAC = getPwAff(E, BB);
3974 isl_set_free(PWAC.second);
3975 return PWAC.first;
3976}
3977
Tobias Grossere5a35142015-11-12 14:07:09 +00003978__isl_give isl_union_map *
3979Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3980 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003981
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003982 for (ScopStmt &Stmt : *this) {
3983 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003984 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003985 continue;
3986
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003987 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003988 isl_map *AccessDomain = MA->getAccessRelation();
3989 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003990 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003991 }
3992 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003993 return isl_union_map_coalesce(Accesses);
3994}
3995
3996__isl_give isl_union_map *Scop::getMustWrites() {
3997 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003998}
3999
4000__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004001 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004002}
4003
Tobias Grosser37eb4222014-02-20 21:43:54 +00004004__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004005 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004006}
4007
4008__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004009 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004010}
4011
Tobias Grosser2ac23382015-11-12 14:07:13 +00004012__isl_give isl_union_map *Scop::getAccesses() {
4013 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4014}
4015
Roman Gareevb3224ad2016-09-14 06:26:09 +00004016// Check whether @p Node is an extension node.
4017//
4018// @return true if @p Node is an extension node.
4019isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4020 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4021 return isl_bool_error;
4022 else
4023 return isl_bool_true;
4024}
4025
4026bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4027 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4028 nullptr) == isl_stat_error;
4029}
4030
Tobias Grosser808cd692015-07-14 09:33:13 +00004031__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004032 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004033 if (containsExtensionNode(Tree)) {
4034 isl_schedule_free(Tree);
4035 return nullptr;
4036 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004037 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004038 isl_schedule_free(Tree);
4039 return S;
4040}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004041
Tobias Grosser808cd692015-07-14 09:33:13 +00004042__isl_give isl_schedule *Scop::getScheduleTree() const {
4043 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4044 getDomains());
4045}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004046
Tobias Grosser808cd692015-07-14 09:33:13 +00004047void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4048 auto *S = isl_schedule_from_domain(getDomains());
4049 S = isl_schedule_insert_partial_schedule(
4050 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4051 isl_schedule_free(Schedule);
4052 Schedule = S;
4053}
4054
4055void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4056 isl_schedule_free(Schedule);
4057 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004058}
4059
4060bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4061 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004062 for (ScopStmt &Stmt : *this) {
4063 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004064 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4065 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4066
4067 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4068 isl_union_set_free(StmtDomain);
4069 isl_union_set_free(NewStmtDomain);
4070 continue;
4071 }
4072
4073 Changed = true;
4074
4075 isl_union_set_free(StmtDomain);
4076 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4077
4078 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004079 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004080 isl_union_set_free(NewStmtDomain);
4081 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004082 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004083 }
4084 isl_union_set_free(Domain);
4085 return Changed;
4086}
4087
Tobias Grosser75805372011-04-29 06:27:02 +00004088ScalarEvolution *Scop::getSE() const { return SE; }
4089
Tobias Grosser808cd692015-07-14 09:33:13 +00004090struct MapToDimensionDataTy {
4091 int N;
4092 isl_union_pw_multi_aff *Res;
4093};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004094
Tobias Grosserc80d6972016-09-02 06:33:33 +00004095// Create a function that maps the elements of 'Set' to its N-th dimension and
4096// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004097//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004098// @param Set The input set.
4099// @param User->N The dimension to map to.
4100// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004101//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004102// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004103static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4104 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4105 int Dim;
4106 isl_space *Space;
4107 isl_pw_multi_aff *PMA;
4108
4109 Dim = isl_set_dim(Set, isl_dim_set);
4110 Space = isl_set_get_space(Set);
4111 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4112 Dim - Data->N);
4113 if (Data->N > 1)
4114 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4115 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4116
4117 isl_set_free(Set);
4118
4119 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004120}
4121
Tobias Grosserc80d6972016-09-02 06:33:33 +00004122// Create an isl_multi_union_aff that defines an identity mapping from the
4123// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004124//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004125// # Example:
4126//
4127// Domain: { A[i,j]; B[i,j,k] }
4128// N: 1
4129//
4130// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4131//
4132// @param USet A union set describing the elements for which to generate a
4133// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004134// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004135// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004136static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004137mapToDimension(__isl_take isl_union_set *USet, int N) {
4138 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004139 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004140 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004141
Tobias Grosser808cd692015-07-14 09:33:13 +00004142 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004143
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004144 auto *Space = isl_union_set_get_space(USet);
4145 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004146
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004147 Data = {N, PwAff};
4148
4149 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004150 (void)Res;
4151
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004152 assert(Res == isl_stat_ok);
4153
4154 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004155 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4156}
4157
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004158void Scop::addScopStmt(BasicBlock *BB) {
4159 assert(BB && "Unexpected nullptr!");
4160 Stmts.emplace_back(*this, *BB);
4161 auto *Stmt = &Stmts.back();
4162 StmtMap[BB] = Stmt;
4163}
4164
4165void Scop::addScopStmt(Region *R) {
4166 assert(R && "Unexpected nullptr!");
4167 Stmts.emplace_back(*this, *R);
4168 auto *Stmt = &Stmts.back();
4169 for (BasicBlock *BB : R->blocks())
Tobias Grosser808cd692015-07-14 09:33:13 +00004170 StmtMap[BB] = Stmt;
Tobias Grosser808cd692015-07-14 09:33:13 +00004171}
4172
Roman Gareevb3224ad2016-09-14 06:26:09 +00004173ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4174 __isl_take isl_map *TargetRel,
4175 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004176#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004177 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4178 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4179 assert(isl_set_is_subset(Domain, TargetDomain) &&
4180 "Target access not defined for complete statement domain");
4181 assert(isl_set_is_subset(Domain, SourceDomain) &&
4182 "Source access not defined for complete statement domain");
4183 isl_set_free(SourceDomain);
4184 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004185#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004186 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4187 CopyStmtsNum++;
4188 return &(Stmts.back());
4189}
4190
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004191void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004192 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004193 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004194 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004195 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4196 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004197}
4198
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004199/// To generate a schedule for the elements in a Region we traverse the Region
4200/// in reverse-post-order and add the contained RegionNodes in traversal order
4201/// to the schedule of the loop that is currently at the top of the LoopStack.
4202/// For loop-free codes, this results in a correct sequential ordering.
4203///
4204/// Example:
4205/// bb1(0)
4206/// / \.
4207/// bb2(1) bb3(2)
4208/// \ / \.
4209/// bb4(3) bb5(4)
4210/// \ /
4211/// bb6(5)
4212///
4213/// Including loops requires additional processing. Whenever a loop header is
4214/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4215/// from an empty schedule, we first process all RegionNodes that are within
4216/// this loop and complete the sequential schedule at this loop-level before
4217/// processing about any other nodes. To implement this
4218/// loop-nodes-first-processing, the reverse post-order traversal is
4219/// insufficient. Hence, we additionally check if the traversal yields
4220/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4221/// These region-nodes are then queue and only traverse after the all nodes
4222/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004223void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004224 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004225
4226 ReversePostOrderTraversal<Region *> RTraversal(R);
4227 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4228 std::deque<RegionNode *> DelayList;
4229 bool LastRNWaiting = false;
4230
4231 // Iterate over the region @p R in reverse post-order but queue
4232 // sub-regions/blocks iff they are not part of the last encountered but not
4233 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4234 // that we queued the last sub-region/block from the reverse post-order
4235 // iterator. If it is set we have to explore the next sub-region/block from
4236 // the iterator (if any) to guarantee progress. If it is not set we first try
4237 // the next queued sub-region/blocks.
4238 while (!WorkList.empty() || !DelayList.empty()) {
4239 RegionNode *RN;
4240
4241 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4242 RN = WorkList.front();
4243 WorkList.pop_front();
4244 LastRNWaiting = false;
4245 } else {
4246 RN = DelayList.front();
4247 DelayList.pop_front();
4248 }
4249
4250 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004251 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004252 L = OuterScopLoop;
4253
Tobias Grosser151ae322016-04-03 19:36:52 +00004254 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004255 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004256 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004257 LastRNWaiting = true;
4258 DelayList.push_back(RN);
4259 continue;
4260 }
4261 LoopStack.push_back({L, nullptr, 0});
4262 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004263 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004264 }
4265
4266 return;
4267}
4268
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004269void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004270
Tobias Grosser8362c262016-01-06 15:30:06 +00004271 if (RN->isSubRegion()) {
4272 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004273 if (!isNonAffineSubRegion(LocalRegion)) {
4274 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004275 return;
4276 }
4277 }
Michael Kruse046dde42015-08-10 13:01:57 +00004278
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004279 auto &LoopData = LoopStack.back();
4280 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004281
Michael Kruse6f7721f2016-02-24 22:08:19 +00004282 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004283 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4284 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004285 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004286 }
4287
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004288 // Check if we just processed the last node in this loop. If we did, finalize
4289 // the loop by:
4290 //
4291 // - adding new schedule dimensions
4292 // - folding the resulting schedule into the parent loop schedule
4293 // - dropping the loop schedule from the LoopStack.
4294 //
4295 // Then continue to check surrounding loops, which might also have been
4296 // completed by this node.
4297 while (LoopData.L &&
4298 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004299 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004300 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004301
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004302 LoopStack.pop_back();
4303 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004304
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004305 if (Schedule) {
4306 auto *Domain = isl_schedule_get_domain(Schedule);
4307 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4308 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4309 NextLoopData.Schedule =
4310 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004311 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004312
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004313 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4314 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004315 }
Tobias Grosser75805372011-04-29 06:27:02 +00004316}
4317
Michael Kruse6f7721f2016-02-24 22:08:19 +00004318ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004319 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004320 if (StmtMapIt == StmtMap.end())
4321 return nullptr;
4322 return StmtMapIt->second;
4323}
4324
Michael Kruse6f7721f2016-02-24 22:08:19 +00004325ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4326 if (RN->isSubRegion())
4327 return getStmtFor(RN->getNodeAs<Region>());
4328 return getStmtFor(RN->getNodeAs<BasicBlock>());
4329}
4330
4331ScopStmt *Scop::getStmtFor(Region *R) const {
4332 ScopStmt *Stmt = getStmtFor(R->getEntry());
4333 assert(!Stmt || Stmt->getRegion() == R);
4334 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004335}
4336
Johannes Doerfert96425c22015-08-30 21:13:53 +00004337int Scop::getRelativeLoopDepth(const Loop *L) const {
4338 Loop *OuterLoop =
4339 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4340 if (!OuterLoop)
4341 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004342 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4343}
4344
Roman Gareevd7754a12016-07-30 09:25:51 +00004345ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4346 for (auto &SAI : arrays()) {
4347 if (SAI->getName() == BaseName)
4348 return SAI;
4349 }
4350 return nullptr;
4351}
4352
Johannes Doerfert99191c72016-05-31 09:41:04 +00004353//===----------------------------------------------------------------------===//
4354void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4355 AU.addRequired<LoopInfoWrapperPass>();
4356 AU.addRequired<RegionInfoPass>();
4357 AU.addRequired<DominatorTreeWrapperPass>();
4358 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4359 AU.addRequiredTransitive<ScopDetection>();
4360 AU.addRequired<AAResultsWrapperPass>();
4361 AU.addRequired<AssumptionCacheTracker>();
4362 AU.setPreservesAll();
4363}
4364
4365bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4366 auto &SD = getAnalysis<ScopDetection>();
4367
4368 if (!SD.isMaxRegionInScop(*R))
4369 return false;
4370
4371 Function *F = R->getEntry()->getParent();
4372 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4373 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4374 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4375 auto const &DL = F->getParent()->getDataLayout();
4376 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4377 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
4378
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004379 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4380 S = SB.getScop(); // take ownership of scop object
Tobias Grosser75805372011-04-29 06:27:02 +00004381 return false;
4382}
4383
Johannes Doerfert99191c72016-05-31 09:41:04 +00004384void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004385 if (S)
4386 S->print(OS);
4387 else
4388 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004389}
Tobias Grosser75805372011-04-29 06:27:02 +00004390
Johannes Doerfert99191c72016-05-31 09:41:04 +00004391char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004392
Johannes Doerfert99191c72016-05-31 09:41:04 +00004393Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4394
4395INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004396 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004397 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004398INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004399INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004400INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004401INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004402INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004403INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004404INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004405INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004406 "Polly - Create polyhedral description of Scops", false,
4407 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004408
4409//===----------------------------------------------------------------------===//
4410void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4411 AU.addRequired<LoopInfoWrapperPass>();
4412 AU.addRequired<RegionInfoPass>();
4413 AU.addRequired<DominatorTreeWrapperPass>();
4414 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4415 AU.addRequiredTransitive<ScopDetection>();
4416 AU.addRequired<AAResultsWrapperPass>();
4417 AU.addRequired<AssumptionCacheTracker>();
4418 AU.setPreservesAll();
4419}
4420
4421bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4422 auto &SD = getAnalysis<ScopDetection>();
4423
4424 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4425 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4426 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4427 auto const &DL = F.getParent()->getDataLayout();
4428 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4429 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4430
4431 /// Create polyhedral descripton of scops for all the valid regions of a
4432 /// function.
4433 for (auto &It : SD) {
4434 Region *R = const_cast<Region *>(It);
4435 if (!SD.isMaxRegionInScop(*R))
4436 continue;
4437
4438 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004439 std::unique_ptr<Scop> S = SB.getScop();
4440 if (!S)
4441 continue;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004442 bool Inserted =
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004443 RegionToScopMap.insert(std::make_pair(R, std::move(S))).second;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004444 assert(Inserted && "Building Scop for the same region twice!");
4445 (void)Inserted;
4446 }
4447 return false;
4448}
4449
4450void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4451 for (auto &It : RegionToScopMap) {
4452 if (It.second)
4453 It.second->print(OS);
4454 else
4455 OS << "Invalid Scop!\n";
4456 }
4457}
4458
4459char ScopInfoWrapperPass::ID = 0;
4460
4461Pass *polly::createScopInfoWrapperPassPass() {
4462 return new ScopInfoWrapperPass();
4463}
4464
4465INITIALIZE_PASS_BEGIN(
4466 ScopInfoWrapperPass, "polly-function-scops",
4467 "Polly - Create polyhedral description of all Scops of a function", false,
4468 false);
4469INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
4470INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
4471INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4472INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4473INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4474INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4475INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4476INITIALIZE_PASS_END(
4477 ScopInfoWrapperPass, "polly-function-scops",
4478 "Polly - Create polyhedral description of all Scops of a function", false,
4479 false)