blob: 3cbb65bf946d9c55e6d07cae8a6a3516054eb93f [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"
Michael Kruse89b1f942017-03-17 13:56:53 +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 Grossercd01a362017-02-17 08:12:36 +000077STATISTIC(NumLoopsInScop, "Number of loops in scops");
78STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
79STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
80STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
81STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
82STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
83STATISTIC(NumScopsDepthLarger,
84 "Number of scops with maximal loop depth 6 and larger");
85STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
86
Tobias Grosser75dc40c2015-12-20 13:31:48 +000087// The maximal number of basic sets we allow during domain construction to
88// be created. More complex scops will result in very high compile time and
89// are also unlikely to result in good code
Tobias Grosser90411a92017-02-16 19:11:33 +000090static int const MaxDisjunctsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +000091
Tobias Grosserc8a82762017-02-16 19:11:25 +000092// The number of disjunct in the context after which we stop to add more
93// disjuncts. This parameter is there to avoid exponential growth in the
94// number of disjunct when adding non-convex sets to the context.
95static int const MaxDisjunctsInContext = 4;
96
Tobias Grosser97715842017-05-19 04:01:52 +000097static cl::opt<int>
98 OptComputeOut("polly-analysis-computeout",
99 cl::desc("Bound the scop analysis by a maximal amount of "
100 "computational steps (0 means no bound)"),
101 cl::Hidden, cl::init(1000000), cl::ZeroOrMore,
102 cl::cat(PollyCategory));
Tobias Grosser45e9fd12017-05-19 03:45:00 +0000103
Johannes Doerfert2f705842016-04-12 16:09:44 +0000104static cl::opt<bool> PollyRemarksMinimal(
105 "polly-remarks-minimal",
106 cl::desc("Do not emit remarks about assumptions that are known"),
107 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
108
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +0000109// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000110// operations can overflow easily. Additive reductions and bit operations
111// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +0000112static cl::opt<bool> DisableMultiplicativeReductions(
113 "polly-disable-multiplicative-reductions",
114 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
115 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000116
Johannes Doerfert9143d672014-09-27 11:02:39 +0000117static cl::opt<unsigned> RunTimeChecksMaxParameters(
118 "polly-rtc-max-parameters",
119 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
120 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
121
Tobias Grosser71500722015-03-28 15:11:14 +0000122static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
123 "polly-rtc-max-arrays-per-group",
124 cl::desc("The maximal number of arrays to compare in each alias group."),
125 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000126
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000127static cl::opt<std::string> UserContextStr(
128 "polly-context", cl::value_desc("isl parameter set"),
129 cl::desc("Provide additional constraints on the context parameters"),
130 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000131
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000132static cl::opt<bool> DetectReductions("polly-detect-reductions",
133 cl::desc("Detect and exploit reductions"),
134 cl::Hidden, cl::ZeroOrMore,
135 cl::init(true), cl::cat(PollyCategory));
136
Tobias Grosser2937b592016-04-29 11:43:20 +0000137static cl::opt<bool>
138 IslOnErrorAbort("polly-on-isl-error-abort",
139 cl::desc("Abort if an isl error is encountered"),
140 cl::init(true), cl::cat(PollyCategory));
141
Tobias Grosserd7c49752017-02-28 09:45:54 +0000142static cl::opt<bool> PollyPreciseInbounds(
143 "polly-precise-inbounds",
144 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
145 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
146
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000147static cl::opt<bool>
148 PollyIgnoreInbounds("polly-ignore-inbounds",
149 cl::desc("Do not take inbounds assumptions at all"),
150 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
151
Tobias Grosser5842dee2017-03-17 13:00:53 +0000152static cl::opt<bool> PollyIgnoreParamBounds(
153 "polly-ignore-parameter-bounds",
154 cl::desc(
155 "Do not add parameter bounds and do no gist simplify sets accordingly"),
156 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
157
Tobias Grosserc2f15102017-03-01 21:11:27 +0000158static cl::opt<bool> PollyPreciseFoldAccesses(
159 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000160 cl::desc("Fold memory accesses to model more possible delinearizations "
161 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000162 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000163
Michael Kruse5ae08c02017-05-06 14:03:58 +0000164bool polly::UseInstructionNames;
165static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000166 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000167 cl::desc("Use LLVM-IR names when deriving statement names"),
168 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
169 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000170
Michael Kruse7bf39442015-09-10 12:46:52 +0000171//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000172
Michael Kruse046dde42015-08-10 13:01:57 +0000173// Create a sequence of two schedules. Either argument may be null and is
174// interpreted as the empty schedule. Can also return null if both schedules are
175// empty.
176static __isl_give isl_schedule *
177combineInSequence(__isl_take isl_schedule *Prev,
178 __isl_take isl_schedule *Succ) {
179 if (!Prev)
180 return Succ;
181 if (!Succ)
182 return Prev;
183
184 return isl_schedule_sequence(Prev, Succ);
185}
186
Johannes Doerferte7044942015-02-24 11:58:30 +0000187static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
188 const ConstantRange &Range,
189 int dim,
190 enum isl_dim_type type) {
191 isl_val *V;
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000192 isl_ctx *Ctx = isl_set_get_ctx(S);
Johannes Doerferte7044942015-02-24 11:58:30 +0000193
Tobias Grosser3281f602017-02-16 18:39:14 +0000194 // The upper and lower bound for a parameter value is derived either from
195 // the data type of the parameter or from the - possibly more restrictive -
196 // range metadata.
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000197 V = isl_valFromAPInt(Ctx, Range.getSignedMin(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000198 S = isl_set_lower_bound_val(S, type, dim, V);
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000199 V = isl_valFromAPInt(Ctx, Range.getSignedMax(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000200 S = isl_set_upper_bound_val(S, type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000201
Tobias Grosser3281f602017-02-16 18:39:14 +0000202 if (Range.isFullSet())
203 return S;
204
Tobias Grosserc8a82762017-02-16 19:11:25 +0000205 if (isl_set_n_basic_set(S) > MaxDisjunctsInContext)
206 return S;
207
Tobias Grosser3281f602017-02-16 18:39:14 +0000208 // In case of signed wrapping, we can refine the set of valid values by
209 // excluding the part not covered by the wrapping range.
210 if (Range.isSignWrappedSet()) {
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000211 V = isl_valFromAPInt(Ctx, Range.getLower(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000212 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
213
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000214 V = isl_valFromAPInt(Ctx, Range.getUpper(), true);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000215 V = isl_val_sub_ui(V, 1);
Tobias Grosser3281f602017-02-16 18:39:14 +0000216 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
217 S = isl_set_union(SLB, SUB);
218 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000219
Tobias Grosser3281f602017-02-16 18:39:14 +0000220 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000221}
222
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000223static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
224 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
225 if (!BasePtrLI)
226 return nullptr;
227
Johannes Doerfert952b5302016-05-23 12:40:48 +0000228 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000229 return nullptr;
230
231 ScalarEvolution &SE = *S->getSE();
232
233 auto *OriginBaseSCEV =
234 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
235 if (!OriginBaseSCEV)
236 return nullptr;
237
238 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
239 if (!OriginBaseSCEVUnknown)
240 return nullptr;
241
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000242 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000243 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000244}
245
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000246ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000247 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000248 const DataLayout &DL, Scop *S,
249 const char *BaseName)
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000250 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000251 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000252 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000253 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
254 Kind == MemoryKind::PHI ? "__phi" : "",
255 UseInstructionNames);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000256 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000257
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000258 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000259
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000260 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000261 BasePtrOriginSAI = nullptr;
262 return;
263 }
264
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000265 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
266 if (BasePtrOriginSAI)
267 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000268}
269
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000270__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000271 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000272 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
273 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
274 return Space;
275}
276
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000277bool ScopArrayInfo::isReadOnly() {
278 isl_union_set *WriteSet = isl_union_map_range(S.getWrites());
279 isl_space *Space = getSpace();
280 WriteSet = isl_union_set_intersect(
281 WriteSet, isl_union_set_from_set(isl_set_universe(Space)));
282
283 bool IsReadOnly = isl_union_set_is_empty(WriteSet);
284 isl_union_set_free(WriteSet);
285
286 return IsReadOnly;
287}
288
Tobias Grosserf3adab42017-05-10 10:59:58 +0000289bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
290 if (Array->getElementType() != getElementType())
291 return false;
292
293 if (Array->getNumberOfDimensions() != getNumberOfDimensions())
294 return false;
295
296 for (unsigned i = 0; i < getNumberOfDimensions(); i++)
297 if (Array->getDimensionSize(i) != getDimensionSize(i))
298 return false;
299
300 return true;
301}
302
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000303void ScopArrayInfo::updateElementType(Type *NewElementType) {
304 if (NewElementType == ElementType)
305 return;
306
Tobias Grosserd840fc72016-02-04 13:18:42 +0000307 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
308 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
309
Johannes Doerferta7920982016-02-25 14:08:48 +0000310 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000311 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000312
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000313 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
314 ElementType = NewElementType;
315 } else {
316 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
317 ElementType = IntegerType::get(ElementType->getContext(), GCD);
318 }
319}
320
Tobias Grosserbedef002016-12-02 08:10:56 +0000321bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
322 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000323 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
324 int ExtraDimsNew = NewSizes.size() - SharedDims;
325 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000326
Tobias Grosserbedef002016-12-02 08:10:56 +0000327 if (CheckConsistency) {
328 for (int i = 0; i < SharedDims; i++) {
329 auto *NewSize = NewSizes[i + ExtraDimsNew];
330 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
331 if (NewSize && KnownSize && NewSize != KnownSize)
332 return false;
333 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000334
Tobias Grosserbedef002016-12-02 08:10:56 +0000335 if (DimensionSizes.size() >= NewSizes.size())
336 return true;
337 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000338
339 DimensionSizes.clear();
340 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
341 NewSizes.end());
342 for (isl_pw_aff *Size : DimensionSizesPw)
343 isl_pw_aff_free(Size);
344 DimensionSizesPw.clear();
345 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000346 if (!Expr) {
347 DimensionSizesPw.push_back(nullptr);
348 continue;
349 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000350 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000351 DimensionSizesPw.push_back(Size);
352 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000353 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000354}
355
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000356ScopArrayInfo::~ScopArrayInfo() {
357 isl_id_free(Id);
358 for (isl_pw_aff *Size : DimensionSizesPw)
359 isl_pw_aff_free(Size);
360}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000361
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000362std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
363
364int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000365 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000366}
367
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000368__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
369 return isl_id_copy(Id);
370}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000371
372void ScopArrayInfo::dump() const { print(errs()); }
373
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000374void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000375 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000376 unsigned u = 0;
377 if (getNumberOfDimensions() > 0 && !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000378 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000379 u++;
380 }
381 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000382 OS << "[";
383
Tobias Grosser26253842015-11-10 14:24:21 +0000384 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000385 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000386 OS << " " << Size << " ";
387 isl_pw_aff_free(Size);
388 } else {
389 OS << *getDimensionSize(u);
390 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000391
392 OS << "]";
393 }
394
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000395 OS << ";";
396
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000397 if (BasePtrOriginSAI)
398 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
399
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000400 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000401}
402
403const ScopArrayInfo *
404ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
405 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
406 assert(Id && "Output dimension didn't have an ID");
407 return getFromId(Id);
408}
409
Michael Krused56b90a2016-09-01 09:03:27 +0000410const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000411 void *User = isl_id_get_user(Id);
412 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
413 isl_id_free(Id);
414 return SAI;
415}
416
Michael Kruse3b425ff2016-04-11 14:34:08 +0000417void MemoryAccess::wrapConstantDimensions() {
418 auto *SAI = getScopArrayInfo();
419 auto *ArraySpace = SAI->getSpace();
420 auto *Ctx = isl_space_get_ctx(ArraySpace);
421 unsigned DimsArray = SAI->getNumberOfDimensions();
422
423 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
424 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
425 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
426
427 // Begin with last dimension, to iteratively carry into higher dimensions.
428 for (int i = DimsArray - 1; i > 0; i--) {
429 auto *DimSize = SAI->getDimensionSize(i);
430 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
431
432 // This transformation is not applicable to dimensions with dynamic size.
433 if (!DimSizeCst)
434 continue;
435
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000436 // This transformation is not applicable to dimensions of size zero.
437 if (DimSize->isZero())
438 continue;
439
Michael Kruse3b425ff2016-04-11 14:34:08 +0000440 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
441 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
442 isl_dim_set, i);
443 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
444 isl_dim_set, i - 1);
445
446 // Compute: index % size
447 // Modulo must apply in the divide of the previous iteration, if any.
448 auto *Modulo = isl_aff_copy(Var);
449 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
450 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
451
452 // Compute: floor(index / size)
453 auto *Divide = Var;
454 Divide = isl_aff_div(
455 Divide,
456 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
457 Divide = isl_aff_floor(Divide);
458 Divide = isl_aff_add(Divide, PrevVar);
459 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
460
461 // Apply Modulo and Divide.
462 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
463 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
464 }
465
466 // Apply all modulo/divides on the accesses.
467 AccessRelation =
468 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
469 AccessRelation = isl_map_detect_equalities(AccessRelation);
470 isl_local_space_free(LArraySpace);
471}
472
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000473void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000474 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000475 auto *ArraySpace = SAI->getSpace();
476 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000477 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000478
479 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
480 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
481 auto DimsMissing = DimsArray - DimsAccess;
482
Michael Kruse375cb5f2016-02-24 22:08:24 +0000483 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000484 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000485 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000486 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000487
Johannes Doerferta90943d2016-02-21 16:37:25 +0000488 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000489 isl_set_universe(AccessSpace),
490 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000491
492 for (unsigned i = 0; i < DimsMissing; i++)
493 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
494
495 for (unsigned i = DimsMissing; i < DimsArray; i++)
496 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
497
498 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000499
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000500 // For the non delinearized arrays, divide the access function of the last
501 // subscript by the size of the elements in the array.
502 //
503 // A stride one array access in C expressed as A[i] is expressed in
504 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
505 // two subsequent values of 'i' index two values that are stored next to
506 // each other in memory. By this division we make this characteristic
507 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000508 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000509 // that divides the offsets of all accesses to this base pointer.
510 if (DimsAccess == 1) {
511 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
512 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
513 }
514
Michael Kruse3b425ff2016-04-11 14:34:08 +0000515 // We currently do this only if we added at least one dimension, which means
516 // some dimension's indices have not been specified, an indicator that some
517 // index values have been added together.
518 // TODO: Investigate general usefulness; Effect on unit tests is to make index
519 // expressions more complicated.
520 if (DimsMissing)
521 wrapConstantDimensions();
522
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000523 if (!isAffine())
524 computeBoundsOnAccessRelation(ArrayElemSize);
525
Tobias Grosserd840fc72016-02-04 13:18:42 +0000526 // Introduce multi-element accesses in case the type loaded by this memory
527 // access is larger than the canonical element type of the array.
528 //
529 // An access ((float *)A)[i] to an array char *A is modeled as
530 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000531 if (ElemBytes > ArrayElemSize) {
532 assert(ElemBytes % ArrayElemSize == 0 &&
533 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000534 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000535 isl_set_universe(isl_space_copy(ArraySpace)),
536 isl_set_universe(isl_space_copy(ArraySpace)));
537 for (unsigned i = 0; i < DimsArray - 1; i++)
538 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
539
Tobias Grosserd840fc72016-02-04 13:18:42 +0000540 isl_constraint *C;
541 isl_local_space *LS;
542
543 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000544 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
545
546 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
547 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000548 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000549 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
550 Map = isl_map_add_constraint(Map, C);
551
552 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000553 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000554 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
555 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
556 Map = isl_map_add_constraint(Map, C);
557 AccessRelation = isl_map_apply_range(AccessRelation, Map);
558 }
559
560 isl_space_free(ArraySpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000561}
562
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000563const std::string
564MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
565 switch (RT) {
566 case MemoryAccess::RT_NONE:
567 llvm_unreachable("Requested a reduction operator string for a memory "
568 "access which isn't a reduction");
569 case MemoryAccess::RT_ADD:
570 return "+";
571 case MemoryAccess::RT_MUL:
572 return "*";
573 case MemoryAccess::RT_BOR:
574 return "|";
575 case MemoryAccess::RT_BXOR:
576 return "^";
577 case MemoryAccess::RT_BAND:
578 return "&";
579 }
580 llvm_unreachable("Unknown reduction type");
581 return "";
582}
583
Tobias Grosserc80d6972016-09-02 06:33:33 +0000584/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000585static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
586 const Instruction *Load) {
587 if (!BinOp)
588 return MemoryAccess::RT_NONE;
589 switch (BinOp->getOpcode()) {
590 case Instruction::FAdd:
591 if (!BinOp->hasUnsafeAlgebra())
592 return MemoryAccess::RT_NONE;
593 // Fall through
594 case Instruction::Add:
595 return MemoryAccess::RT_ADD;
596 case Instruction::Or:
597 return MemoryAccess::RT_BOR;
598 case Instruction::Xor:
599 return MemoryAccess::RT_BXOR;
600 case Instruction::And:
601 return MemoryAccess::RT_BAND;
602 case Instruction::FMul:
603 if (!BinOp->hasUnsafeAlgebra())
604 return MemoryAccess::RT_NONE;
605 // Fall through
606 case Instruction::Mul:
607 if (DisableMultiplicativeReductions)
608 return MemoryAccess::RT_NONE;
609 return MemoryAccess::RT_MUL;
610 default:
611 return MemoryAccess::RT_NONE;
612 }
613}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000614
Tobias Grosser75805372011-04-29 06:27:02 +0000615MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000616 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000617 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000618 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000619 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000620}
621
Michael Kruse2fa35192016-09-01 19:53:31 +0000622const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000623 isl_id *ArrayId = getArrayId();
624 void *User = isl_id_get_user(ArrayId);
625 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
626 isl_id_free(ArrayId);
627 return SAI;
628}
629
Michael Kruse2fa35192016-09-01 19:53:31 +0000630const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
631 isl_id *ArrayId = getLatestArrayId();
632 void *User = isl_id_get_user(ArrayId);
633 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
634 isl_id_free(ArrayId);
635 return SAI;
636}
637
638__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000639 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
640}
641
Michael Kruse2fa35192016-09-01 19:53:31 +0000642__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
643 if (!hasNewAccessRelation())
644 return getOriginalArrayId();
645 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
646}
647
Tobias Grosserd840fc72016-02-04 13:18:42 +0000648__isl_give isl_map *MemoryAccess::getAddressFunction() const {
649 return isl_map_lexmin(getAccessRelation());
650}
651
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000652__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
653 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000654 isl_map *Schedule, *ScheduledAccRel;
655 isl_union_set *UDomain;
656
657 UDomain = isl_union_set_from_set(getStatement()->getDomain());
658 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
659 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000660 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000661 return isl_pw_multi_aff_from_map(ScheduledAccRel);
662}
663
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000664__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000665 return isl_map_copy(AccessRelation);
666}
667
Johannes Doerferta99130f2014-10-13 12:58:03 +0000668std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000669 return stringFromIslObj(AccessRelation);
670}
671
Johannes Doerferta99130f2014-10-13 12:58:03 +0000672__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000673 return isl_map_get_space(AccessRelation);
674}
675
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000676__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000677 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000678}
679
Tobias Grosser6f730082015-09-05 07:46:47 +0000680std::string MemoryAccess::getNewAccessRelationStr() const {
681 return stringFromIslObj(NewAccessRelation);
682}
683
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000684__isl_give isl_basic_map *
685MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000686 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000687 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000688
Tobias Grosser084d8f72012-05-29 09:29:44 +0000689 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000690 isl_basic_set_universe(Statement->getDomainSpace()),
691 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000692}
693
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000694// Formalize no out-of-bound access assumption
695//
696// When delinearizing array accesses we optimistically assume that the
697// delinearized accesses do not access out of bound locations (the subscript
698// expression of each array evaluates for each statement instance that is
699// executed to a value that is larger than zero and strictly smaller than the
700// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000701// dimension for which we do not need to assume any upper bound. At this point
702// we formalize this assumption to ensure that at code generation time the
703// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000704//
705// To find the set of constraints necessary to avoid out of bound accesses, we
706// first build the set of data locations that are not within array bounds. We
707// then apply the reverse access relation to obtain the set of iterations that
708// may contain invalid accesses and reduce this set of iterations to the ones
709// that are actually executed by intersecting them with the domain of the
710// statement. If we now project out all loop dimensions, we obtain a set of
711// parameters that may cause statement instances to be executed that may
712// possibly yield out of bound memory accesses. The complement of these
713// constraints is the set of constraints that needs to be assumed to ensure such
714// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000715void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000716 if (PollyIgnoreInbounds)
717 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000718 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000719 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000720 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000721 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000722 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
723 isl_pw_aff *Var =
724 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
725 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
726
727 isl_set *DimOutside;
728
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000729 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000730 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000731 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
732 isl_space_dim(Space, isl_dim_set));
733 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
734 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000735
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000736 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000737
738 Outside = isl_set_union(Outside, DimOutside);
739 }
740
741 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
742 Outside = isl_set_intersect(Outside, Statement->getDomain());
743 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000744
745 // Remove divs to avoid the construction of overly complicated assumptions.
746 // Doing so increases the set of parameter combinations that are assumed to
747 // not appear. This is always save, but may make the resulting run-time check
748 // bail out more often than strictly necessary.
749 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000750 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000751 const auto &Loc = getAccessInstruction()
752 ? getAccessInstruction()->getDebugLoc()
753 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000754 if (!PollyPreciseInbounds)
755 Outside = isl_set_gist(Outside, isl_set_params(Statement->getDomain()));
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000756 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
757 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000758 isl_space_free(Space);
759}
760
Johannes Doerfertcea61932016-02-21 19:13:19 +0000761void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000762 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000763 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000764
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000765 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000766 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000767
768 isl_map *LengthMap;
769 if (Subscripts[1] == nullptr) {
770 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
771 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000772 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000773 LengthMap = isl_map_from_pw_aff(LengthPWA);
774 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
775 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
776 }
777 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
778 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000779 SubscriptMap =
780 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000781 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
782 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
783 getStatement()->getDomainId());
784}
785
Johannes Doerferte7044942015-02-24 11:58:30 +0000786void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
787 ScalarEvolution *SE = Statement->getParent()->getSE();
788
Johannes Doerfertcea61932016-02-21 19:13:19 +0000789 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000790 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000791 return;
792
793 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000794 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
795 return;
796
797 auto *PtrSCEV = SE->getSCEV(Ptr);
798 if (isa<SCEVCouldNotCompute>(PtrSCEV))
799 return;
800
801 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
802 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
803 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
804
805 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
806 if (Range.isFullSet())
807 return;
808
Michael Kruse960c0d02017-05-18 21:55:36 +0000809 if (Range.isWrappedSet() || Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000810 return;
811
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000812 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000813
Johannes Doerferte7044942015-02-24 11:58:30 +0000814 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000815 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000816 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000817 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000818
819 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000820 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000821
Tobias Grosserb3a85882017-02-12 08:11:12 +0000822 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
823
Johannes Doerferte7044942015-02-24 11:58:30 +0000824 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
825 AccessRange =
826 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
827 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
828}
829
Tobias Grosser491b7992016-12-02 05:21:22 +0000830void MemoryAccess::foldAccessRelation() {
831 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
832 return;
833
Michael Krusee2bccbb2015-09-18 19:59:43 +0000834 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000835
Tobias Grosserc2f15102017-03-01 21:11:27 +0000836 isl_map *OldAccessRelation = isl_map_copy(AccessRelation);
837
Tobias Grosser619190d2015-03-30 17:22:28 +0000838 for (int i = Size - 2; i >= 0; --i) {
839 isl_space *Space;
840 isl_map *MapOne, *MapTwo;
Roman Gareevf5aff702016-09-12 17:08:31 +0000841 isl_pw_aff *DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000842
843 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
844 isl_pw_aff_free(DimSize);
845 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
846
847 Space = isl_map_get_space(AccessRelation);
848 Space = isl_space_map_from_set(isl_space_range(Space));
849 Space = isl_space_align_params(Space, SpaceSize);
850
851 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
852 isl_id_free(ParamId);
853
854 MapOne = isl_map_universe(isl_space_copy(Space));
855 for (int j = 0; j < Size; ++j)
856 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
857 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
858
859 MapTwo = isl_map_universe(isl_space_copy(Space));
860 for (int j = 0; j < Size; ++j)
861 if (j < i || j > i + 1)
862 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
863
864 isl_local_space *LS = isl_local_space_from_space(Space);
865 isl_constraint *C;
866 C = isl_equality_alloc(isl_local_space_copy(LS));
867 C = isl_constraint_set_constant_si(C, -1);
868 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
869 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
870 MapTwo = isl_map_add_constraint(MapTwo, C);
871 C = isl_equality_alloc(LS);
872 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
873 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
874 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
875 MapTwo = isl_map_add_constraint(MapTwo, C);
876 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
877
878 MapOne = isl_map_union(MapOne, MapTwo);
879 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
880 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000881
882 isl_id *BaseAddrId = getScopArrayInfo()->getBasePtrId();
883 auto Space = Statement->getDomainSpace();
884 AccessRelation = isl_map_set_tuple_id(
885 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
886 AccessRelation =
887 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
888 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Tobias Grosserc2f15102017-03-01 21:11:27 +0000889
890 // Access dimension folding might in certain cases increase the number of
891 // disjuncts in the memory access, which can possibly complicate the generated
892 // run-time checks and can lead to costly compilation.
893 if (!PollyPreciseFoldAccesses && isl_map_n_basic_map(AccessRelation) >
894 isl_map_n_basic_map(OldAccessRelation)) {
895 isl_map_free(AccessRelation);
896 AccessRelation = OldAccessRelation;
897 } else {
898 isl_map_free(OldAccessRelation);
899 }
900
Tobias Grosser491b7992016-12-02 05:21:22 +0000901 isl_space_free(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000902}
903
Tobias Grosserc80d6972016-09-02 06:33:33 +0000904/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000905static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000906 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000907 if (Size == 1)
908 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000909
910 // Only one factor needs to be divisible.
911 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
912 for (auto *FactorExpr : MulExpr->operands())
913 if (isDivisible(FactorExpr, Size, SE))
914 return true;
915 return false;
916 }
917
918 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
919 // to be divisble.
920 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
921 for (auto *OpExpr : NAryExpr->operands())
922 if (!isDivisible(OpExpr, Size, SE))
923 return false;
924 return true;
925 }
926
927 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
928 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
929 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
930 return MulSCEV == Expr;
931}
932
Michael Krusee2bccbb2015-09-18 19:59:43 +0000933void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
934 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000935
Johannes Doerfert85676e32016-04-23 14:32:34 +0000936 // Initialize the invalid domain which describes all iterations for which the
937 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000938 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
939 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
940 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000941
Michael Krusee2bccbb2015-09-18 19:59:43 +0000942 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000943 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000944
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000945 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
946 buildMemIntrinsicAccessRelation();
947 AccessRelation =
948 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
949 return;
950 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000951
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000952 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000953 // We overapproximate non-affine accesses with a possible access to the
954 // whole array. For read accesses it does not make a difference, if an
955 // access must or may happen. However, for write accesses it is important to
956 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000957 if (!AccessRelation)
958 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
959
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000960 AccessRelation =
961 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000962 return;
963 }
964
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000965 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000966 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000967
Michael Krusee2bccbb2015-09-18 19:59:43 +0000968 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000969 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000970 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000971 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000972 }
973
Tobias Grosser79baa212014-04-10 08:38:02 +0000974 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000975 AccessRelation = isl_map_set_tuple_id(
976 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000977 AccessRelation =
978 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
979
Tobias Grosseraa660a92015-03-30 00:07:50 +0000980 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000981 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000982}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000983
Michael Krusecac948e2015-10-02 13:53:07 +0000984MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000985 AccessType AccType, Value *BaseAddress,
986 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000987 ArrayRef<const SCEV *> Subscripts,
988 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +0000989 MemoryKind Kind)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000990 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Tobias Grosser81331282017-05-03 07:57:35 +0000991 InvalidDomain(nullptr), BaseAddr(BaseAddress), ElementType(ElementType),
992 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
993 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000994 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +0000995 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000996 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +0000997 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000998
Tobias Grosser81331282017-05-03 07:57:35 +0000999 std::string IdName = Stmt->getBaseName() + Access;
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001000 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1001}
Michael Krusee2bccbb2015-09-18 19:59:43 +00001002
Roman Gareevb3224ad2016-09-14 06:26:09 +00001003MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
1004 __isl_take isl_map *AccRel)
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001005 : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
1006 Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001007 IsAffine(true), AccessRelation(nullptr), NewAccessRelation(AccRel),
1008 FAD(nullptr) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001009 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
1010 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1011 Sizes.push_back(nullptr);
1012 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1013 Sizes.push_back(SAI->getDimensionSize(i));
1014 ElementType = SAI->getElementType();
1015 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001016 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001017 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001018
Tobias Grosser81331282017-05-03 07:57:35 +00001019 std::string IdName = Stmt->getBaseName() + Access;
Roman Gareevb3224ad2016-09-14 06:26:09 +00001020 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1021}
1022
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001023void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +00001024 auto *Ctx = Statement->getParent()->getContext();
1025 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1026 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001027}
1028
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001029const std::string MemoryAccess::getReductionOperatorStr() const {
1030 return MemoryAccess::getReductionOperatorStr(getReductionType());
1031}
1032
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001033__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
1034
Johannes Doerfertf6183392014-07-01 20:52:51 +00001035raw_ostream &polly::operator<<(raw_ostream &OS,
1036 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001037 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001038 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001039 else
1040 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001041 return OS;
1042}
1043
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001044void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001045
Tobias Grosser75805372011-04-29 06:27:02 +00001046void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001047 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001048 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001049 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001050 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001051 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001052 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001053 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001054 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001055 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001056 break;
1057 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001058
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001059 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001060
1061 if (FAD) {
1062 OS << "[Fortran array descriptor: " << FAD->getName();
1063 OS << "] ";
1064 };
1065
Tobias Grossera535dff2015-12-13 19:59:01 +00001066 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001067 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001068 if (hasNewAccessRelation())
1069 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001070}
1071
Tobias Grosser74394f02013-01-14 22:40:23 +00001072void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +00001073
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001074__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
1075 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001076 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +00001077 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
1078 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
1079 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +00001080 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001081}
1082
Tobias Grosser75805372011-04-29 06:27:02 +00001083// Create a map in the size of the provided set domain, that maps from the
1084// one element of the provided set domain to another element of the provided
1085// set domain.
1086// The mapping is limited to all points that are equal in all but the last
1087// dimension and for which the last dimension of the input is strict smaller
1088// than the last dimension of the output.
1089//
1090// getEqualAndLarger(set[i0, i1, ..., iX]):
1091//
1092// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1093// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1094//
Tobias Grosser2a526fe2016-09-08 11:18:56 +00001095static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +00001096 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001097 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +00001098 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001099
1100 // Set all but the last dimension to be equal for the input and output
1101 //
1102 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1103 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001104 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +00001105 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001106
1107 // Set the last dimension of the input to be strict smaller than the
1108 // last dimension of the output.
1109 //
1110 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001111 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1112 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001113 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001114}
1115
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001116__isl_give isl_set *
1117MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001118 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +00001119 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +00001120 isl_space *Space = isl_space_range(isl_map_get_space(S));
1121 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001122
Sebastian Popa00a0292012-12-18 07:46:06 +00001123 S = isl_map_reverse(S);
1124 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001125
Sebastian Popa00a0292012-12-18 07:46:06 +00001126 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1127 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1128 NextScatt = isl_map_apply_domain(NextScatt, S);
1129 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001130
Sebastian Popa00a0292012-12-18 07:46:06 +00001131 isl_set *Deltas = isl_map_deltas(NextScatt);
1132 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001133}
1134
Sebastian Popa00a0292012-12-18 07:46:06 +00001135bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001136 int StrideWidth) const {
1137 isl_set *Stride, *StrideX;
1138 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001139
Sebastian Popa00a0292012-12-18 07:46:06 +00001140 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001141 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001142 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1143 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1144 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1145 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001146 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001147
Tobias Grosser28dd4862012-01-24 16:42:16 +00001148 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001149 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001150
Tobias Grosser28dd4862012-01-24 16:42:16 +00001151 return IsStrideX;
1152}
1153
Michael Krused56b90a2016-09-01 09:03:27 +00001154bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001155 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001156}
1157
Michael Krused56b90a2016-09-01 09:03:27 +00001158bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001159 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001160}
1161
Tobias Grosserbedef002016-12-02 08:10:56 +00001162void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
1163 isl_map_free(AccessRelation);
1164 AccessRelation = NewAccess;
1165}
1166
Michael Krused56b90a2016-09-01 09:03:27 +00001167void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001168 assert(NewAccess);
1169
1170#ifndef NDEBUG
1171 // Check domain space compatibility.
1172 auto *NewSpace = isl_map_get_space(NewAccess);
1173 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1174 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1175 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1176 isl_space_free(NewDomainSpace);
1177 isl_space_free(OriginalDomainSpace);
1178
1179 // Check whether there is an access for every statement instance.
1180 auto *StmtDomain = getStatement()->getDomain();
1181 StmtDomain = isl_set_intersect_params(
1182 StmtDomain, getStatement()->getParent()->getContext());
1183 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1184 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1185 "Partial accesses not supported");
1186 isl_set_free(NewDomain);
1187 isl_set_free(StmtDomain);
1188
Michael Kruse772ce722016-09-01 19:16:58 +00001189 auto *NewAccessSpace = isl_space_range(NewSpace);
1190 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1191 "Must specify the array that is accessed");
1192 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1193 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1194 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001195
1196 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1197 InvariantEquivClassTy *EqClass =
1198 getStatement()->getParent()->lookupInvariantEquivClass(
1199 SAI->getBasePtr());
1200 assert(EqClass &&
1201 "Access functions to indirect arrays must have an invariant and "
1202 "hoisted base pointer");
1203 }
1204
1205 // Check whether access dimensions correspond to number of dimensions of the
1206 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001207 auto Dims = SAI->getNumberOfDimensions();
1208 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1209 "Access dims must match array dims");
1210 isl_space_free(NewAccessSpace);
1211 isl_id_free(NewArrayId);
1212#endif
1213
Tobias Grosser166c4222015-09-05 07:46:40 +00001214 isl_map_free(NewAccessRelation);
1215 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001216}
Tobias Grosser75805372011-04-29 06:27:02 +00001217
1218//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001219
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001220__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001221 isl_set *Domain = getDomain();
1222 if (isl_set_is_empty(Domain)) {
1223 isl_set_free(Domain);
1224 return isl_map_from_aff(
1225 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1226 }
1227 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001228 if (!Schedule) {
1229 isl_set_free(Domain);
1230 return nullptr;
1231 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001232 Schedule = isl_union_map_intersect_domain(
1233 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1234 if (isl_union_map_is_empty(Schedule)) {
1235 isl_set_free(Domain);
1236 isl_union_map_free(Schedule);
1237 return isl_map_from_aff(
1238 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1239 }
1240 auto *M = isl_map_from_union_map(Schedule);
1241 M = isl_map_coalesce(M);
1242 M = isl_map_gist_domain(M, Domain);
1243 M = isl_map_coalesce(M);
1244 return M;
1245}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001246
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001247__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1248 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001249 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1250 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001251}
1252
Tobias Grosser37eb4222014-02-20 21:43:54 +00001253void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1254 assert(isl_set_is_subset(NewDomain, Domain) &&
1255 "New domain is not a subset of old domain!");
1256 isl_set_free(Domain);
1257 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001258}
1259
Michael Krusecac948e2015-10-02 13:53:07 +00001260void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001261 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001262 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001263 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001264
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001265 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001266 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001267 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001268 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001269 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001270 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001271 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001272 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001273 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001274
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001275 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1276 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001277 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001278 }
1279}
1280
Michael Kruse4c276432017-05-11 22:56:46 +00001281MemoryAccess *ScopStmt::lookupPHIReadOf(PHINode *PHI) const {
1282 for (auto *MA : *this) {
1283 if (!MA->isRead())
1284 continue;
1285 if (!MA->isLatestAnyPHIKind())
1286 continue;
1287
1288 if (MA->getAccessInstruction() == PHI)
1289 return MA;
1290 }
1291 return nullptr;
1292}
1293
Michael Krusecac948e2015-10-02 13:53:07 +00001294void ScopStmt::addAccess(MemoryAccess *Access) {
1295 Instruction *AccessInst = Access->getAccessInstruction();
1296
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001297 if (Access->isArrayKind()) {
1298 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1299 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001300 } else if (Access->isValueKind() && Access->isWrite()) {
1301 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001302 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001303 assert(!ValueWrites.lookup(AccessVal));
1304
1305 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001306 } else if (Access->isValueKind() && Access->isRead()) {
1307 Value *AccessVal = Access->getAccessValue();
1308 assert(!ValueReads.lookup(AccessVal));
1309
1310 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001311 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001312 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001313 assert(!PHIWrites.lookup(PHI));
1314
1315 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001316 }
1317
1318 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001319}
1320
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001321void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001322 for (MemoryAccess *MA : *this)
1323 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001324
Johannes Doerferta60ad842016-05-10 12:18:22 +00001325 auto *Ctx = Parent.getContext();
1326 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1327 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001328}
1329
Tobias Grosserc80d6972016-09-02 06:33:33 +00001330/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001331static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1332 void *User) {
1333 isl_set **BoundedParts = static_cast<isl_set **>(User);
1334 if (isl_basic_set_is_bounded(BSet))
1335 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1336 else
1337 isl_basic_set_free(BSet);
1338 return isl_stat_ok;
1339}
1340
Tobias Grosserc80d6972016-09-02 06:33:33 +00001341/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001342static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1343 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1344 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1345 isl_set_free(S);
1346 return BoundedParts;
1347}
1348
Tobias Grosserc80d6972016-09-02 06:33:33 +00001349/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001350///
1351/// @returns A separation of @p S into first an unbounded then a bounded subset,
1352/// both with regards to the dimension @p Dim.
1353static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1354partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1355
1356 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001357 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001358
1359 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001360 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001361
1362 // Remove dimensions that are greater than Dim as they are not interesting.
1363 assert(NumDimsS >= Dim + 1);
1364 OnlyDimS =
1365 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1366
1367 // Create artificial parametric upper bounds for dimensions smaller than Dim
1368 // as we are not interested in them.
1369 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1370 for (unsigned u = 0; u < Dim; u++) {
1371 isl_constraint *C = isl_inequality_alloc(
1372 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1373 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1374 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1375 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1376 }
1377
1378 // Collect all bounded parts of OnlyDimS.
1379 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1380
1381 // Create the dimensions greater than Dim again.
1382 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1383 NumDimsS - Dim - 1);
1384
1385 // Remove the artificial upper bound parameters again.
1386 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1387
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001388 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001389 return std::make_pair(UnboundedParts, BoundedParts);
1390}
1391
Tobias Grosserc80d6972016-09-02 06:33:33 +00001392/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001393static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1394 __isl_take isl_set *To) {
1395 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1396 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1397 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1398 }
1399 return To;
1400}
1401
Tobias Grosserc80d6972016-09-02 06:33:33 +00001402/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001403static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001404 __isl_take isl_pw_aff *L,
1405 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001406 switch (Pred) {
1407 case ICmpInst::ICMP_EQ:
1408 return isl_pw_aff_eq_set(L, R);
1409 case ICmpInst::ICMP_NE:
1410 return isl_pw_aff_ne_set(L, R);
1411 case ICmpInst::ICMP_SLT:
1412 return isl_pw_aff_lt_set(L, R);
1413 case ICmpInst::ICMP_SLE:
1414 return isl_pw_aff_le_set(L, R);
1415 case ICmpInst::ICMP_SGT:
1416 return isl_pw_aff_gt_set(L, R);
1417 case ICmpInst::ICMP_SGE:
1418 return isl_pw_aff_ge_set(L, R);
1419 case ICmpInst::ICMP_ULT:
1420 return isl_pw_aff_lt_set(L, R);
1421 case ICmpInst::ICMP_UGT:
1422 return isl_pw_aff_gt_set(L, R);
1423 case ICmpInst::ICMP_ULE:
1424 return isl_pw_aff_le_set(L, R);
1425 case ICmpInst::ICMP_UGE:
1426 return isl_pw_aff_ge_set(L, R);
1427 default:
1428 llvm_unreachable("Non integer predicate not supported");
1429 }
1430}
1431
Tobias Grosserc80d6972016-09-02 06:33:33 +00001432/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001433///
1434/// Helper function that will make sure the dimensions of the result have the
1435/// same isl_id's as the @p Domain.
1436static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1437 __isl_take isl_pw_aff *L,
1438 __isl_take isl_pw_aff *R,
1439 __isl_keep isl_set *Domain) {
1440 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1441 return setDimensionIds(Domain, ConsequenceCondSet);
1442}
1443
Tobias Grosserc80d6972016-09-02 06:33:33 +00001444/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001445///
1446/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001447/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1448/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001449static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001450buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1451 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001452 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1453
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001454 Value *Condition = getConditionFromTerminator(SI);
1455 assert(Condition && "No condition for switch");
1456
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001457 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001458 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001459 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001460 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001461
1462 unsigned NumSuccessors = SI->getNumSuccessors();
1463 ConditionSets.resize(NumSuccessors);
1464 for (auto &Case : SI->cases()) {
1465 unsigned Idx = Case.getSuccessorIndex();
1466 ConstantInt *CaseValue = Case.getCaseValue();
1467
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001468 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001469 isl_set *CaseConditionSet =
1470 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1471 ConditionSets[Idx] = isl_set_coalesce(
1472 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1473 }
1474
1475 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1476 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1477 for (unsigned u = 2; u < NumSuccessors; u++)
1478 ConditionSetUnion =
1479 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1480 ConditionSets[0] = setDimensionIds(
1481 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1482
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001483 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001484
1485 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001486}
1487
Tobias Grosserc80d6972016-09-02 06:33:33 +00001488/// Build the conditions sets for the branch condition @p Condition in
1489/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001490///
1491/// This will fill @p ConditionSets with the conditions under which control
1492/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001493/// have as many elements as @p TI has successors. If @p TI is nullptr the
1494/// context under which @p Condition is true/false will be returned as the
1495/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001496static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001497buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1498 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001499 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1500
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001501 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001502 isl_set *ConsequenceCondSet = nullptr;
1503 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1504 if (CCond->isZero())
1505 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1506 else
1507 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1508 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1509 auto Opcode = BinOp->getOpcode();
1510 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1511
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001512 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1513 ConditionSets) &&
1514 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1515 ConditionSets);
1516 if (!Valid) {
1517 while (!ConditionSets.empty())
1518 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001519 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001520 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001521
1522 isl_set_free(ConditionSets.pop_back_val());
1523 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1524 isl_set_free(ConditionSets.pop_back_val());
1525 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1526
1527 if (Opcode == Instruction::And)
1528 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1529 else
1530 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1531 } else {
1532 auto *ICond = dyn_cast<ICmpInst>(Condition);
1533 assert(ICond &&
1534 "Condition of exiting branch was neither constant nor ICmp!");
1535
1536 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001537 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001538 // For unsigned comparisons we assumed the signed bit of neither operand
1539 // to be set. The comparison is equal to a signed comparison under this
1540 // assumption.
1541 bool NonNeg = ICond->isUnsigned();
1542 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1543 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001544 ConsequenceCondSet =
1545 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1546 }
1547
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001548 // If no terminator was given we are only looking for parameter constraints
1549 // under which @p Condition is true/false.
1550 if (!TI)
1551 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001552 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001553 ConsequenceCondSet = isl_set_coalesce(
1554 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001555
Johannes Doerfertb2885792016-04-26 09:20:41 +00001556 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001557 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001558 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001559
Michael Krusef7a4a942016-05-02 12:25:36 +00001560 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001561 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1562 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001563 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001564 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001565 }
1566
Michael Krusef7a4a942016-05-02 12:25:36 +00001567 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001568 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001569 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001570 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001571 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001572 }
1573
1574 ConditionSets.push_back(ConsequenceCondSet);
1575 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001576
1577 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001578}
1579
Tobias Grosserc80d6972016-09-02 06:33:33 +00001580/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001581///
1582/// This will fill @p ConditionSets with the conditions under which control
1583/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1584/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001585static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001586buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001587 __isl_keep isl_set *Domain,
1588 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1589
1590 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001591 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001592
1593 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1594
1595 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001596 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001597 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001598 }
1599
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001600 Value *Condition = getConditionFromTerminator(TI);
1601 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001602
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001603 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001604}
1605
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001606void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001607 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001608
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001609 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001610 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001611}
1612
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001613void ScopStmt::collectSurroundingLoops() {
1614 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1615 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1616 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1617 isl_id_free(DimId);
1618 }
1619}
1620
Michael Kruse55454072017-03-15 22:16:43 +00001621ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001622 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
Michael Kruse55454072017-03-15 22:16:43 +00001623 R(&R), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001624
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001625 BaseName = getIslCompatibleName(
1626 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001627}
1628
Michael Kruse55454072017-03-15 22:16:43 +00001629ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001630 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Michael Kruse55454072017-03-15 22:16:43 +00001631 R(nullptr), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Tobias Grosser75805372011-04-29 06:27:02 +00001632
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001633 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), "",
1634 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001635}
1636
Roman Gareevb3224ad2016-09-14 06:26:09 +00001637ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1638 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1639 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1640 R(nullptr), Build(nullptr) {
1641 BaseName = getIslCompatibleName("CopyStmt_", "",
1642 std::to_string(parent.getCopyStmtsNum()));
1643 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1644 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1645 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1646 auto *Access =
1647 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1648 parent.addAccessFunction(Access);
1649 addAccess(Access);
1650 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1651 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1652 parent.addAccessFunction(Access);
1653 addAccess(Access);
1654}
1655
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001656void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001657 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001658
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001659 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001660 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001661 buildAccessRelations();
1662
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001663 if (DetectReductions)
1664 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001665}
1666
Tobias Grosserc80d6972016-09-02 06:33:33 +00001667/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001668///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001669/// Check if the stored value for @p StoreMA is a binary operator with one or
1670/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001671/// used only once (by @p StoreMA) and its load operands are also used only
1672/// once, we have found a possible reduction chain. It starts at an operand
1673/// load and includes the binary operator and @p StoreMA.
1674///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001675/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001676/// escape this block or into any other store except @p StoreMA.
1677void ScopStmt::collectCandiateReductionLoads(
1678 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1679 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1680 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001681 return;
1682
1683 // Skip if there is not one binary operator between the load and the store
1684 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001685 if (!BinOp)
1686 return;
1687
1688 // Skip if the binary operators has multiple uses
1689 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001690 return;
1691
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001692 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001693 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1694 return;
1695
Johannes Doerfert9890a052014-07-01 00:32:29 +00001696 // Skip if the binary operator is outside the current SCoP
1697 if (BinOp->getParent() != Store->getParent())
1698 return;
1699
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001700 // Skip if it is a multiplicative reduction and we disabled them
1701 if (DisableMultiplicativeReductions &&
1702 (BinOp->getOpcode() == Instruction::Mul ||
1703 BinOp->getOpcode() == Instruction::FMul))
1704 return;
1705
Johannes Doerferte58a0122014-06-27 20:31:28 +00001706 // Check the binary operator operands for a candidate load
1707 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1708 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1709 if (!PossibleLoad0 && !PossibleLoad1)
1710 return;
1711
1712 // A load is only a candidate if it cannot escape (thus has only this use)
1713 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001714 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001715 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001716 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001717 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001718 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001719}
1720
Tobias Grosserc80d6972016-09-02 06:33:33 +00001721/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001722///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001723/// Iterate over all store memory accesses and check for valid binary reduction
1724/// like chains. For all candidates we check if they have the same base address
1725/// and there are no other accesses which overlap with them. The base address
1726/// check rules out impossible reductions candidates early. The overlap check,
1727/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001728/// guarantees that none of the intermediate results will escape during
1729/// execution of the loop nest. We basically check here that no other memory
1730/// access can access the same memory as the potential reduction.
1731void ScopStmt::checkForReductions() {
1732 SmallVector<MemoryAccess *, 2> Loads;
1733 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1734
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001735 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001736 // stores and collecting possible reduction loads.
1737 for (MemoryAccess *StoreMA : MemAccs) {
1738 if (StoreMA->isRead())
1739 continue;
1740
1741 Loads.clear();
1742 collectCandiateReductionLoads(StoreMA, Loads);
1743 for (MemoryAccess *LoadMA : Loads)
1744 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1745 }
1746
1747 // Then check each possible candidate pair.
1748 for (const auto &CandidatePair : Candidates) {
1749 bool Valid = true;
1750 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1751 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1752
1753 // Skip those with obviously unequal base addresses.
1754 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1755 isl_map_free(LoadAccs);
1756 isl_map_free(StoreAccs);
1757 continue;
1758 }
1759
1760 // And check if the remaining for overlap with other memory accesses.
1761 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1762 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1763 isl_set *AllAccs = isl_map_range(AllAccsRel);
1764
1765 for (MemoryAccess *MA : MemAccs) {
1766 if (MA == CandidatePair.first || MA == CandidatePair.second)
1767 continue;
1768
1769 isl_map *AccRel =
1770 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1771 isl_set *Accs = isl_map_range(AccRel);
1772
Tobias Grosser55a7af72016-09-08 14:08:07 +00001773 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001774 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1775 Valid = Valid && isl_set_is_empty(OverlapAccs);
1776 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001777 } else {
1778 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001779 }
1780 }
1781
1782 isl_set_free(AllAccs);
1783 if (!Valid)
1784 continue;
1785
Johannes Doerfertf6183392014-07-01 20:52:51 +00001786 const LoadInst *Load =
1787 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1788 MemoryAccess::ReductionType RT =
1789 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1790
Johannes Doerferte58a0122014-06-27 20:31:28 +00001791 // If no overlapping access was found we mark the load and store as
1792 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001793 CandidatePair.first->markAsReductionLike(RT);
1794 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001795 }
Tobias Grosser75805372011-04-29 06:27:02 +00001796}
1797
Tobias Grosser74394f02013-01-14 22:40:23 +00001798std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001799
Tobias Grosser54839312015-04-21 11:37:25 +00001800std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001801 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001802 if (!S)
1803 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001804 auto Str = stringFromIslObj(S);
1805 isl_map_free(S);
1806 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001807}
1808
Johannes Doerferta3519512016-04-23 13:02:23 +00001809void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1810 isl_set_free(InvalidDomain);
1811 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001812}
1813
Michael Kruse375cb5f2016-02-24 22:08:24 +00001814BasicBlock *ScopStmt::getEntryBlock() const {
1815 if (isBlockStmt())
1816 return getBasicBlock();
1817 return getRegion()->getEntry();
1818}
1819
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001820unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001821
Tobias Grosser75805372011-04-29 06:27:02 +00001822const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1823
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001824Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001825 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001826}
1827
Tobias Grosser74394f02013-01-14 22:40:23 +00001828isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001829
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001830__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001831
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001832__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001833 return isl_set_get_space(Domain);
1834}
1835
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001836__isl_give isl_id *ScopStmt::getDomainId() const {
1837 return isl_set_get_tuple_id(Domain);
1838}
Tobias Grossercd95b772012-08-30 11:49:38 +00001839
Johannes Doerfert7c013572016-04-12 09:57:34 +00001840ScopStmt::~ScopStmt() {
1841 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001842 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001843}
Tobias Grosser75805372011-04-29 06:27:02 +00001844
1845void ScopStmt::print(raw_ostream &OS) const {
1846 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001847 OS.indent(12) << "Domain :=\n";
1848
1849 if (Domain) {
1850 OS.indent(16) << getDomainStr() << ";\n";
1851 } else
1852 OS.indent(16) << "n/a\n";
1853
Tobias Grosser54839312015-04-21 11:37:25 +00001854 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001855
1856 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001857 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001858 } else
1859 OS.indent(16) << "n/a\n";
1860
Tobias Grosser083d3d32014-06-28 08:59:45 +00001861 for (MemoryAccess *Access : MemAccs)
1862 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001863}
1864
1865void ScopStmt::dump() const { print(dbgs()); }
1866
Michael Krusee60eca72017-05-11 22:56:12 +00001867void ScopStmt::removeAccessData(MemoryAccess *MA) {
1868 if (MA->isRead() && MA->isOriginalValueKind()) {
1869 bool Found = ValueReads.erase(MA->getAccessValue());
1870 (void)Found;
1871 assert(Found && "Expected access data not found");
1872 }
1873 if (MA->isWrite() && MA->isOriginalValueKind()) {
1874 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1875 (void)Found;
1876 assert(Found && "Expected access data not found");
1877 }
1878 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1879 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1880 (void)Found;
1881 assert(Found && "Expected access data not found");
1882 }
1883}
1884
Michael Kruse10071822016-05-23 14:45:58 +00001885void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001886 // Remove the memory accesses from this statement together with all scalar
1887 // accesses that were caused by it. MemoryKind::Value READs have no access
1888 // instruction, hence would not be removed by this function. However, it is
1889 // only used for invariant LoadInst accesses, its arguments are always affine,
1890 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1891 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001892 auto Predicate = [&](MemoryAccess *Acc) {
1893 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1894 };
Michael Krusee60eca72017-05-11 22:56:12 +00001895 for (auto *MA : MemAccs) {
1896 if (Predicate(MA))
1897 removeAccessData(MA);
1898 }
Michael Kruse10071822016-05-23 14:45:58 +00001899 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1900 MemAccs.end());
1901 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001902}
1903
Michael Kruse0446d812017-03-10 16:05:24 +00001904void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
1905 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1906 assert(MAIt != MemAccs.end());
1907 MemAccs.erase(MAIt);
1908
Michael Krusee60eca72017-05-11 22:56:12 +00001909 removeAccessData(MA);
1910
Michael Kruse0446d812017-03-10 16:05:24 +00001911 auto It = InstructionToAccess.find(MA->getAccessInstruction());
1912 if (It != InstructionToAccess.end()) {
1913 It->second.remove(MA);
1914 if (It->second.empty())
1915 InstructionToAccess.erase(MA->getAccessInstruction());
1916 }
1917}
1918
Tobias Grosser75805372011-04-29 06:27:02 +00001919//===----------------------------------------------------------------------===//
1920/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001921
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001922void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001923 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1924 isl_set_free(Context);
1925 Context = NewContext;
1926}
1927
Tobias Grosserc80d6972016-09-02 06:33:33 +00001928/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001929struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001930 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001931 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001932
1933public:
1934 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001935 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001936
1937 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1938 ValueToValueMap &VMap) {
1939 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1940 return SSPR.visit(E);
1941 }
1942
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001943 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1944 auto *Start = visit(E->getStart());
1945 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1946 visit(E->getStepRecurrence(SE)),
1947 E->getLoop(), SCEV::FlagAnyWrap);
1948 return SE.getAddExpr(Start, AddRec);
1949 }
1950
1951 const SCEV *visitUnknown(const SCEVUnknown *E) {
1952 if (auto *NewValue = VMap.lookup(E->getValue()))
1953 return SE.getUnknown(NewValue);
1954 return E;
1955 }
1956};
1957
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001958const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001959 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001960}
1961
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001962void Scop::createParameterId(const SCEV *Parameter) {
1963 assert(Parameters.count(Parameter));
1964 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001965
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001966 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001967
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001968 if (UseInstructionNames) {
1969 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1970 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001971
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001972 // If this parameter references a specific Value and this value has a name
1973 // we use this name as it is likely to be unique and more useful than just
1974 // a number.
1975 if (Val->hasName())
1976 ParameterName = Val->getName();
1977 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1978 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1979 if (LoadOrigin->hasName()) {
1980 ParameterName += "_loaded_from_";
1981 ParameterName +=
1982 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1983 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001984 }
1985 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001986
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001987 ParameterName = getIslCompatibleName("", ParameterName, "");
1988 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001989
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001990 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1991 const_cast<void *>((const void *)Parameter));
1992 ParameterIds[Parameter] = Id;
1993}
1994
1995void Scop::addParams(const ParameterSetTy &NewParameters) {
1996 for (const SCEV *Parameter : NewParameters) {
1997 // Normalize the SCEV to get the representing element for an invariant load.
1998 Parameter = extractConstantFactor(Parameter, *SE).second;
1999 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2000
2001 if (Parameters.insert(Parameter))
2002 createParameterId(Parameter);
2003 }
2004}
2005
2006__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
2007 // Normalize the SCEV to get the representing element for an invariant load.
2008 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2009 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00002010}
Tobias Grosser75805372011-04-29 06:27:02 +00002011
Michael Krused56b90a2016-09-01 09:03:27 +00002012__isl_give isl_set *
2013Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002014 isl_set *DomainContext = isl_union_set_params(getDomains());
2015 return isl_set_intersect_params(C, DomainContext);
2016}
2017
Johannes Doerferte0b08072016-05-23 12:43:44 +00002018bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2019 return DT.dominates(BB, getEntry());
2020}
2021
Michael Kruse89b1f942017-03-17 13:56:53 +00002022void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
2023 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002024 auto &F = getFunction();
Michael Kruse89b1f942017-03-17 13:56:53 +00002025 for (auto &Assumption : AC.assumptions()) {
2026 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2027 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002028 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002029
Michael Kruse89b1f942017-03-17 13:56:53 +00002030 bool InScop = contains(CI);
2031 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2032 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002033
Michael Kruse89b1f942017-03-17 13:56:53 +00002034 auto *L = LI.getLoopFor(CI->getParent());
2035 auto *Val = CI->getArgOperand(0);
2036 ParameterSetTy DetectedParams;
2037 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
2038 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
2039 CI->getDebugLoc(),
2040 "Non-affine user assumption ignored.");
2041 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002042 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002043
2044 // Collect all newly introduced parameters.
2045 ParameterSetTy NewParams;
2046 for (auto *Param : DetectedParams) {
2047 Param = extractConstantFactor(Param, *SE).second;
2048 Param = getRepresentingInvariantLoadSCEV(Param);
2049 if (Parameters.count(Param))
2050 continue;
2051 NewParams.insert(Param);
2052 }
2053
2054 SmallVector<isl_set *, 2> ConditionSets;
2055 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
2056 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
2057 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
2058 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
2059 isl_set_free(Dom);
2060
2061 if (!Valid)
2062 continue;
2063
2064 isl_set *AssumptionCtx = nullptr;
2065 if (InScop) {
2066 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2067 isl_set_free(ConditionSets[0]);
2068 } else {
2069 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2070 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2071 }
2072
2073 // Project out newly introduced parameters as they are not otherwise useful.
2074 if (!NewParams.empty()) {
2075 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2076 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2077 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2078 isl_id_free(Id);
2079
2080 if (!NewParams.count(Param))
2081 continue;
2082
2083 AssumptionCtx =
2084 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2085 }
2086 }
2087
2088 emitOptimizationRemarkAnalysis(
2089 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
2090 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
2091 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002092 }
2093}
2094
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002095void Scop::addUserContext() {
2096 if (UserContextStr.empty())
2097 return;
2098
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002099 isl_set *UserContext =
2100 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002101 isl_space *Space = getParamSpace();
2102 if (isl_space_dim(Space, isl_dim_param) !=
2103 isl_set_dim(UserContext, isl_dim_param)) {
2104 auto SpaceStr = isl_space_to_str(Space);
2105 errs() << "Error: the context provided in -polly-context has not the same "
2106 << "number of dimensions than the computed context. Due to this "
2107 << "mismatch, the -polly-context option is ignored. Please provide "
2108 << "the context in the parameter space: " << SpaceStr << ".\n";
2109 free(SpaceStr);
2110 isl_set_free(UserContext);
2111 isl_space_free(Space);
2112 return;
2113 }
2114
2115 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002116 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2117 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002118
2119 if (strcmp(NameContext, NameUserContext) != 0) {
2120 auto SpaceStr = isl_space_to_str(Space);
2121 errs() << "Error: the name of dimension " << i
2122 << " provided in -polly-context "
2123 << "is '" << NameUserContext << "', but the name in the computed "
2124 << "context is '" << NameContext
2125 << "'. Due to this name mismatch, "
2126 << "the -polly-context option is ignored. Please provide "
2127 << "the context in the parameter space: " << SpaceStr << ".\n";
2128 free(SpaceStr);
2129 isl_set_free(UserContext);
2130 isl_space_free(Space);
2131 return;
2132 }
2133
2134 UserContext =
2135 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2136 isl_space_get_dim_id(Space, isl_dim_param, i));
2137 }
2138
2139 Context = isl_set_intersect(Context, UserContext);
2140 isl_space_free(Space);
2141}
2142
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002143void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002144 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002145
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002146 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002147 for (LoadInst *LInst : RIL) {
2148 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2149
Johannes Doerfert96e54712016-02-07 17:30:13 +00002150 Type *Ty = LInst->getType();
2151 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002152 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002153 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002154 continue;
2155 }
2156
2157 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002158 InvariantEquivClasses.emplace_back(
2159 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002160 }
2161}
2162
Tobias Grosser6be480c2011-11-08 15:41:13 +00002163void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002164 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002165 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002166 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002167 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002168}
2169
Tobias Grosser18daaca2012-05-22 10:47:27 +00002170void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002171 unsigned PDim = 0;
2172 for (auto *Parameter : Parameters) {
2173 ConstantRange SRange = SE->getSignedRange(Parameter);
2174 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002175 }
2176}
2177
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002178void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002179 if (PollyIgnoreParamBounds)
2180 return;
2181
Tobias Grosser6be480c2011-11-08 15:41:13 +00002182 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002183 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002184
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002185 unsigned PDim = 0;
2186 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002187 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002188 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002189 }
2190
2191 // Align the parameters of all data structures to the model.
2192 Context = isl_set_align_params(Context, Space);
2193
Johannes Doerferta60ad842016-05-10 12:18:22 +00002194 // As all parameters are known add bounds to them.
2195 addParameterBounds();
2196
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002197 for (ScopStmt &Stmt : *this)
2198 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002199
2200 // Simplify the schedule according to the context too.
2201 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002202}
2203
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002204static __isl_give isl_set *
2205simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2206 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002207 // If we have modeled all blocks in the SCoP that have side effects we can
2208 // simplify the context with the constraints that are needed for anything to
2209 // be executed at all. However, if we have error blocks in the SCoP we already
2210 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002211 // domains, thus we cannot use the remaining domain to simplify the
2212 // assumptions.
2213 if (!S.hasErrorBlock()) {
2214 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2215 AssumptionContext =
2216 isl_set_gist_params(AssumptionContext, DomainParameters);
2217 }
2218
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002219 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2220 return AssumptionContext;
2221}
2222
2223void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002224 // The parameter constraints of the iteration domains give us a set of
2225 // constraints that need to hold for all cases where at least a single
2226 // statement iteration is executed in the whole scop. We now simplify the
2227 // assumed context under the assumption that such constraints hold and at
2228 // least a single statement iteration is executed. For cases where no
2229 // statement instances are executed, the assumptions we have taken about
2230 // the executed code do not matter and can be changed.
2231 //
2232 // WARNING: This only holds if the assumptions we have taken do not reduce
2233 // the set of statement instances that are executed. Otherwise we
2234 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002235 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002236 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002237 // performed. In such a case, modifying the run-time conditions and
2238 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002239 // to not be executed.
2240 //
2241 // Example:
2242 //
2243 // When delinearizing the following code:
2244 //
2245 // for (long i = 0; i < 100; i++)
2246 // for (long j = 0; j < m; j++)
2247 // A[i+p][j] = 1.0;
2248 //
2249 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002250 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002251 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002252 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002253 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002254}
2255
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002256struct MinMaxData {
2257 Scop::MinMaxVectorTy &MinMaxAccesses;
2258 Scop &S;
2259};
2260
Tobias Grosserc80d6972016-09-02 06:33:33 +00002261/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002262static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002263 auto Data = (struct MinMaxData *)User;
2264 Scop::MinMaxVectorTy *MinMaxAccesses = &Data->MinMaxAccesses;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002265 isl_pw_multi_aff *MinPMA, *MaxPMA;
2266 isl_pw_aff *LastDimAff;
2267 isl_aff *OneAff;
2268 unsigned Pos;
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002269 isl_ctx *Ctx = isl_set_get_ctx(Set);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002270
Johannes Doerfert6296d952016-04-22 11:38:19 +00002271 Set = isl_set_remove_divs(Set);
2272
Tobias Grosser90411a92017-02-16 19:11:33 +00002273 if (isl_set_n_basic_set(Set) >= MaxDisjunctsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002274 isl_set_free(Set);
2275 return isl_stat_error;
2276 }
2277
Johannes Doerfert9143d672014-09-27 11:02:39 +00002278 // Restrict the number of parameters involved in the access as the lexmin/
2279 // lexmax computation will take too long if this number is high.
2280 //
2281 // Experiments with a simple test case using an i7 4800MQ:
2282 //
2283 // #Parameters involved | Time (in sec)
2284 // 6 | 0.01
2285 // 7 | 0.04
2286 // 8 | 0.12
2287 // 9 | 0.40
2288 // 10 | 1.54
2289 // 11 | 6.78
2290 // 12 | 30.38
2291 //
2292 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2293 unsigned InvolvedParams = 0;
2294 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2295 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2296 InvolvedParams++;
2297
2298 if (InvolvedParams > RunTimeChecksMaxParameters) {
2299 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002300 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002301 }
2302 }
2303
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002304 {
2305 IslMaxOperationsGuard MaxOpGuard(isl_set_get_ctx(Set), OptComputeOut);
2306 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2307 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2308 }
2309
2310 if (isl_ctx_last_error(Ctx) == isl_error_quota) {
2311 MinPMA = isl_pw_multi_aff_free(MinPMA);
2312 MaxPMA = isl_pw_multi_aff_free(MaxPMA);
2313 Set = isl_set_free(Set);
2314 Data->S.invalidate(COMPLEXITY, DebugLoc());
2315 return isl_stat_error;
2316 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002317
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002318 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2319 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2320
Johannes Doerfertb164c792014-09-18 11:17:17 +00002321 // Adjust the last dimension of the maximal access by one as we want to
2322 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2323 // we test during code generation might now point after the end of the
2324 // allocated array but we will never dereference it anyway.
2325 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2326 "Assumed at least one output dimension");
2327 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2328 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2329 OneAff = isl_aff_zero_on_domain(
2330 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2331 OneAff = isl_aff_add_constant_si(OneAff, 1);
2332 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2333 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2334
2335 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2336
2337 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002338 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002339}
2340
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002341static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2342 isl_set *Domain = MA->getStatement()->getDomain();
2343 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2344 return isl_set_reset_tuple_id(Domain);
2345}
2346
Tobias Grosserc80d6972016-09-02 06:33:33 +00002347/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002348static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002349 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002350
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002351 struct MinMaxData Data = {MinMaxAccesses, S};
2352 Data.MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002353
2354 isl_union_set *Domains = S.getDomains();
2355 isl_union_map *Accesses = isl_union_map_empty(S.getParamSpace());
2356
2357 for (MemoryAccess *MA : AliasGroup)
2358 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2359
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002360 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2361 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002362 Locations = isl_union_set_coalesce(Locations);
2363 Locations = isl_union_set_detect_equalities(Locations);
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002364 bool Valid =
2365 (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess, &Data));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002366 isl_union_set_free(Locations);
2367 return Valid;
2368}
2369
Tobias Grosserc80d6972016-09-02 06:33:33 +00002370/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002371///
2372///{
2373
Tobias Grosserc80d6972016-09-02 06:33:33 +00002374/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002375static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2376 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2377 : RN->getNodeAs<BasicBlock>();
2378}
2379
Tobias Grosserc80d6972016-09-02 06:33:33 +00002380/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002381static inline BasicBlock *
2382getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002383 if (RN->isSubRegion()) {
2384 assert(idx == 0);
2385 return RN->getNodeAs<Region>()->getExit();
2386 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002387 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002388}
2389
Tobias Grosserc80d6972016-09-02 06:33:33 +00002390/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002391static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002392 if (!RN->isSubRegion()) {
2393 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2394 Loop *L = LI.getLoopFor(BB);
2395
2396 // Unreachable statements are not considered to belong to a LLVM loop, as
2397 // they are not part of an actual loop in the control flow graph.
2398 // Nevertheless, we handle certain unreachable statements that are common
2399 // when modeling run-time bounds checks as being part of the loop to be
2400 // able to model them and to later eliminate the run-time bounds checks.
2401 //
2402 // Specifically, for basic blocks that terminate in an unreachable and
2403 // where the immeditate predecessor is part of a loop, we assume these
2404 // basic blocks belong to the loop the predecessor belongs to. This
2405 // allows us to model the following code.
2406 //
2407 // for (i = 0; i < N; i++) {
2408 // if (i > 1024)
2409 // abort(); <- this abort might be translated to an
2410 // unreachable
2411 //
2412 // A[i] = ...
2413 // }
2414 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2415 L = LI.getLoopFor(BB->getPrevNode());
2416 return L;
2417 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002418
2419 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2420 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2421 while (L && NonAffineSubRegion->contains(L))
2422 L = L->getParentLoop();
2423 return L;
2424}
2425
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002426/// Get the number of blocks in @p L.
2427///
2428/// The number of blocks in a loop are the number of basic blocks actually
2429/// belonging to the loop, as well as all single basic blocks that the loop
2430/// exits to and which terminate in an unreachable instruction. We do not
2431/// allow such basic blocks in the exit of a scop, hence they belong to the
2432/// scop and represent run-time conditions which we want to model and
2433/// subsequently speculate away.
2434///
2435/// @see getRegionNodeLoop for additional details.
2436long getNumBlocksInLoop(Loop *L) {
2437 long NumBlocks = L->getNumBlocks();
2438 SmallVector<llvm::BasicBlock *, 4> ExitBlocks;
2439 L->getExitBlocks(ExitBlocks);
2440
2441 for (auto ExitBlock : ExitBlocks) {
2442 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2443 NumBlocks++;
2444 }
2445 return NumBlocks;
2446}
2447
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002448static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2449 if (!RN->isSubRegion())
2450 return 1;
2451
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002452 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002453 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002454}
2455
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002456static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2457 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002458 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002459 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002460 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002461 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002462 return true;
2463 return false;
2464}
2465
Johannes Doerfert96425c22015-08-30 21:13:53 +00002466///}
2467
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002468static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2469 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002470 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002471 isl_id *DimId =
2472 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2473 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2474}
2475
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002476__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002477 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002478}
2479
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002480__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002481 auto DIt = DomainMap.find(BB);
2482 if (DIt != DomainMap.end())
2483 return isl_set_copy(DIt->getSecond());
2484
2485 auto &RI = *R.getRegionInfo();
2486 auto *BBR = RI.getRegionFor(BB);
2487 while (BBR->getEntry() == BB)
2488 BBR = BBR->getParent();
2489 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002490}
2491
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002492bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002493
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002494 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002495 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002496 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2497 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002498 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002499
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002500 while (LD-- >= 0) {
2501 S = addDomainDimId(S, LD + 1, L);
2502 L = L->getParentLoop();
2503 }
2504
Johannes Doerferta3519512016-04-23 13:02:23 +00002505 // Initialize the invalid domain.
2506 auto *EntryStmt = getStmtFor(EntryBB);
2507 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2508
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002509 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002510
Johannes Doerfert432658d2016-01-26 11:01:41 +00002511 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002512 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002513
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002514 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002515 return false;
2516
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002517 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002518 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002519
2520 // Error blocks and blocks dominated by them have been assumed to never be
2521 // executed. Representing them in the Scop does not add any value. In fact,
2522 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002523 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002524 // will cause problems when building up a ScopStmt for them.
2525 // Furthermore, basic blocks dominated by error blocks may reference
2526 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002527 // can themselves not be constructed properly. To this end we will replace
2528 // the domains of error blocks and those only reachable via error blocks
2529 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002530 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002531 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002532 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002533 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002534
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002535 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002536}
2537
Tobias Grosserc80d6972016-09-02 06:33:33 +00002538/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002539/// to be compatible to domains constructed for loop @p NewL.
2540///
2541/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2542/// edge from @p OldL to @p NewL.
2543static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2544 __isl_take isl_set *Dom,
2545 Loop *OldL, Loop *NewL) {
2546
2547 // If the loops are the same there is nothing to do.
2548 if (NewL == OldL)
2549 return Dom;
2550
2551 int OldDepth = S.getRelativeLoopDepth(OldL);
2552 int NewDepth = S.getRelativeLoopDepth(NewL);
2553 // If both loops are non-affine loops there is nothing to do.
2554 if (OldDepth == -1 && NewDepth == -1)
2555 return Dom;
2556
2557 // Distinguish three cases:
2558 // 1) The depth is the same but the loops are not.
2559 // => One loop was left one was entered.
2560 // 2) The depth increased from OldL to NewL.
2561 // => One loop was entered, none was left.
2562 // 3) The depth decreased from OldL to NewL.
2563 // => Loops were left were difference of the depths defines how many.
2564 if (OldDepth == NewDepth) {
2565 assert(OldL->getParentLoop() == NewL->getParentLoop());
2566 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2567 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2568 Dom = addDomainDimId(Dom, NewDepth, NewL);
2569 } else if (OldDepth < NewDepth) {
2570 assert(OldDepth + 1 == NewDepth);
2571 auto &R = S.getRegion();
2572 (void)R;
2573 assert(NewL->getParentLoop() == OldL ||
2574 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2575 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2576 Dom = addDomainDimId(Dom, NewDepth, NewL);
2577 } else {
2578 assert(OldDepth > NewDepth);
2579 int Diff = OldDepth - NewDepth;
2580 int NumDim = isl_set_n_dim(Dom);
2581 assert(NumDim >= Diff);
2582 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2583 }
2584
2585 return Dom;
2586}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002587
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002588bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2589 LoopInfo &LI) {
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002590 ReversePostOrderTraversal<Region *> RTraversal(R);
2591 for (auto *RN : RTraversal) {
2592
2593 // Recurse for affine subregions but go on for basic blocks and non-affine
2594 // subregions.
2595 if (RN->isSubRegion()) {
2596 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002597 if (!isNonAffineSubRegion(SubRegion)) {
2598 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002599 continue;
2600 }
2601 }
2602
2603 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2604 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002605 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002606 isl_set *&Domain = DomainMap[BB];
2607 assert(Domain && "Cannot propagate a nullptr");
2608
Johannes Doerferta3519512016-04-23 13:02:23 +00002609 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002610 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002611 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002612
Johannes Doerferta3519512016-04-23 13:02:23 +00002613 if (!IsInvalidBlock) {
2614 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002615 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002616 isl_set_free(InvalidDomain);
2617 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002618 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2619 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2620 AS_RESTRICTION);
2621 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002622 }
2623
Johannes Doerferta3519512016-04-23 13:02:23 +00002624 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002625 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002626 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002627 }
2628
Johannes Doerferta3519512016-04-23 13:02:23 +00002629 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002630 auto *TI = BB->getTerminator();
2631 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2632 for (unsigned u = 0; u < NumSuccs; u++) {
2633 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002634 auto *SuccStmt = getStmtFor(SuccBB);
2635
2636 // Skip successors outside the SCoP.
2637 if (!SuccStmt)
2638 continue;
2639
Johannes Doerferte4459a22016-04-25 13:34:50 +00002640 // Skip backedges.
2641 if (DT.dominates(SuccBB, BB))
2642 continue;
2643
Michael Kruse55454072017-03-15 22:16:43 +00002644 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta3519512016-04-23 13:02:23 +00002645 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2646 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2647 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2648 SuccInvalidDomain =
2649 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2650 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2651 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2652 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002653
Michael Krusebc150122016-05-02 12:25:18 +00002654 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002655 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002656 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002657 continue;
2658
Johannes Doerferta3519512016-04-23 13:02:23 +00002659 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002660 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002661 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002662 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002663
2664 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002665 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002666
2667 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002668}
2669
Johannes Doerfert642594a2016-04-04 07:57:39 +00002670void Scop::propagateDomainConstraintsToRegionExit(
2671 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002672 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002673
2674 // Check if the block @p BB is the entry of a region. If so we propagate it's
2675 // domain to the exit block of the region. Otherwise we are done.
2676 auto *RI = R.getRegionInfo();
2677 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2678 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002679 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002680 return;
2681
Johannes Doerfert642594a2016-04-04 07:57:39 +00002682 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002683 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002684 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002685 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002686 SmallVector<BasicBlock *, 4> LatchBBs;
2687 BBLoop->getLoopLatches(LatchBBs);
2688 for (auto *LatchBB : LatchBBs)
2689 if (BB != LatchBB && BBReg->contains(LatchBB))
2690 return;
2691 L = L->getParentLoop();
2692 }
2693
2694 auto *Domain = DomainMap[BB];
2695 assert(Domain && "Cannot propagate a nullptr");
2696
Michael Kruse55454072017-03-15 22:16:43 +00002697 auto *ExitStmt = getStmtFor(ExitBB);
2698 auto *ExitBBLoop = ExitStmt->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002699
2700 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2701 // adjust the domain before we can propagate it.
2702 auto *AdjustedDomain =
2703 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2704 auto *&ExitDomain = DomainMap[ExitBB];
2705
2706 // If the exit domain is not yet created we set it otherwise we "add" the
2707 // current domain.
2708 ExitDomain =
2709 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2710
Johannes Doerferta3519512016-04-23 13:02:23 +00002711 // Initialize the invalid domain.
Johannes Doerferta3519512016-04-23 13:02:23 +00002712 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2713
Johannes Doerfert642594a2016-04-04 07:57:39 +00002714 FinishedExitBlocks.insert(ExitBB);
2715}
2716
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002717bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2718 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002719 // To create the domain for each block in R we iterate over all blocks and
2720 // subregions in R and propagate the conditions under which the current region
2721 // element is executed. To this end we iterate in reverse post order over R as
2722 // it ensures that we first visit all predecessors of a region node (either a
2723 // basic block or a subregion) before we visit the region node itself.
2724 // Initially, only the domain for the SCoP region entry block is set and from
2725 // there we propagate the current domain to all successors, however we add the
2726 // condition that the successor is actually executed next.
2727 // As we are only interested in non-loop carried constraints here we can
2728 // simply skip loop back edges.
2729
Johannes Doerfert642594a2016-04-04 07:57:39 +00002730 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002731 ReversePostOrderTraversal<Region *> RTraversal(R);
2732 for (auto *RN : RTraversal) {
2733
2734 // Recurse for affine subregions but go on for basic blocks and non-affine
2735 // subregions.
2736 if (RN->isSubRegion()) {
2737 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002738 if (!isNonAffineSubRegion(SubRegion)) {
2739 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002740 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002741 continue;
2742 }
2743 }
2744
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002745 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002746 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002747
Johannes Doerfert96425c22015-08-30 21:13:53 +00002748 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002749 TerminatorInst *TI = BB->getTerminator();
2750
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002751 if (isa<UnreachableInst>(TI))
2752 continue;
2753
Johannes Doerfertf5673802015-10-01 23:48:18 +00002754 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002755 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002756 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002757 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002758
Johannes Doerfert642594a2016-04-04 07:57:39 +00002759 auto *BBLoop = getRegionNodeLoop(RN, LI);
2760 // Propagate the domain from BB directly to blocks that have a superset
2761 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002762 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002763
2764 // If all successors of BB have been set a domain through the propagation
2765 // above we do not need to build condition sets but can just skip this
2766 // block. However, it is important to note that this is a local property
2767 // with regards to the region @p R. To this end FinishedExitBlocks is a
2768 // local variable.
2769 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2770 return FinishedExitBlocks.count(SuccBB);
2771 };
2772 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2773 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002774
2775 // Build the condition sets for the successor nodes of the current region
2776 // node. If it is a non-affine subregion we will always execute the single
2777 // exit node, hence the single entry node domain is the condition set. For
2778 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002779 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002780 if (RN->isSubRegion())
2781 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002782 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2783 ConditionSets))
2784 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002785
2786 // Now iterate over the successors and set their initial domain based on
2787 // their condition set. We skip back edges here and have to be careful when
2788 // we leave a loop not to keep constraints over a dimension that doesn't
2789 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002790 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002791 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002792 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002793 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002794
Johannes Doerfert535de032016-04-19 14:49:05 +00002795 auto *SuccStmt = getStmtFor(SuccBB);
2796 // Skip blocks outside the region.
2797 if (!SuccStmt) {
2798 isl_set_free(CondSet);
2799 continue;
2800 }
2801
Johannes Doerfert642594a2016-04-04 07:57:39 +00002802 // If we propagate the domain of some block to "SuccBB" we do not have to
2803 // adjust the domain.
2804 if (FinishedExitBlocks.count(SuccBB)) {
2805 isl_set_free(CondSet);
2806 continue;
2807 }
2808
Johannes Doerfert96425c22015-08-30 21:13:53 +00002809 // Skip back edges.
2810 if (DT.dominates(SuccBB, BB)) {
2811 isl_set_free(CondSet);
2812 continue;
2813 }
2814
Michael Kruse55454072017-03-15 22:16:43 +00002815 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002816 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002817
2818 // Set the domain for the successor or merge it with an existing domain in
2819 // case there are multiple paths (without loop back edges) to the
2820 // successor block.
2821 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002822
Johannes Doerferta3519512016-04-23 13:02:23 +00002823 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002824 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002825 } else {
2826 // Initialize the invalid domain.
2827 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2828 SuccDomain = CondSet;
2829 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002830
Michael Krusebc150122016-05-02 12:25:18 +00002831 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002832 // In case this happens we will clean up and bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002833 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002834 continue;
2835
2836 invalidate(COMPLEXITY, DebugLoc());
2837 while (++u < ConditionSets.size())
2838 isl_set_free(ConditionSets[u]);
2839 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002840 }
2841 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002842
2843 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002844}
2845
Michael Krused56b90a2016-09-01 09:03:27 +00002846__isl_give isl_set *
2847Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2848 __isl_keep isl_set *Domain,
2849 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002850 // If @p BB is the ScopEntry we are done
2851 if (R.getEntry() == BB)
2852 return isl_set_universe(isl_set_get_space(Domain));
2853
Johannes Doerfert642594a2016-04-04 07:57:39 +00002854 // The region info of this function.
2855 auto &RI = *R.getRegionInfo();
2856
Michael Kruse55454072017-03-15 22:16:43 +00002857 auto *BBLoop = getStmtFor(BB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002858
2859 // A domain to collect all predecessor domains, thus all conditions under
2860 // which the block is executed. To this end we start with the empty domain.
2861 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2862
2863 // Set of regions of which the entry block domain has been propagated to BB.
2864 // all predecessors inside any of the regions can be skipped.
2865 SmallSet<Region *, 8> PropagatedRegions;
2866
2867 for (auto *PredBB : predecessors(BB)) {
2868 // Skip backedges.
2869 if (DT.dominates(BB, PredBB))
2870 continue;
2871
2872 // If the predecessor is in a region we used for propagation we can skip it.
2873 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2874 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2875 PredBBInRegion)) {
2876 continue;
2877 }
2878
2879 // Check if there is a valid region we can use for propagation, thus look
2880 // for a region that contains the predecessor and has @p BB as exit block.
2881 auto *PredR = RI.getRegionFor(PredBB);
2882 while (PredR->getExit() != BB && !PredR->contains(BB))
2883 PredR->getParent();
2884
2885 // If a valid region for propagation was found use the entry of that region
2886 // for propagation, otherwise the PredBB directly.
2887 if (PredR->getExit() == BB) {
2888 PredBB = PredR->getEntry();
2889 PropagatedRegions.insert(PredR);
2890 }
2891
Johannes Doerfert41cda152016-04-08 10:32:26 +00002892 auto *PredBBDom = getDomainConditions(PredBB);
Michael Kruse55454072017-03-15 22:16:43 +00002893 auto *PredBBLoop = getStmtFor(PredBB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002894 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2895
2896 PredDom = isl_set_union(PredDom, PredBBDom);
2897 }
2898
2899 return PredDom;
2900}
2901
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002902bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2903 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002904 // Iterate over the region R and propagate the domain constrains from the
2905 // predecessors to the current node. In contrast to the
2906 // buildDomainsWithBranchConstraints function, this one will pull the domain
2907 // information from the predecessors instead of pushing it to the successors.
2908 // Additionally, we assume the domains to be already present in the domain
2909 // map here. However, we iterate again in reverse post order so we know all
2910 // predecessors have been visited before a block or non-affine subregion is
2911 // visited.
2912
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002913 ReversePostOrderTraversal<Region *> RTraversal(R);
2914 for (auto *RN : RTraversal) {
2915
2916 // Recurse for affine subregions but go on for basic blocks and non-affine
2917 // subregions.
2918 if (RN->isSubRegion()) {
2919 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002920 if (!isNonAffineSubRegion(SubRegion)) {
2921 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002922 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002923 continue;
2924 }
2925 }
2926
2927 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002928 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002929 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002930
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002931 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002932 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002933 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002934 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002935
Johannes Doerfert642594a2016-04-04 07:57:39 +00002936 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002937 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002938 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2939 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002940 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002941
2942 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002943}
2944
Tobias Grosserc80d6972016-09-02 06:33:33 +00002945/// Create a map to map from a given iteration to a subsequent iteration.
2946///
2947/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2948/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002949/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002950///
2951/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002952static __isl_give isl_map *
2953createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2954 auto *MapSpace = isl_space_map_from_set(SetSpace);
2955 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00002956 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002957 if (u != Dim)
2958 NextIterationMap =
2959 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2960 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2961 C = isl_constraint_set_constant_si(C, 1);
2962 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2963 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2964 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2965 return NextIterationMap;
2966}
2967
Johannes Doerfert297c7202016-05-10 13:06:42 +00002968bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002969 int LoopDepth = getRelativeLoopDepth(L);
2970 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002971
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002972 BasicBlock *HeaderBB = L->getHeader();
2973 assert(DomainMap.count(HeaderBB));
2974 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002975
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002976 isl_map *NextIterationMap =
2977 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002978
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002979 isl_set *UnionBackedgeCondition =
2980 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002981
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002982 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2983 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002984
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002985 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002986
2987 // If the latch is only reachable via error statements we skip it.
2988 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2989 if (!LatchBBDom)
2990 continue;
2991
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002992 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002993
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002994 TerminatorInst *TI = LatchBB->getTerminator();
2995 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00002996 assert(BI && "Only branch instructions allowed in loop latches");
2997
2998 if (BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002999 BackedgeCondition = isl_set_copy(LatchBBDom);
3000 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003001 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003002 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00003003 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
Michael Krusee1dc3872016-11-03 15:19:41 +00003004 ConditionSets)) {
3005 isl_map_free(NextIterationMap);
3006 isl_set_free(UnionBackedgeCondition);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003007 return false;
Michael Krusee1dc3872016-11-03 15:19:41 +00003008 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003009
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003010 // Free the non back edge condition set as we do not need it.
3011 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003012
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003013 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003014 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003015
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003016 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3017 assert(LatchLoopDepth >= LoopDepth);
3018 BackedgeCondition =
3019 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
3020 LatchLoopDepth - LoopDepth);
3021 UnionBackedgeCondition =
3022 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003023 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003024
3025 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
3026 for (int i = 0; i < LoopDepth; i++)
3027 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
3028
3029 isl_set *UnionBackedgeConditionComplement =
3030 isl_set_complement(UnionBackedgeCondition);
3031 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
3032 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
3033 UnionBackedgeConditionComplement =
3034 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
3035 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
3036 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
3037
3038 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
3039 HeaderBBDom = Parts.second;
3040
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003041 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3042 // the bounded assumptions to the context as they are already implied by the
3043 // <nsw> tag.
3044 if (Affinator.hasNSWAddRecForLoop(L)) {
3045 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003046 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003047 }
3048
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003049 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003050 recordAssumption(INFINITELOOP, UnboundedCtx,
3051 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003052 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003053}
3054
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003055MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003056 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003057
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003058 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003059 if (!PointerBaseInst)
3060 return nullptr;
3061
3062 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3063 if (!BasePtrStmt)
3064 return nullptr;
3065
3066 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3067}
3068
3069bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
3070 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003071 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
3072 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
3073 bool Hoistable = NHCtx != nullptr;
3074 isl_set_free(NHCtx);
3075 return !Hoistable;
3076 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003077
Tobias Grosserbe372d52017-02-09 10:11:58 +00003078 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003079 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003080 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003081 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003082
3083 return false;
3084}
3085
Johannes Doerfert5210da52016-06-02 11:06:54 +00003086bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003087 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003088 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003089
Johannes Doerfertcd195322016-11-17 21:41:08 +00003090 if (buildAliasGroups(AA)) {
3091 // Aliasing assumptions do not go through addAssumption but we still want to
3092 // collect statistics so we do it here explicitly.
3093 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003094 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003095 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003096 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003097
3098 // If a problem occurs while building the alias groups we need to delete
3099 // this SCoP and pretend it wasn't valid in the first place. To this end
3100 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003101 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003102
3103 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3104 << " could not be created as the number of parameters involved "
3105 "is too high. The SCoP will be "
3106 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3107 "the maximal number of parameters but be advised that the "
3108 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003109 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003110}
3111
Tobias Grosser889830b2017-02-09 23:12:22 +00003112std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003113Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003114 AliasSetTracker AST(AA);
3115
3116 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003117 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003118 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003119
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003120 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003121 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3122 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003123
3124 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003125 if (StmtDomainEmpty)
3126 continue;
3127
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003128 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003129 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003130 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003131 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003132 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003133 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003134 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003135 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003136 else
3137 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003138 AST.add(Acc);
3139 }
3140 }
3141
Tobias Grosser9edcf072017-01-16 14:07:57 +00003142 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003143 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003144 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003145 continue;
3146 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003147 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003148 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003149 if (AG.size() < 2)
3150 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003151 AliasGroups.push_back(std::move(AG));
3152 }
3153
Tobias Grosser9edcf072017-01-16 14:07:57 +00003154 return std::make_tuple(AliasGroups, HasWriteAccess);
3155}
3156
Tobias Grossere39f9122017-01-16 14:08:00 +00003157void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003158 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3159 AliasGroupTy NewAG;
3160 AliasGroupTy &AG = AliasGroups[u];
3161 AliasGroupTy::iterator AGI = AG.begin();
3162 isl_set *AGDomain = getAccessDomain(*AGI);
3163 while (AGI != AG.end()) {
3164 MemoryAccess *MA = *AGI;
3165 isl_set *MADomain = getAccessDomain(MA);
3166 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3167 NewAG.push_back(MA);
3168 AGI = AG.erase(AGI);
3169 isl_set_free(MADomain);
3170 } else {
3171 AGDomain = isl_set_union(AGDomain, MADomain);
3172 AGI++;
3173 }
3174 }
3175 if (NewAG.size() > 1)
3176 AliasGroups.push_back(std::move(NewAG));
3177 isl_set_free(AGDomain);
3178 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003179}
3180
3181bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3182 // To create sound alias checks we perform the following steps:
3183 // o) We partition each group into read only and non read only accesses.
3184 // o) For each group with more than one base pointer we then compute minimal
3185 // and maximal accesses to each array of a group in read only and non
3186 // read only partitions separately.
3187 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003188 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003189
3190 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3191
3192 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003193
Johannes Doerfert13771732014-10-01 12:40:46 +00003194 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003195 bool Valid = buildAliasGroup(AG, HasWriteAccess);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003196 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003197 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003198 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003199
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003200 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003201}
3202
Tobias Grosser77f32572017-01-16 15:49:07 +00003203bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003204 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003205 AliasGroupTy ReadOnlyAccesses;
3206 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003207 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003208 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003209
3210 auto &F = getFunction();
3211
3212 if (AliasGroup.size() < 2)
3213 return true;
3214
3215 for (MemoryAccess *Access : AliasGroup) {
3216 emitOptimizationRemarkAnalysis(
3217 F.getContext(), DEBUG_TYPE, F,
3218 Access->getAccessInstruction()->getDebugLoc(),
3219 "Possibly aliasing pointer, use restrict keyword.");
3220
Tobias Grosser889830b2017-02-09 23:12:22 +00003221 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3222 if (HasWriteAccess.count(Array)) {
3223 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003224 ReadWriteAccesses.push_back(Access);
3225 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003226 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003227 ReadOnlyAccesses.push_back(Access);
3228 }
3229 }
3230
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003231 // If there are no read-only pointers, and less than two read-write pointers,
3232 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003233 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003234 return true;
3235
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003236 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003237 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003238 return true;
3239
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003240 // For non-affine accesses, no alias check can be generated as we cannot
3241 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003242 for (MemoryAccess *MA : AliasGroup) {
3243 if (!MA->isAffine()) {
3244 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3245 return false;
3246 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003247 }
3248
3249 // Ensure that for all memory accesses for which we generate alias checks,
3250 // their base pointers are available.
3251 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003252 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3253 addRequiredInvariantLoad(
3254 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3255 }
3256
3257 MinMaxAliasGroups.emplace_back();
3258 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3259 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3260 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3261
3262 bool Valid;
3263
3264 Valid =
3265 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3266
3267 if (!Valid)
3268 return false;
3269
3270 // Bail out if the number of values we need to compare is too large.
3271 // This is important as the number of comparisons grows quadratically with
3272 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003273 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003274 RunTimeChecksMaxArraysPerGroup)
3275 return false;
3276
3277 Valid =
3278 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3279
3280 if (!Valid)
3281 return false;
3282
3283 return true;
3284}
3285
Tobias Grosserc80d6972016-09-02 06:33:33 +00003286/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003287static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003288 // Start with the smallest loop containing the entry and expand that
3289 // loop until it contains all blocks in the region. If there is a loop
3290 // containing all blocks in the region check if it is itself contained
3291 // and if so take the parent loop as it will be the smallest containing
3292 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003293 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003294 while (L) {
3295 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003296 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003297 AllContained &= L->contains(BB);
3298 if (AllContained)
3299 break;
3300 L = L->getParentLoop();
3301 }
3302
Johannes Doerfertef744432016-05-23 12:42:38 +00003303 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003304}
3305
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003306Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003307 ScopDetection::DetectionContext &DC)
Philip Pfaffe35bdcaf2017-05-15 13:43:01 +00003308 : SE(&ScalarEvolution), R(R), name(R.getNameStr()), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003309 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003310 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3311 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3312 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3313 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003314 if (IslOnErrorAbort)
3315 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003316 buildContext();
3317}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003318
Tobias Grosserbedef002016-12-02 08:10:56 +00003319void Scop::foldSizeConstantsToRight() {
3320 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3321
3322 for (auto Array : arrays()) {
3323 if (Array->getNumberOfDimensions() <= 1)
3324 continue;
3325
3326 isl_space *Space = Array->getSpace();
3327
3328 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3329
3330 if (!isl_union_set_contains(Accessed, Space)) {
3331 isl_space_free(Space);
3332 continue;
3333 }
3334
3335 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3336
3337 isl_map *Transform =
3338 isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3339
3340 std::vector<int> Int;
3341
3342 int Dims = isl_set_dim(Elements, isl_dim_set);
3343 for (int i = 0; i < Dims; i++) {
3344 isl_set *DimOnly =
3345 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3346 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3347 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3348
3349 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3350
3351 if (i == Dims - 1) {
3352 Int.push_back(1);
3353 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3354 isl_basic_set_free(DimHull);
3355 continue;
3356 }
3357
3358 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3359 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3360 isl_val *Val = isl_aff_get_denominator_val(Diff);
3361 isl_aff_free(Diff);
3362
3363 int ValInt = 1;
3364
3365 if (isl_val_is_int(Val))
3366 ValInt = isl_val_get_num_si(Val);
3367 isl_val_free(Val);
3368
3369 Int.push_back(ValInt);
3370
3371 isl_constraint *C = isl_constraint_alloc_equality(
3372 isl_local_space_from_space(isl_map_get_space(Transform)));
3373 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3374 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3375 Transform = isl_map_add_constraint(Transform, C);
3376 isl_basic_set_free(DimHull);
3377 continue;
3378 }
3379
3380 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3381 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3382
3383 int ValInt = 1;
3384 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3385 ValInt = 0;
3386 }
3387
3388 Int.push_back(ValInt);
3389 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3390 isl_basic_set_free(DimHull);
3391 isl_basic_set_free(ZeroSet);
3392 }
3393
3394 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3395
3396 if (!isl_set_is_subset(Elements, MappedElements)) {
3397 isl_set_free(Elements);
3398 isl_set_free(MappedElements);
3399 isl_map_free(Transform);
3400 continue;
3401 }
3402
3403 isl_set_free(MappedElements);
3404
3405 bool CanFold = true;
3406
3407 if (Int[0] <= 1)
3408 CanFold = false;
3409
3410 unsigned NumDims = Array->getNumberOfDimensions();
3411 for (unsigned i = 1; i < NumDims - 1; i++)
3412 if (Int[0] != Int[i] && Int[i])
3413 CanFold = false;
3414
3415 if (!CanFold) {
3416 isl_set_free(Elements);
3417 isl_map_free(Transform);
3418 continue;
3419 }
3420
Tobias Grosserbedef002016-12-02 08:10:56 +00003421 for (auto &Access : AccessFunctions)
3422 if (Access->getScopArrayInfo() == Array)
3423 Access->setAccessRelation(isl_map_apply_range(
3424 Access->getAccessRelation(), isl_map_copy(Transform)));
3425
3426 isl_map_free(Transform);
3427
3428 std::vector<const SCEV *> Sizes;
3429 for (unsigned i = 0; i < NumDims; i++) {
3430 auto Size = Array->getDimensionSize(i);
3431
3432 if (i == NumDims - 1)
3433 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3434 Sizes.push_back(Size);
3435 }
3436
3437 Array->updateSizes(Sizes, false /* CheckConsistency */);
3438
3439 isl_set_free(Elements);
3440 }
3441 isl_union_set_free(Accessed);
3442 return;
3443}
3444
Tobias Grosser491b7992016-12-02 05:21:22 +00003445void Scop::finalizeAccesses() {
3446 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003447 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003448 foldAccessRelations();
3449 assumeNoOutOfBounds();
3450}
3451
Tobias Grosser75805372011-04-29 06:27:02 +00003452Scop::~Scop() {
3453 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003454 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003455 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003456 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003457
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003458 for (auto &It : ParameterIds)
3459 isl_id_free(It.second);
3460
Johannes Doerfert96425c22015-08-30 21:13:53 +00003461 for (auto It : DomainMap)
3462 isl_set_free(It.second);
3463
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003464 for (auto &AS : RecordedAssumptions)
3465 isl_set_free(AS.Set);
3466
Johannes Doerfertb164c792014-09-18 11:17:17 +00003467 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003468 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003469 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003470 isl_pw_multi_aff_free(MMA.first);
3471 isl_pw_multi_aff_free(MMA.second);
3472 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003473 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003474 isl_pw_multi_aff_free(MMA.first);
3475 isl_pw_multi_aff_free(MMA.second);
3476 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003477 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003478
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003479 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003480 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003481
3482 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003483 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003484 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003485 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003486 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003487 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003488 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003489}
3490
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003491void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003492 // Check all array accesses for each base pointer and find a (virtual) element
3493 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003494 for (ScopStmt &Stmt : *this)
3495 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003496 if (!Access->isArrayKind())
3497 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003498 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003499 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3500
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003501 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003502 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003503 unsigned DivisibleSize = Array->getElemSizeInBytes();
3504 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003505 while (!isDivisible(Subscript, DivisibleSize, *SE))
3506 DivisibleSize /= 2;
3507 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003508 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003509 }
3510
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003511 for (auto &Stmt : *this)
3512 for (auto &Access : Stmt)
3513 Access->updateDimensionality();
3514}
3515
Tobias Grosser491b7992016-12-02 05:21:22 +00003516void Scop::foldAccessRelations() {
3517 for (auto &Stmt : *this)
3518 for (auto &Access : Stmt)
3519 Access->foldAccessRelation();
3520}
3521
3522void Scop::assumeNoOutOfBounds() {
3523 for (auto &Stmt : *this)
3524 for (auto &Access : Stmt)
3525 Access->assumeNoOutOfBound();
3526}
3527
Michael Kruse977d38b2016-07-22 17:31:17 +00003528void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003529 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3530 ScopStmt &Stmt = *StmtIt;
3531
Johannes Doerfert26404542016-05-10 12:19:47 +00003532 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003533 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003534 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003535
Johannes Doerferteca9e892015-11-03 16:54:49 +00003536 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003537 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003538 bool OnlyRead = true;
3539 for (MemoryAccess *MA : Stmt) {
3540 if (MA->isRead())
3541 continue;
3542
3543 OnlyRead = false;
3544 break;
3545 }
3546
3547 RemoveStmt = OnlyRead;
3548 }
3549
Johannes Doerfert26404542016-05-10 12:19:47 +00003550 if (!RemoveStmt) {
3551 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003552 continue;
3553 }
3554
Johannes Doerfert26404542016-05-10 12:19:47 +00003555 // Remove the statement because it is unnecessary.
3556 if (Stmt.isRegionStmt())
3557 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3558 StmtMap.erase(BB);
3559 else
3560 StmtMap.erase(Stmt.getBasicBlock());
3561
3562 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003563 }
3564}
3565
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003566InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003567 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3568 if (!LInst)
3569 return nullptr;
3570
3571 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3572 LInst = cast<LoadInst>(Rep);
3573
Johannes Doerfert96e54712016-02-07 17:30:13 +00003574 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003575 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003576 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003577 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003578 continue;
3579
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003580 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003581 for (auto *MA : MAs)
3582 if (MA->getAccessInstruction() == Val)
3583 return &IAClass;
3584 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003585
3586 return nullptr;
3587}
3588
Tobias Grosserc80d6972016-09-02 06:33:33 +00003589/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003590static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003591 bool MAInvalidCtxIsEmpty,
3592 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003593 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3594 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3595 // TODO: We can provide more information for better but more expensive
3596 // results.
3597 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3598 LInst->getAlignment(), DL))
3599 return false;
3600
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003601 // If the location might be overwritten we do not hoist it unconditionally.
3602 //
3603 // TODO: This is probably to conservative.
3604 if (!NonHoistableCtxIsEmpty)
3605 return false;
3606
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003607 // If a dereferencable load is in a statement that is modeled precisely we can
3608 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003609 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003610 return true;
3611
3612 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003613 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003614 // statement domain.
3615 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3616 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3617 return false;
3618 return true;
3619}
3620
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003621void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003622
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003623 if (InvMAs.empty())
3624 return;
3625
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003626 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003627 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003628
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003629 // Get the context under which the statement is executed but remove the error
3630 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003631 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003632 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003633
Tobias Grosser90411a92017-02-16 19:11:33 +00003634 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003635 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003636 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3637 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003638 for (auto &InvMA : InvMAs)
3639 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003640 return;
3641 }
3642
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003643 // Project out all parameters that relate to loads in the statement. Otherwise
3644 // we could have cyclic dependences on the constraints under which the
3645 // hoisted loads are executed and we could not determine an order in which to
3646 // pre-load them. This happens because not only lower bounds are part of the
3647 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003648 for (auto &InvMA : InvMAs) {
3649 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003650 Instruction *AccInst = MA->getAccessInstruction();
3651 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003652 SetVector<Value *> Values;
3653 for (const SCEV *Parameter : Parameters) {
3654 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003655 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003656 if (!Values.count(AccInst))
3657 continue;
3658
3659 if (isl_id *ParamId = getIdForParam(Parameter)) {
3660 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003661 if (Dim >= 0)
3662 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003663 isl_id_free(ParamId);
3664 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003665 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003666 }
3667 }
3668
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003669 for (auto &InvMA : InvMAs) {
3670 auto *MA = InvMA.MA;
3671 auto *NHCtx = InvMA.NonHoistableCtx;
3672
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003673 // Check for another invariant access that accesses the same location as
3674 // MA and if found consolidate them. Otherwise create a new equivalence
3675 // class at the end of InvariantEquivClasses.
3676 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003677 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003678 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3679
Johannes Doerfert85676e32016-04-23 14:32:34 +00003680 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003681 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003682 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3683
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003684 isl_set *MACtx;
3685 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003686 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3687 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003688 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003689 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003690 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003691 } else {
3692 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003693 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003694 MACtx = isl_set_gist_params(MACtx, getContext());
3695 }
3696
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003697 bool Consolidated = false;
3698 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003699 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003700 continue;
3701
Johannes Doerfertdf880232016-03-03 12:26:58 +00003702 // If the pointer and the type is equal check if the access function wrt.
3703 // to the domain is equal too. It can happen that the domain fixes
3704 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003705 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003706 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003707 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003708 if (!MAs.empty()) {
3709 auto *LastMA = MAs.front();
3710
3711 auto *AR = isl_map_range(MA->getAccessRelation());
3712 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3713 bool SameAR = isl_set_is_equal(AR, LastAR);
3714 isl_set_free(AR);
3715 isl_set_free(LastAR);
3716
3717 if (!SameAR)
3718 continue;
3719 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003720
3721 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003722 MAs.push_front(MA);
3723
Johannes Doerfertdf880232016-03-03 12:26:58 +00003724 Consolidated = true;
3725
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003726 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003727 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003728 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003729 IAClassDomainCtx =
3730 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003731 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003732 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003733 break;
3734 }
3735
3736 if (Consolidated)
3737 continue;
3738
3739 // If we did not consolidate MA, thus did not find an equivalence class
3740 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003741 InvariantEquivClasses.emplace_back(
3742 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003743 }
3744
3745 isl_set_free(DomainCtx);
3746}
3747
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003748__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3749 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003750 // TODO: Loads that are not loop carried, hence are in a statement with
3751 // zero iterators, are by construction invariant, though we
3752 // currently "hoist" them anyway. This is necessary because we allow
3753 // them to be treated as parameters (e.g., in conditions) and our code
3754 // generation would otherwise use the old value.
3755
3756 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003757 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003758
Johannes Doerfertc9765462016-11-17 22:11:56 +00003759 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3760 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003761 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003762
3763 // Skip accesses that have an invariant base pointer which is defined but
3764 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3765 // returns a pointer that is used as a base address. However, as we want
3766 // to hoist indirect pointers, we allow the base pointer to be defined in
3767 // the region if it is also a memory access. Each ScopArrayInfo object
3768 // that has a base pointer origin has a base pointer that is loaded and
3769 // that it is invariant, thus it will be hoisted too. However, if there is
3770 // no base pointer origin we check that the base pointer is defined
3771 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003772 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003773 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003774 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003775
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003776 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003777 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003778
3779 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3780 Stmt.getNumIterators())) {
3781 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003782 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003783 }
3784
3785 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003786 isl_set *SafeToLoad;
3787
3788 auto &DL = getFunction().getParent()->getDataLayout();
3789 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
3790 DL)) {
3791 SafeToLoad =
3792 isl_set_universe(isl_space_range(isl_map_get_space(AccessRelation)));
3793 isl_map_free(AccessRelation);
3794 } else if (BB != LI->getParent()) {
3795 // Skip accesses in non-affine subregions as they might not be executed
3796 // under the same condition as the entry of the non-affine subregion.
3797 isl_map_free(AccessRelation);
3798 return nullptr;
3799 } else {
3800 SafeToLoad = isl_map_range(AccessRelation);
3801 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003802
3803 isl_union_map *Written = isl_union_map_intersect_range(
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003804 isl_union_map_copy(Writes), isl_union_set_from_set(SafeToLoad));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003805 auto *WrittenCtx = isl_union_map_params(Written);
3806 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003807
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003808 if (!IsWritten)
3809 return WrittenCtx;
3810
3811 WrittenCtx = isl_set_remove_divs(WrittenCtx);
Tobias Grosser90411a92017-02-16 19:11:33 +00003812 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctsInDomain;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003813 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3814 isl_set_free(WrittenCtx);
3815 return nullptr;
3816 }
3817
3818 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3819 AS_RESTRICTION);
3820 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003821}
3822
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003823void Scop::verifyInvariantLoads() {
3824 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003825 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003826 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003827 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003828 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003829 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3830 return;
3831 }
3832 }
3833}
3834
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003835void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003836 if (!PollyInvariantLoadHoisting)
3837 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003838
Tobias Grosser0865e7752016-02-29 07:29:42 +00003839 isl_union_map *Writes = getWrites();
3840 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003841 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003842
Tobias Grosser0865e7752016-02-29 07:29:42 +00003843 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003844 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3845 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003846
3847 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003848 for (auto InvMA : InvariantAccesses)
3849 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003850 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003851 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003852 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003853}
3854
Tobias Grosserf3adab42017-05-10 10:59:58 +00003855/// Find the canonical scop array info object for a set of invariant load
3856/// hoisted loads. The canonical array is the one that corresponds to the
3857/// first load in the list of accesses which is used as base pointer of a
3858/// scop array.
3859static const ScopArrayInfo *findCanonicalArray(Scop *S,
3860 MemoryAccessList &Accesses) {
3861 for (MemoryAccess *Access : Accesses) {
3862 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
3863 Access->getAccessInstruction(), MemoryKind::Array);
3864 if (CanonicalArray)
3865 return CanonicalArray;
3866 }
3867 return nullptr;
3868}
3869
3870/// Check if @p Array severs as base array in an invariant load.
3871static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
3872 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
3873 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
3874 if (Access2->getScopArrayInfo() == Array)
3875 return true;
3876 return false;
3877}
3878
3879/// Replace the base pointer arrays in all memory accesses referencing @p Old,
3880/// with a reference to @p New.
3881static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
3882 const ScopArrayInfo *New) {
3883 for (ScopStmt &Stmt : *S)
3884 for (MemoryAccess *Access : Stmt) {
3885 if (Access->getLatestScopArrayInfo() != Old)
3886 continue;
3887
3888 isl_id *Id = New->getBasePtrId();
3889 isl_map *Map = Access->getAccessRelation();
3890 Map = isl_map_set_tuple_id(Map, isl_dim_out, Id);
3891 Access->setAccessRelation(Map);
3892 }
3893}
3894
3895void Scop::canonicalizeDynamicBasePtrs() {
3896 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
3897 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
3898
3899 const ScopArrayInfo *CanonicalBasePtrSAI =
3900 findCanonicalArray(this, BasePtrAccesses);
3901
3902 if (!CanonicalBasePtrSAI)
3903 continue;
3904
3905 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
3906 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
3907 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
3908 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
3909 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
3910 continue;
3911
3912 // we currently do not canonicalize arrays where some accesses are
3913 // hoisted as invariant loads. If we would, we need to update the access
3914 // function of the invariant loads as well. However, as this is not a
3915 // very common situation, we leave this for now to avoid further
3916 // complexity increases.
3917 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
3918 continue;
3919
3920 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
3921 }
3922 }
3923}
3924
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003925const ScopArrayInfo *
3926Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
3927 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
3928 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00003929 assert((BasePtr || BaseName) &&
3930 "BasePtr and BaseName can not be nullptr at the same time.");
3931 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3932 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3933 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003934 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003935 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003936 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003937 DL, this, BaseName));
3938 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003939 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003940 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003941 // In case of mismatching array sizes, we bail out by setting the run-time
3942 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003943 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003944 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003945 }
Tobias Grosserab671442015-05-23 05:58:27 +00003946 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003947}
3948
Roman Gareevd7754a12016-07-30 09:25:51 +00003949const ScopArrayInfo *
3950Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3951 const std::vector<unsigned> &Sizes) {
3952 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3953 std::vector<const SCEV *> SCEVSizes;
3954
3955 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003956 if (size)
3957 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3958 else
3959 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003960
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003961 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3962 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00003963 return SAI;
3964}
3965
Tobias Grosserf3adab42017-05-10 10:59:58 +00003966const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
3967 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003968 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00003969 return SAI;
3970}
3971
3972const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
3973 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003974 assert(SAI && "No ScopArrayInfo available for this base pointer");
3975 return SAI;
3976}
3977
Tobias Grosser74394f02013-01-14 22:40:23 +00003978std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003979
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003980std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003981 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003982 return stringFromIslObj(AssumedContext);
3983}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003984
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003985std::string Scop::getInvalidContextStr() const {
3986 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003987}
Tobias Grosser75805372011-04-29 06:27:02 +00003988
3989std::string Scop::getNameStr() const {
3990 std::string ExitName, EntryName;
3991 raw_string_ostream ExitStr(ExitName);
3992 raw_string_ostream EntryStr(EntryName);
3993
Tobias Grosserf240b482014-01-09 10:42:15 +00003994 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003995 EntryStr.str();
3996
3997 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003998 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003999 ExitStr.str();
4000 } else
4001 ExitName = "FunctionExit";
4002
4003 return EntryName + "---" + ExitName;
4004}
4005
Tobias Grosser74394f02013-01-14 22:40:23 +00004006__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00004007__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00004008 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00004009}
4010
Tobias Grossere86109f2013-10-29 21:05:49 +00004011__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004012 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00004013 return isl_set_copy(AssumedContext);
4014}
4015
Michael Krusef3091bf2017-03-17 13:09:52 +00004016bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004017 if (PollyProcessUnprofitable)
4018 return true;
4019
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004020 if (isEmpty())
4021 return false;
4022
4023 unsigned OptimizableStmtsOrLoops = 0;
4024 for (auto &Stmt : *this) {
4025 if (Stmt.getNumIterators() == 0)
4026 continue;
4027
4028 bool ContainsArrayAccs = false;
4029 bool ContainsScalarAccs = false;
4030 for (auto *MA : Stmt) {
4031 if (MA->isRead())
4032 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004033 ContainsArrayAccs |= MA->isLatestArrayKind();
4034 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004035 }
4036
Michael Krusef3091bf2017-03-17 13:09:52 +00004037 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004038 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4039 }
4040
4041 return OptimizableStmtsOrLoops > 1;
4042}
4043
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004044bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004045 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004046 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00004047 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4048 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4049 isl_set_is_subset(PositiveContext, NegativeContext));
4050 isl_set_free(PositiveContext);
4051 if (!IsFeasible) {
4052 isl_set_free(NegativeContext);
4053 return false;
4054 }
4055
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004056 auto *DomainContext = isl_union_set_params(getDomains());
4057 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00004058 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004059 isl_set_free(NegativeContext);
4060 isl_set_free(DomainContext);
4061
Johannes Doerfert43788c52015-08-20 05:58:56 +00004062 return IsFeasible;
4063}
4064
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004065static std::string toString(AssumptionKind Kind) {
4066 switch (Kind) {
4067 case ALIASING:
4068 return "No-aliasing";
4069 case INBOUNDS:
4070 return "Inbounds";
4071 case WRAPPING:
4072 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004073 case UNSIGNED:
4074 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004075 case COMPLEXITY:
4076 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004077 case PROFITABLE:
4078 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004079 case ERRORBLOCK:
4080 return "No-error";
4081 case INFINITELOOP:
4082 return "Finite loop";
4083 case INVARIANTLOAD:
4084 return "Invariant load";
4085 case DELINEARIZATION:
4086 return "Delinearization";
4087 }
4088 llvm_unreachable("Unknown AssumptionKind!");
4089}
4090
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004091bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4092 if (Sign == AS_ASSUMPTION) {
4093 if (isl_set_is_subset(Context, Set))
4094 return false;
4095
4096 if (isl_set_is_subset(AssumedContext, Set))
4097 return false;
4098 } else {
4099 if (isl_set_is_disjoint(Set, Context))
4100 return false;
4101
4102 if (isl_set_is_subset(Set, InvalidContext))
4103 return false;
4104 }
4105 return true;
4106}
4107
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004108bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
4109 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004110 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4111 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004112
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004113 // Do never emit trivial assumptions as they only clutter the output.
4114 if (!PollyRemarksMinimal) {
4115 isl_set *Univ = nullptr;
4116 if (Sign == AS_ASSUMPTION)
4117 Univ = isl_set_universe(isl_set_get_space(Set));
4118
4119 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4120 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4121 isl_set_free(Univ);
4122
4123 if (IsTrivial)
4124 return false;
4125 }
4126
Johannes Doerfertcd195322016-11-17 21:41:08 +00004127 switch (Kind) {
4128 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004129 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004130 break;
4131 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004132 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004133 break;
4134 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004135 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004136 break;
4137 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004138 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004139 break;
4140 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004141 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004142 break;
4143 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004144 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004145 break;
4146 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004147 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004148 break;
4149 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004150 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004151 break;
4152 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004153 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004154 break;
4155 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004156 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004157 break;
4158 }
4159
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004160 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004161 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4162 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004163 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004164 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004165}
4166
4167void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004168 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004169 // Simplify the assumptions/restrictions first.
4170 Set = isl_set_gist_params(Set, getContext());
4171
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004172 if (!trackAssumption(Kind, Set, Loc, Sign)) {
4173 isl_set_free(Set);
4174 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004175 }
4176
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004177 if (Sign == AS_ASSUMPTION) {
4178 AssumedContext = isl_set_intersect(AssumedContext, Set);
4179 AssumedContext = isl_set_coalesce(AssumedContext);
4180 } else {
4181 InvalidContext = isl_set_union(InvalidContext, Set);
4182 InvalidContext = isl_set_coalesce(InvalidContext);
4183 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004184}
4185
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004186void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004187 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004188 assert((isl_set_is_params(Set) || BB) &&
4189 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004190 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004191}
4192
4193void Scop::addRecordedAssumptions() {
4194 while (!RecordedAssumptions.empty()) {
4195 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004196
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004197 if (!AS.BB) {
4198 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
4199 continue;
4200 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004201
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004202 // If the domain was deleted the assumptions are void.
4203 isl_set *Dom = getDomainConditions(AS.BB);
4204 if (!Dom) {
4205 isl_set_free(AS.Set);
4206 continue;
4207 }
4208
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004209 // If a basic block was given use its domain to simplify the assumption.
4210 // In case of restrictions we know they only have to hold on the domain,
4211 // thus we can intersect them with the domain of the block. However, for
4212 // assumptions the domain has to imply them, thus:
4213 // _ _____
4214 // Dom => S <==> A v B <==> A - B
4215 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004216 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004217 // assumption.
4218 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004219 if (AS.Sign == AS_RESTRICTION)
4220 S = isl_set_params(isl_set_intersect(S, Dom));
4221 else /* (AS.Sign == AS_ASSUMPTION) */
4222 S = isl_set_params(isl_set_subtract(Dom, S));
4223
4224 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004225 }
4226}
4227
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004228void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004229 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004230}
4231
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004232__isl_give isl_set *Scop::getInvalidContext() const {
4233 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004234}
4235
Tobias Grosser75805372011-04-29 06:27:02 +00004236void Scop::printContext(raw_ostream &OS) const {
4237 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004238 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004239
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004240 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004241 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004242
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004243 OS.indent(4) << "Invalid Context:\n";
4244 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004245
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004246 unsigned Dim = 0;
4247 for (const SCEV *Parameter : Parameters)
4248 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004249}
4250
Johannes Doerfertb164c792014-09-18 11:17:17 +00004251void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004252 int noOfGroups = 0;
4253 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004254 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004255 noOfGroups += 1;
4256 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004257 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004258 }
4259
Tobias Grosserbb853c22015-07-25 12:31:03 +00004260 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004261 if (MinMaxAliasGroups.empty()) {
4262 OS.indent(8) << "n/a\n";
4263 return;
4264 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004265
Tobias Grosserbb853c22015-07-25 12:31:03 +00004266 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004267
4268 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004269 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004270 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004271 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004272 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4273 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004274 }
4275 OS << " ]]\n";
4276 }
4277
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004278 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004279 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004280 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004281 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004282 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4283 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004284 }
4285 OS << " ]]\n";
4286 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004287 }
4288}
4289
Tobias Grosser75805372011-04-29 06:27:02 +00004290void Scop::printStatements(raw_ostream &OS) const {
4291 OS << "Statements {\n";
4292
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004293 for (const ScopStmt &Stmt : *this)
4294 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00004295
4296 OS.indent(4) << "}\n";
4297}
4298
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004299void Scop::printArrayInfo(raw_ostream &OS) const {
4300 OS << "Arrays {\n";
4301
Tobias Grosserab671442015-05-23 05:58:27 +00004302 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004303 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004304
4305 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004306
4307 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4308
4309 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004310 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004311
4312 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004313}
4314
Tobias Grosser75805372011-04-29 06:27:02 +00004315void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004316 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004317 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004318 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004319 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004320 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004321 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004322 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004323 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004324 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004325 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004326 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4327 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004328 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004329 }
4330 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004331 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004332 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004333 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00004334 printStatements(OS.indent(4));
4335}
4336
4337void Scop::dump() const { print(dbgs()); }
4338
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004339isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004340
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004341__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4342 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004343 // First try to use the SCEVAffinator to generate a piecewise defined
4344 // affine function from @p E in the context of @p BB. If that tasks becomes to
4345 // complex the affinator might return a nullptr. In such a case we invalidate
4346 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004347 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004348 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004349 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004350 // TODO: We could use a heuristic and either use:
4351 // SCEVAffinator::takeNonNegativeAssumption
4352 // or
4353 // SCEVAffinator::interpretAsUnsigned
4354 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004355 if (NonNegative)
4356 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004357 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004358 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004359
4360 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
4361 invalidate(COMPLEXITY, DL);
4362 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004363}
4364
Tobias Grosser808cd692015-07-14 09:33:13 +00004365__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004366 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4367 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004368
Tobias Grosser808cd692015-07-14 09:33:13 +00004369 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004370 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004371
4372 return Domain;
4373}
4374
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004375__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4376 PWACtx PWAC = getPwAff(E, BB);
4377 isl_set_free(PWAC.second);
4378 return PWAC.first;
4379}
4380
Tobias Grossere5a35142015-11-12 14:07:09 +00004381__isl_give isl_union_map *
4382Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4383 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004384
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004385 for (ScopStmt &Stmt : *this) {
4386 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004387 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004388 continue;
4389
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004390 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004391 isl_map *AccessDomain = MA->getAccessRelation();
4392 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004393 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004394 }
4395 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004396 return isl_union_map_coalesce(Accesses);
4397}
4398
4399__isl_give isl_union_map *Scop::getMustWrites() {
4400 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004401}
4402
4403__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004404 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004405}
4406
Tobias Grosser37eb4222014-02-20 21:43:54 +00004407__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004408 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004409}
4410
4411__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004412 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004413}
4414
Tobias Grosser2ac23382015-11-12 14:07:13 +00004415__isl_give isl_union_map *Scop::getAccesses() {
4416 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4417}
4418
Roman Gareevb3224ad2016-09-14 06:26:09 +00004419// Check whether @p Node is an extension node.
4420//
4421// @return true if @p Node is an extension node.
4422isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4423 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4424 return isl_bool_error;
4425 else
4426 return isl_bool_true;
4427}
4428
4429bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4430 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4431 nullptr) == isl_stat_error;
4432}
4433
Tobias Grosser808cd692015-07-14 09:33:13 +00004434__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004435 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004436 if (containsExtensionNode(Tree)) {
4437 isl_schedule_free(Tree);
4438 return nullptr;
4439 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004440 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004441 isl_schedule_free(Tree);
4442 return S;
4443}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004444
Tobias Grosser808cd692015-07-14 09:33:13 +00004445__isl_give isl_schedule *Scop::getScheduleTree() const {
4446 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4447 getDomains());
4448}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004449
Tobias Grosser808cd692015-07-14 09:33:13 +00004450void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4451 auto *S = isl_schedule_from_domain(getDomains());
4452 S = isl_schedule_insert_partial_schedule(
4453 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4454 isl_schedule_free(Schedule);
4455 Schedule = S;
4456}
4457
4458void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4459 isl_schedule_free(Schedule);
4460 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004461}
4462
4463bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4464 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004465 for (ScopStmt &Stmt : *this) {
4466 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004467 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4468 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4469
4470 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4471 isl_union_set_free(StmtDomain);
4472 isl_union_set_free(NewStmtDomain);
4473 continue;
4474 }
4475
4476 Changed = true;
4477
4478 isl_union_set_free(StmtDomain);
4479 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4480
4481 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004482 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004483 isl_union_set_free(NewStmtDomain);
4484 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004485 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004486 }
4487 isl_union_set_free(Domain);
4488 return Changed;
4489}
4490
Tobias Grosser75805372011-04-29 06:27:02 +00004491ScalarEvolution *Scop::getSE() const { return SE; }
4492
Tobias Grosser808cd692015-07-14 09:33:13 +00004493struct MapToDimensionDataTy {
4494 int N;
4495 isl_union_pw_multi_aff *Res;
4496};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004497
Tobias Grosserc80d6972016-09-02 06:33:33 +00004498// Create a function that maps the elements of 'Set' to its N-th dimension and
4499// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004500//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004501// @param Set The input set.
4502// @param User->N The dimension to map to.
4503// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004504//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004505// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004506static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4507 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4508 int Dim;
4509 isl_space *Space;
4510 isl_pw_multi_aff *PMA;
4511
4512 Dim = isl_set_dim(Set, isl_dim_set);
4513 Space = isl_set_get_space(Set);
4514 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4515 Dim - Data->N);
4516 if (Data->N > 1)
4517 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4518 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4519
4520 isl_set_free(Set);
4521
4522 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004523}
4524
Tobias Grosserc80d6972016-09-02 06:33:33 +00004525// Create an isl_multi_union_aff that defines an identity mapping from the
4526// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004527//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004528// # Example:
4529//
4530// Domain: { A[i,j]; B[i,j,k] }
4531// N: 1
4532//
4533// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4534//
4535// @param USet A union set describing the elements for which to generate a
4536// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004537// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004538// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004539static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004540mapToDimension(__isl_take isl_union_set *USet, int N) {
4541 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004542 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004543 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004544
Tobias Grosser808cd692015-07-14 09:33:13 +00004545 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004546
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004547 auto *Space = isl_union_set_get_space(USet);
4548 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004549
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004550 Data = {N, PwAff};
4551
4552 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004553 (void)Res;
4554
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004555 assert(Res == isl_stat_ok);
4556
4557 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004558 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4559}
4560
Michael Kruse55454072017-03-15 22:16:43 +00004561void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004562 assert(BB && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004563 Stmts.emplace_back(*this, *BB, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004564 auto *Stmt = &Stmts.back();
4565 StmtMap[BB] = Stmt;
4566}
4567
Michael Kruse55454072017-03-15 22:16:43 +00004568void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004569 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004570 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004571 auto *Stmt = &Stmts.back();
4572 for (BasicBlock *BB : R->blocks())
Tobias Grosser808cd692015-07-14 09:33:13 +00004573 StmtMap[BB] = Stmt;
Tobias Grosser808cd692015-07-14 09:33:13 +00004574}
4575
Roman Gareevb3224ad2016-09-14 06:26:09 +00004576ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4577 __isl_take isl_map *TargetRel,
4578 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004579#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004580 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4581 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4582 assert(isl_set_is_subset(Domain, TargetDomain) &&
4583 "Target access not defined for complete statement domain");
4584 assert(isl_set_is_subset(Domain, SourceDomain) &&
4585 "Source access not defined for complete statement domain");
4586 isl_set_free(SourceDomain);
4587 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004588#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004589 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4590 CopyStmtsNum++;
4591 return &(Stmts.back());
4592}
4593
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004594void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004595 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004596 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004597 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004598 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4599 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004600}
4601
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004602/// To generate a schedule for the elements in a Region we traverse the Region
4603/// in reverse-post-order and add the contained RegionNodes in traversal order
4604/// to the schedule of the loop that is currently at the top of the LoopStack.
4605/// For loop-free codes, this results in a correct sequential ordering.
4606///
4607/// Example:
4608/// bb1(0)
4609/// / \.
4610/// bb2(1) bb3(2)
4611/// \ / \.
4612/// bb4(3) bb5(4)
4613/// \ /
4614/// bb6(5)
4615///
4616/// Including loops requires additional processing. Whenever a loop header is
4617/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4618/// from an empty schedule, we first process all RegionNodes that are within
4619/// this loop and complete the sequential schedule at this loop-level before
4620/// processing about any other nodes. To implement this
4621/// loop-nodes-first-processing, the reverse post-order traversal is
4622/// insufficient. Hence, we additionally check if the traversal yields
4623/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4624/// These region-nodes are then queue and only traverse after the all nodes
4625/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004626void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004627 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004628
4629 ReversePostOrderTraversal<Region *> RTraversal(R);
4630 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4631 std::deque<RegionNode *> DelayList;
4632 bool LastRNWaiting = false;
4633
4634 // Iterate over the region @p R in reverse post-order but queue
4635 // sub-regions/blocks iff they are not part of the last encountered but not
4636 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4637 // that we queued the last sub-region/block from the reverse post-order
4638 // iterator. If it is set we have to explore the next sub-region/block from
4639 // the iterator (if any) to guarantee progress. If it is not set we first try
4640 // the next queued sub-region/blocks.
4641 while (!WorkList.empty() || !DelayList.empty()) {
4642 RegionNode *RN;
4643
4644 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4645 RN = WorkList.front();
4646 WorkList.pop_front();
4647 LastRNWaiting = false;
4648 } else {
4649 RN = DelayList.front();
4650 DelayList.pop_front();
4651 }
4652
4653 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004654 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004655 L = OuterScopLoop;
4656
Tobias Grosser151ae322016-04-03 19:36:52 +00004657 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004658 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004659 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004660 LastRNWaiting = true;
4661 DelayList.push_back(RN);
4662 continue;
4663 }
4664 LoopStack.push_back({L, nullptr, 0});
4665 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004666 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004667 }
4668
4669 return;
4670}
4671
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004672void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004673
Tobias Grosser8362c262016-01-06 15:30:06 +00004674 if (RN->isSubRegion()) {
4675 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004676 if (!isNonAffineSubRegion(LocalRegion)) {
4677 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004678 return;
4679 }
4680 }
Michael Kruse046dde42015-08-10 13:01:57 +00004681
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004682 auto &LoopData = LoopStack.back();
4683 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004684
Michael Kruse6f7721f2016-02-24 22:08:19 +00004685 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004686 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4687 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004688 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004689 }
4690
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004691 // Check if we just processed the last node in this loop. If we did, finalize
4692 // the loop by:
4693 //
4694 // - adding new schedule dimensions
4695 // - folding the resulting schedule into the parent loop schedule
4696 // - dropping the loop schedule from the LoopStack.
4697 //
4698 // Then continue to check surrounding loops, which might also have been
4699 // completed by this node.
4700 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00004701 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004702 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004703 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004704
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004705 LoopStack.pop_back();
4706 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004707
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004708 if (Schedule) {
4709 auto *Domain = isl_schedule_get_domain(Schedule);
4710 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4711 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4712 NextLoopData.Schedule =
4713 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004714 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004715
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004716 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4717 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004718 }
Tobias Grosser75805372011-04-29 06:27:02 +00004719}
4720
Michael Kruse6f7721f2016-02-24 22:08:19 +00004721ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004722 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004723 if (StmtMapIt == StmtMap.end())
4724 return nullptr;
4725 return StmtMapIt->second;
4726}
4727
Michael Kruse6f7721f2016-02-24 22:08:19 +00004728ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4729 if (RN->isSubRegion())
4730 return getStmtFor(RN->getNodeAs<Region>());
4731 return getStmtFor(RN->getNodeAs<BasicBlock>());
4732}
4733
4734ScopStmt *Scop::getStmtFor(Region *R) const {
4735 ScopStmt *Stmt = getStmtFor(R->getEntry());
4736 assert(!Stmt || Stmt->getRegion() == R);
4737 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004738}
4739
Johannes Doerfert96425c22015-08-30 21:13:53 +00004740int Scop::getRelativeLoopDepth(const Loop *L) const {
4741 Loop *OuterLoop =
4742 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4743 if (!OuterLoop)
4744 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004745 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4746}
4747
Roman Gareevd7754a12016-07-30 09:25:51 +00004748ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4749 for (auto &SAI : arrays()) {
4750 if (SAI->getName() == BaseName)
4751 return SAI;
4752 }
4753 return nullptr;
4754}
4755
Johannes Doerfert99191c72016-05-31 09:41:04 +00004756//===----------------------------------------------------------------------===//
4757void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4758 AU.addRequired<LoopInfoWrapperPass>();
4759 AU.addRequired<RegionInfoPass>();
4760 AU.addRequired<DominatorTreeWrapperPass>();
4761 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004762 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004763 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004764 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004765 AU.setPreservesAll();
4766}
4767
Tobias Grossercd01a362017-02-17 08:12:36 +00004768void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
4769 NumLoopsInScop += Stats.NumLoops;
4770 MaxNumLoopsInScop =
4771 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
4772
Tobias Grossercd01a362017-02-17 08:12:36 +00004773 if (Stats.MaxDepth == 1)
4774 NumScopsDepthOne++;
4775 else if (Stats.MaxDepth == 2)
4776 NumScopsDepthTwo++;
4777 else if (Stats.MaxDepth == 3)
4778 NumScopsDepthThree++;
4779 else if (Stats.MaxDepth == 4)
4780 NumScopsDepthFour++;
4781 else if (Stats.MaxDepth == 5)
4782 NumScopsDepthFive++;
4783 else
4784 NumScopsDepthLarger++;
4785}
4786
Johannes Doerfert99191c72016-05-31 09:41:04 +00004787bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004788 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004789
4790 if (!SD.isMaxRegionInScop(*R))
4791 return false;
4792
4793 Function *F = R->getEntry()->getParent();
4794 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4795 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4796 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4797 auto const &DL = F->getParent()->getDataLayout();
4798 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004799 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004800
Michael Kruse89b1f942017-03-17 13:56:53 +00004801 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004802 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00004803
4804 if (S) {
4805 ScopDetection::LoopStats Stats =
4806 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
4807 updateLoopCountStatistic(Stats);
4808 }
4809
Tobias Grosser75805372011-04-29 06:27:02 +00004810 return false;
4811}
4812
Johannes Doerfert99191c72016-05-31 09:41:04 +00004813void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004814 if (S)
4815 S->print(OS);
4816 else
4817 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004818}
Tobias Grosser75805372011-04-29 06:27:02 +00004819
Johannes Doerfert99191c72016-05-31 09:41:04 +00004820char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004821
Johannes Doerfert99191c72016-05-31 09:41:04 +00004822Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4823
4824INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004825 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004826 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004827INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00004828INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004829INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004830INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004831INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004832INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004833INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004834INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004835 "Polly - Create polyhedral description of Scops", false,
4836 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004837
4838//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00004839ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
4840 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
4841 AssumptionCache &AC) {
4842 /// Create polyhedral descripton of scops for all the valid regions of a
4843 /// function.
4844 for (auto &It : SD) {
4845 Region *R = const_cast<Region *>(It);
4846 if (!SD.isMaxRegionInScop(*R))
4847 continue;
4848
4849 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4850 std::unique_ptr<Scop> S = SB.getScop();
4851 if (!S)
4852 continue;
4853 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
4854 assert(Inserted && "Building Scop for the same region twice!");
4855 (void)Inserted;
4856 }
4857}
4858
4859AnalysisKey ScopInfoAnalysis::Key;
4860
4861ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
4862 FunctionAnalysisManager &FAM) {
4863 auto &SD = FAM.getResult<ScopAnalysis>(F);
4864 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
4865 auto &LI = FAM.getResult<LoopAnalysis>(F);
4866 auto &AA = FAM.getResult<AAManager>(F);
4867 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
4868 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
4869 auto &DL = F.getParent()->getDataLayout();
4870 return {DL, SD, SE, LI, AA, DT, AC};
4871}
4872
4873PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
4874 FunctionAnalysisManager &FAM) {
4875 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
4876 for (auto &It : SI) {
4877 if (It.second)
4878 It.second->print(Stream);
4879 else
4880 Stream << "Invalid Scop!\n";
4881 }
4882 return PreservedAnalyses::all();
4883}
4884
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004885void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4886 AU.addRequired<LoopInfoWrapperPass>();
4887 AU.addRequired<RegionInfoPass>();
4888 AU.addRequired<DominatorTreeWrapperPass>();
4889 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004890 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004891 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004892 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004893 AU.setPreservesAll();
4894}
4895
4896bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004897 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004898 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4899 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4900 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4901 auto const &DL = F.getParent()->getDataLayout();
4902 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004903 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004904
Philip Pfaffe838e0882017-05-15 12:55:14 +00004905 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004906 return false;
4907}
4908
4909void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00004910 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004911 if (It.second)
4912 It.second->print(OS);
4913 else
4914 OS << "Invalid Scop!\n";
4915 }
4916}
4917
4918char ScopInfoWrapperPass::ID = 0;
4919
4920Pass *polly::createScopInfoWrapperPassPass() {
4921 return new ScopInfoWrapperPass();
4922}
4923
4924INITIALIZE_PASS_BEGIN(
4925 ScopInfoWrapperPass, "polly-function-scops",
4926 "Polly - Create polyhedral description of all Scops of a function", false,
4927 false);
4928INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00004929INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004930INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4931INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4932INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004933INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004934INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4935INITIALIZE_PASS_END(
4936 ScopInfoWrapperPass, "polly-function-scops",
4937 "Polly - Create polyhedral description of all Scops of a function", false,
4938 false)