blob: eff8cfdb321d0e61a45e275d873e8833236bdf0c [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
Johannes Doerfert2f705842016-04-12 16:09:44 +000097static cl::opt<bool> PollyRemarksMinimal(
98 "polly-remarks-minimal",
99 cl::desc("Do not emit remarks about assumptions that are known"),
100 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
101
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +0000102// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000103// operations can overflow easily. Additive reductions and bit operations
104// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +0000105static cl::opt<bool> DisableMultiplicativeReductions(
106 "polly-disable-multiplicative-reductions",
107 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
108 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000109
Johannes Doerfert9143d672014-09-27 11:02:39 +0000110static cl::opt<unsigned> RunTimeChecksMaxParameters(
111 "polly-rtc-max-parameters",
112 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
113 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
114
Tobias Grosser71500722015-03-28 15:11:14 +0000115static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
116 "polly-rtc-max-arrays-per-group",
117 cl::desc("The maximal number of arrays to compare in each alias group."),
118 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000119
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000120static cl::opt<std::string> UserContextStr(
121 "polly-context", cl::value_desc("isl parameter set"),
122 cl::desc("Provide additional constraints on the context parameters"),
123 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000124
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000125static cl::opt<bool> DetectReductions("polly-detect-reductions",
126 cl::desc("Detect and exploit reductions"),
127 cl::Hidden, cl::ZeroOrMore,
128 cl::init(true), cl::cat(PollyCategory));
129
Tobias Grosser2937b592016-04-29 11:43:20 +0000130static cl::opt<bool>
131 IslOnErrorAbort("polly-on-isl-error-abort",
132 cl::desc("Abort if an isl error is encountered"),
133 cl::init(true), cl::cat(PollyCategory));
134
Tobias Grosserd7c49752017-02-28 09:45:54 +0000135static cl::opt<bool> PollyPreciseInbounds(
136 "polly-precise-inbounds",
137 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
138 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
139
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000140static cl::opt<bool>
141 PollyIgnoreInbounds("polly-ignore-inbounds",
142 cl::desc("Do not take inbounds assumptions at all"),
143 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
144
Tobias Grosser5842dee2017-03-17 13:00:53 +0000145static cl::opt<bool> PollyIgnoreParamBounds(
146 "polly-ignore-parameter-bounds",
147 cl::desc(
148 "Do not add parameter bounds and do no gist simplify sets accordingly"),
149 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
150
Tobias Grosserc2f15102017-03-01 21:11:27 +0000151static cl::opt<bool> PollyPreciseFoldAccesses(
152 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000153 cl::desc("Fold memory accesses to model more possible delinearizations "
154 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000155 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000156
Michael Kruse5ae08c02017-05-06 14:03:58 +0000157bool polly::UseInstructionNames;
158static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000159 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000160 cl::desc("Use LLVM-IR names when deriving statement names"),
161 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
162 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000163
Michael Kruse7bf39442015-09-10 12:46:52 +0000164//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000165
Michael Kruse046dde42015-08-10 13:01:57 +0000166// Create a sequence of two schedules. Either argument may be null and is
167// interpreted as the empty schedule. Can also return null if both schedules are
168// empty.
169static __isl_give isl_schedule *
170combineInSequence(__isl_take isl_schedule *Prev,
171 __isl_take isl_schedule *Succ) {
172 if (!Prev)
173 return Succ;
174 if (!Succ)
175 return Prev;
176
177 return isl_schedule_sequence(Prev, Succ);
178}
179
Johannes Doerferte7044942015-02-24 11:58:30 +0000180static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
181 const ConstantRange &Range,
182 int dim,
183 enum isl_dim_type type) {
184 isl_val *V;
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000185 isl_ctx *Ctx = isl_set_get_ctx(S);
Johannes Doerferte7044942015-02-24 11:58:30 +0000186
Tobias Grosser3281f602017-02-16 18:39:14 +0000187 // The upper and lower bound for a parameter value is derived either from
188 // the data type of the parameter or from the - possibly more restrictive -
189 // range metadata.
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000190 V = isl_valFromAPInt(Ctx, Range.getSignedMin(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000191 S = isl_set_lower_bound_val(S, type, dim, V);
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000192 V = isl_valFromAPInt(Ctx, Range.getSignedMax(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000193 S = isl_set_upper_bound_val(S, type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000194
Tobias Grosser3281f602017-02-16 18:39:14 +0000195 if (Range.isFullSet())
196 return S;
197
Tobias Grosserc8a82762017-02-16 19:11:25 +0000198 if (isl_set_n_basic_set(S) > MaxDisjunctsInContext)
199 return S;
200
Tobias Grosser3281f602017-02-16 18:39:14 +0000201 // In case of signed wrapping, we can refine the set of valid values by
202 // excluding the part not covered by the wrapping range.
203 if (Range.isSignWrappedSet()) {
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000204 V = isl_valFromAPInt(Ctx, Range.getLower(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000205 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
206
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000207 V = isl_valFromAPInt(Ctx, Range.getUpper(), true);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000208 V = isl_val_sub_ui(V, 1);
Tobias Grosser3281f602017-02-16 18:39:14 +0000209 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
210 S = isl_set_union(SLB, SUB);
211 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000212
Tobias Grosser3281f602017-02-16 18:39:14 +0000213 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000214}
215
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000216static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
217 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
218 if (!BasePtrLI)
219 return nullptr;
220
Johannes Doerfert952b5302016-05-23 12:40:48 +0000221 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000222 return nullptr;
223
224 ScalarEvolution &SE = *S->getSE();
225
226 auto *OriginBaseSCEV =
227 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
228 if (!OriginBaseSCEV)
229 return nullptr;
230
231 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
232 if (!OriginBaseSCEVUnknown)
233 return nullptr;
234
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000235 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000236 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000237}
238
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000239ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000240 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000241 const DataLayout &DL, Scop *S,
242 const char *BaseName)
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000243 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000244 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000245 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000246 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
247 Kind == MemoryKind::PHI ? "__phi" : "",
248 UseInstructionNames);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000249 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000250
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000251 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000252
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000253 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000254 BasePtrOriginSAI = nullptr;
255 return;
256 }
257
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000258 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
259 if (BasePtrOriginSAI)
260 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000261}
262
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000263__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000264 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000265 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
266 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
267 return Space;
268}
269
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000270bool ScopArrayInfo::isReadOnly() {
271 isl_union_set *WriteSet = isl_union_map_range(S.getWrites());
272 isl_space *Space = getSpace();
273 WriteSet = isl_union_set_intersect(
274 WriteSet, isl_union_set_from_set(isl_set_universe(Space)));
275
276 bool IsReadOnly = isl_union_set_is_empty(WriteSet);
277 isl_union_set_free(WriteSet);
278
279 return IsReadOnly;
280}
281
Tobias Grosserf3adab42017-05-10 10:59:58 +0000282bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
283 if (Array->getElementType() != getElementType())
284 return false;
285
286 if (Array->getNumberOfDimensions() != getNumberOfDimensions())
287 return false;
288
289 for (unsigned i = 0; i < getNumberOfDimensions(); i++)
290 if (Array->getDimensionSize(i) != getDimensionSize(i))
291 return false;
292
293 return true;
294}
295
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000296void ScopArrayInfo::updateElementType(Type *NewElementType) {
297 if (NewElementType == ElementType)
298 return;
299
Tobias Grosserd840fc72016-02-04 13:18:42 +0000300 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
301 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
302
Johannes Doerferta7920982016-02-25 14:08:48 +0000303 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000304 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000305
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000306 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
307 ElementType = NewElementType;
308 } else {
309 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
310 ElementType = IntegerType::get(ElementType->getContext(), GCD);
311 }
312}
313
Tobias Grosserbedef002016-12-02 08:10:56 +0000314bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
315 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000316 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
317 int ExtraDimsNew = NewSizes.size() - SharedDims;
318 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000319
Tobias Grosserbedef002016-12-02 08:10:56 +0000320 if (CheckConsistency) {
321 for (int i = 0; i < SharedDims; i++) {
322 auto *NewSize = NewSizes[i + ExtraDimsNew];
323 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
324 if (NewSize && KnownSize && NewSize != KnownSize)
325 return false;
326 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000327
Tobias Grosserbedef002016-12-02 08:10:56 +0000328 if (DimensionSizes.size() >= NewSizes.size())
329 return true;
330 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000331
332 DimensionSizes.clear();
333 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
334 NewSizes.end());
335 for (isl_pw_aff *Size : DimensionSizesPw)
336 isl_pw_aff_free(Size);
337 DimensionSizesPw.clear();
338 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000339 if (!Expr) {
340 DimensionSizesPw.push_back(nullptr);
341 continue;
342 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000343 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000344 DimensionSizesPw.push_back(Size);
345 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000346 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000347}
348
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000349ScopArrayInfo::~ScopArrayInfo() {
350 isl_id_free(Id);
351 for (isl_pw_aff *Size : DimensionSizesPw)
352 isl_pw_aff_free(Size);
353}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000354
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000355std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
356
357int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000358 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000359}
360
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000361__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
362 return isl_id_copy(Id);
363}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000364
365void ScopArrayInfo::dump() const { print(errs()); }
366
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000367void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000368 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000369 unsigned u = 0;
370 if (getNumberOfDimensions() > 0 && !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000371 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000372 u++;
373 }
374 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000375 OS << "[";
376
Tobias Grosser26253842015-11-10 14:24:21 +0000377 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000378 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000379 OS << " " << Size << " ";
380 isl_pw_aff_free(Size);
381 } else {
382 OS << *getDimensionSize(u);
383 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000384
385 OS << "]";
386 }
387
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000388 OS << ";";
389
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000390 if (BasePtrOriginSAI)
391 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
392
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000393 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000394}
395
396const ScopArrayInfo *
397ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
398 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
399 assert(Id && "Output dimension didn't have an ID");
400 return getFromId(Id);
401}
402
Michael Krused56b90a2016-09-01 09:03:27 +0000403const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000404 void *User = isl_id_get_user(Id);
405 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
406 isl_id_free(Id);
407 return SAI;
408}
409
Michael Kruse3b425ff2016-04-11 14:34:08 +0000410void MemoryAccess::wrapConstantDimensions() {
411 auto *SAI = getScopArrayInfo();
412 auto *ArraySpace = SAI->getSpace();
413 auto *Ctx = isl_space_get_ctx(ArraySpace);
414 unsigned DimsArray = SAI->getNumberOfDimensions();
415
416 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
417 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
418 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
419
420 // Begin with last dimension, to iteratively carry into higher dimensions.
421 for (int i = DimsArray - 1; i > 0; i--) {
422 auto *DimSize = SAI->getDimensionSize(i);
423 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
424
425 // This transformation is not applicable to dimensions with dynamic size.
426 if (!DimSizeCst)
427 continue;
428
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000429 // This transformation is not applicable to dimensions of size zero.
430 if (DimSize->isZero())
431 continue;
432
Michael Kruse3b425ff2016-04-11 14:34:08 +0000433 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
434 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
435 isl_dim_set, i);
436 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
437 isl_dim_set, i - 1);
438
439 // Compute: index % size
440 // Modulo must apply in the divide of the previous iteration, if any.
441 auto *Modulo = isl_aff_copy(Var);
442 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
443 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
444
445 // Compute: floor(index / size)
446 auto *Divide = Var;
447 Divide = isl_aff_div(
448 Divide,
449 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
450 Divide = isl_aff_floor(Divide);
451 Divide = isl_aff_add(Divide, PrevVar);
452 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
453
454 // Apply Modulo and Divide.
455 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
456 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
457 }
458
459 // Apply all modulo/divides on the accesses.
460 AccessRelation =
461 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
462 AccessRelation = isl_map_detect_equalities(AccessRelation);
463 isl_local_space_free(LArraySpace);
464}
465
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000466void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000467 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000468 auto *ArraySpace = SAI->getSpace();
469 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000470 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000471
472 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
473 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
474 auto DimsMissing = DimsArray - DimsAccess;
475
Michael Kruse375cb5f2016-02-24 22:08:24 +0000476 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000477 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000478 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000479 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000480
Johannes Doerferta90943d2016-02-21 16:37:25 +0000481 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000482 isl_set_universe(AccessSpace),
483 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000484
485 for (unsigned i = 0; i < DimsMissing; i++)
486 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
487
488 for (unsigned i = DimsMissing; i < DimsArray; i++)
489 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
490
491 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000492
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000493 // For the non delinearized arrays, divide the access function of the last
494 // subscript by the size of the elements in the array.
495 //
496 // A stride one array access in C expressed as A[i] is expressed in
497 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
498 // two subsequent values of 'i' index two values that are stored next to
499 // each other in memory. By this division we make this characteristic
500 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000501 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000502 // that divides the offsets of all accesses to this base pointer.
503 if (DimsAccess == 1) {
504 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
505 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
506 }
507
Michael Kruse3b425ff2016-04-11 14:34:08 +0000508 // We currently do this only if we added at least one dimension, which means
509 // some dimension's indices have not been specified, an indicator that some
510 // index values have been added together.
511 // TODO: Investigate general usefulness; Effect on unit tests is to make index
512 // expressions more complicated.
513 if (DimsMissing)
514 wrapConstantDimensions();
515
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000516 if (!isAffine())
517 computeBoundsOnAccessRelation(ArrayElemSize);
518
Tobias Grosserd840fc72016-02-04 13:18:42 +0000519 // Introduce multi-element accesses in case the type loaded by this memory
520 // access is larger than the canonical element type of the array.
521 //
522 // An access ((float *)A)[i] to an array char *A is modeled as
523 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000524 if (ElemBytes > ArrayElemSize) {
525 assert(ElemBytes % ArrayElemSize == 0 &&
526 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000527 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000528 isl_set_universe(isl_space_copy(ArraySpace)),
529 isl_set_universe(isl_space_copy(ArraySpace)));
530 for (unsigned i = 0; i < DimsArray - 1; i++)
531 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
532
Tobias Grosserd840fc72016-02-04 13:18:42 +0000533 isl_constraint *C;
534 isl_local_space *LS;
535
536 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000537 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
538
539 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
540 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000541 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000542 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
543 Map = isl_map_add_constraint(Map, C);
544
545 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000546 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000547 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
548 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
549 Map = isl_map_add_constraint(Map, C);
550 AccessRelation = isl_map_apply_range(AccessRelation, Map);
551 }
552
553 isl_space_free(ArraySpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000554}
555
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000556const std::string
557MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
558 switch (RT) {
559 case MemoryAccess::RT_NONE:
560 llvm_unreachable("Requested a reduction operator string for a memory "
561 "access which isn't a reduction");
562 case MemoryAccess::RT_ADD:
563 return "+";
564 case MemoryAccess::RT_MUL:
565 return "*";
566 case MemoryAccess::RT_BOR:
567 return "|";
568 case MemoryAccess::RT_BXOR:
569 return "^";
570 case MemoryAccess::RT_BAND:
571 return "&";
572 }
573 llvm_unreachable("Unknown reduction type");
574 return "";
575}
576
Tobias Grosserc80d6972016-09-02 06:33:33 +0000577/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000578static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
579 const Instruction *Load) {
580 if (!BinOp)
581 return MemoryAccess::RT_NONE;
582 switch (BinOp->getOpcode()) {
583 case Instruction::FAdd:
584 if (!BinOp->hasUnsafeAlgebra())
585 return MemoryAccess::RT_NONE;
586 // Fall through
587 case Instruction::Add:
588 return MemoryAccess::RT_ADD;
589 case Instruction::Or:
590 return MemoryAccess::RT_BOR;
591 case Instruction::Xor:
592 return MemoryAccess::RT_BXOR;
593 case Instruction::And:
594 return MemoryAccess::RT_BAND;
595 case Instruction::FMul:
596 if (!BinOp->hasUnsafeAlgebra())
597 return MemoryAccess::RT_NONE;
598 // Fall through
599 case Instruction::Mul:
600 if (DisableMultiplicativeReductions)
601 return MemoryAccess::RT_NONE;
602 return MemoryAccess::RT_MUL;
603 default:
604 return MemoryAccess::RT_NONE;
605 }
606}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000607
Tobias Grosser75805372011-04-29 06:27:02 +0000608MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000609 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000610 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000611 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000612 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000613}
614
Michael Kruse2fa35192016-09-01 19:53:31 +0000615const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000616 isl_id *ArrayId = getArrayId();
617 void *User = isl_id_get_user(ArrayId);
618 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
619 isl_id_free(ArrayId);
620 return SAI;
621}
622
Michael Kruse2fa35192016-09-01 19:53:31 +0000623const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
624 isl_id *ArrayId = getLatestArrayId();
625 void *User = isl_id_get_user(ArrayId);
626 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
627 isl_id_free(ArrayId);
628 return SAI;
629}
630
631__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000632 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
633}
634
Michael Kruse2fa35192016-09-01 19:53:31 +0000635__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
636 if (!hasNewAccessRelation())
637 return getOriginalArrayId();
638 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
639}
640
Tobias Grosserd840fc72016-02-04 13:18:42 +0000641__isl_give isl_map *MemoryAccess::getAddressFunction() const {
642 return isl_map_lexmin(getAccessRelation());
643}
644
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000645__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
646 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000647 isl_map *Schedule, *ScheduledAccRel;
648 isl_union_set *UDomain;
649
650 UDomain = isl_union_set_from_set(getStatement()->getDomain());
651 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
652 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000653 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000654 return isl_pw_multi_aff_from_map(ScheduledAccRel);
655}
656
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000657__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000658 return isl_map_copy(AccessRelation);
659}
660
Johannes Doerferta99130f2014-10-13 12:58:03 +0000661std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000662 return stringFromIslObj(AccessRelation);
663}
664
Johannes Doerferta99130f2014-10-13 12:58:03 +0000665__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000666 return isl_map_get_space(AccessRelation);
667}
668
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000669__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000670 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000671}
672
Tobias Grosser6f730082015-09-05 07:46:47 +0000673std::string MemoryAccess::getNewAccessRelationStr() const {
674 return stringFromIslObj(NewAccessRelation);
675}
676
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000677__isl_give isl_basic_map *
678MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000679 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000680 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000681
Tobias Grosser084d8f72012-05-29 09:29:44 +0000682 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000683 isl_basic_set_universe(Statement->getDomainSpace()),
684 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000685}
686
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000687// Formalize no out-of-bound access assumption
688//
689// When delinearizing array accesses we optimistically assume that the
690// delinearized accesses do not access out of bound locations (the subscript
691// expression of each array evaluates for each statement instance that is
692// executed to a value that is larger than zero and strictly smaller than the
693// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000694// dimension for which we do not need to assume any upper bound. At this point
695// we formalize this assumption to ensure that at code generation time the
696// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000697//
698// To find the set of constraints necessary to avoid out of bound accesses, we
699// first build the set of data locations that are not within array bounds. We
700// then apply the reverse access relation to obtain the set of iterations that
701// may contain invalid accesses and reduce this set of iterations to the ones
702// that are actually executed by intersecting them with the domain of the
703// statement. If we now project out all loop dimensions, we obtain a set of
704// parameters that may cause statement instances to be executed that may
705// possibly yield out of bound memory accesses. The complement of these
706// constraints is the set of constraints that needs to be assumed to ensure such
707// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000708void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000709 if (PollyIgnoreInbounds)
710 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000711 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000712 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000713 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000714 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000715 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
716 isl_pw_aff *Var =
717 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
718 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
719
720 isl_set *DimOutside;
721
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000722 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000723 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000724 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
725 isl_space_dim(Space, isl_dim_set));
726 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
727 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000728
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000729 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000730
731 Outside = isl_set_union(Outside, DimOutside);
732 }
733
734 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
735 Outside = isl_set_intersect(Outside, Statement->getDomain());
736 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000737
738 // Remove divs to avoid the construction of overly complicated assumptions.
739 // Doing so increases the set of parameter combinations that are assumed to
740 // not appear. This is always save, but may make the resulting run-time check
741 // bail out more often than strictly necessary.
742 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000743 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000744 const auto &Loc = getAccessInstruction()
745 ? getAccessInstruction()->getDebugLoc()
746 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000747 if (!PollyPreciseInbounds)
748 Outside = isl_set_gist(Outside, isl_set_params(Statement->getDomain()));
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000749 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
750 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000751 isl_space_free(Space);
752}
753
Johannes Doerfertcea61932016-02-21 19:13:19 +0000754void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000755 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000756 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000757
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000758 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000759 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000760
761 isl_map *LengthMap;
762 if (Subscripts[1] == nullptr) {
763 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
764 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000765 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000766 LengthMap = isl_map_from_pw_aff(LengthPWA);
767 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
768 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
769 }
770 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
771 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000772 SubscriptMap =
773 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000774 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
775 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
776 getStatement()->getDomainId());
777}
778
Johannes Doerferte7044942015-02-24 11:58:30 +0000779void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
780 ScalarEvolution *SE = Statement->getParent()->getSE();
781
Johannes Doerfertcea61932016-02-21 19:13:19 +0000782 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000783 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000784 return;
785
786 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000787 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
788 return;
789
790 auto *PtrSCEV = SE->getSCEV(Ptr);
791 if (isa<SCEVCouldNotCompute>(PtrSCEV))
792 return;
793
794 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
795 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
796 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
797
798 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
799 if (Range.isFullSet())
800 return;
801
Tobias Grosserd5727c52017-05-05 13:20:47 +0000802 if (Range.isWrappedSet() | Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000803 return;
804
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000805 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000806
Johannes Doerferte7044942015-02-24 11:58:30 +0000807 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000808 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000809 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000810 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000811
812 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000813 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000814
Tobias Grosserb3a85882017-02-12 08:11:12 +0000815 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
816
Johannes Doerferte7044942015-02-24 11:58:30 +0000817 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
818 AccessRange =
819 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
820 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
821}
822
Tobias Grosser491b7992016-12-02 05:21:22 +0000823void MemoryAccess::foldAccessRelation() {
824 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
825 return;
826
Michael Krusee2bccbb2015-09-18 19:59:43 +0000827 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000828
Tobias Grosserc2f15102017-03-01 21:11:27 +0000829 isl_map *OldAccessRelation = isl_map_copy(AccessRelation);
830
Tobias Grosser619190d2015-03-30 17:22:28 +0000831 for (int i = Size - 2; i >= 0; --i) {
832 isl_space *Space;
833 isl_map *MapOne, *MapTwo;
Roman Gareevf5aff702016-09-12 17:08:31 +0000834 isl_pw_aff *DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000835
836 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
837 isl_pw_aff_free(DimSize);
838 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
839
840 Space = isl_map_get_space(AccessRelation);
841 Space = isl_space_map_from_set(isl_space_range(Space));
842 Space = isl_space_align_params(Space, SpaceSize);
843
844 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
845 isl_id_free(ParamId);
846
847 MapOne = isl_map_universe(isl_space_copy(Space));
848 for (int j = 0; j < Size; ++j)
849 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
850 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
851
852 MapTwo = isl_map_universe(isl_space_copy(Space));
853 for (int j = 0; j < Size; ++j)
854 if (j < i || j > i + 1)
855 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
856
857 isl_local_space *LS = isl_local_space_from_space(Space);
858 isl_constraint *C;
859 C = isl_equality_alloc(isl_local_space_copy(LS));
860 C = isl_constraint_set_constant_si(C, -1);
861 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
862 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
863 MapTwo = isl_map_add_constraint(MapTwo, C);
864 C = isl_equality_alloc(LS);
865 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
866 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
867 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
868 MapTwo = isl_map_add_constraint(MapTwo, C);
869 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
870
871 MapOne = isl_map_union(MapOne, MapTwo);
872 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
873 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000874
875 isl_id *BaseAddrId = getScopArrayInfo()->getBasePtrId();
876 auto Space = Statement->getDomainSpace();
877 AccessRelation = isl_map_set_tuple_id(
878 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
879 AccessRelation =
880 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
881 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Tobias Grosserc2f15102017-03-01 21:11:27 +0000882
883 // Access dimension folding might in certain cases increase the number of
884 // disjuncts in the memory access, which can possibly complicate the generated
885 // run-time checks and can lead to costly compilation.
886 if (!PollyPreciseFoldAccesses && isl_map_n_basic_map(AccessRelation) >
887 isl_map_n_basic_map(OldAccessRelation)) {
888 isl_map_free(AccessRelation);
889 AccessRelation = OldAccessRelation;
890 } else {
891 isl_map_free(OldAccessRelation);
892 }
893
Tobias Grosser491b7992016-12-02 05:21:22 +0000894 isl_space_free(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000895}
896
Tobias Grosserc80d6972016-09-02 06:33:33 +0000897/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000898static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000899 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000900 if (Size == 1)
901 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000902
903 // Only one factor needs to be divisible.
904 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
905 for (auto *FactorExpr : MulExpr->operands())
906 if (isDivisible(FactorExpr, Size, SE))
907 return true;
908 return false;
909 }
910
911 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
912 // to be divisble.
913 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
914 for (auto *OpExpr : NAryExpr->operands())
915 if (!isDivisible(OpExpr, Size, SE))
916 return false;
917 return true;
918 }
919
920 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
921 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
922 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
923 return MulSCEV == Expr;
924}
925
Michael Krusee2bccbb2015-09-18 19:59:43 +0000926void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
927 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000928
Johannes Doerfert85676e32016-04-23 14:32:34 +0000929 // Initialize the invalid domain which describes all iterations for which the
930 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000931 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
932 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
933 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000934
Michael Krusee2bccbb2015-09-18 19:59:43 +0000935 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000936 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000937
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000938 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
939 buildMemIntrinsicAccessRelation();
940 AccessRelation =
941 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
942 return;
943 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000944
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000945 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000946 // We overapproximate non-affine accesses with a possible access to the
947 // whole array. For read accesses it does not make a difference, if an
948 // access must or may happen. However, for write accesses it is important to
949 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000950 if (!AccessRelation)
951 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
952
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000953 AccessRelation =
954 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000955 return;
956 }
957
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000958 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000959 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000960
Michael Krusee2bccbb2015-09-18 19:59:43 +0000961 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000962 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000963 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000964 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000965 }
966
Tobias Grosser79baa212014-04-10 08:38:02 +0000967 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000968 AccessRelation = isl_map_set_tuple_id(
969 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000970 AccessRelation =
971 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
972
Tobias Grosseraa660a92015-03-30 00:07:50 +0000973 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000974 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000975}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000976
Michael Krusecac948e2015-10-02 13:53:07 +0000977MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000978 AccessType AccType, Value *BaseAddress,
979 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000980 ArrayRef<const SCEV *> Subscripts,
981 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +0000982 MemoryKind Kind)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000983 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Tobias Grosser81331282017-05-03 07:57:35 +0000984 InvalidDomain(nullptr), BaseAddr(BaseAddress), ElementType(ElementType),
985 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
986 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000987 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000988 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000989 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +0000990 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000991
Tobias Grosser81331282017-05-03 07:57:35 +0000992 std::string IdName = Stmt->getBaseName() + Access;
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000993 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
994}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000995
Roman Gareevb3224ad2016-09-14 06:26:09 +0000996MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
997 __isl_take isl_map *AccRel)
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000998 : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
999 Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
1000 IsAffine(true), AccessRelation(nullptr), NewAccessRelation(AccRel) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001001 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
1002 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1003 Sizes.push_back(nullptr);
1004 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1005 Sizes.push_back(SAI->getDimensionSize(i));
1006 ElementType = SAI->getElementType();
1007 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001008 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001009 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001010
Tobias Grosser81331282017-05-03 07:57:35 +00001011 std::string IdName = Stmt->getBaseName() + Access;
Roman Gareevb3224ad2016-09-14 06:26:09 +00001012 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1013}
1014
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001015void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +00001016 auto *Ctx = Statement->getParent()->getContext();
1017 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1018 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001019}
1020
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001021const std::string MemoryAccess::getReductionOperatorStr() const {
1022 return MemoryAccess::getReductionOperatorStr(getReductionType());
1023}
1024
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001025__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
1026
Johannes Doerfertf6183392014-07-01 20:52:51 +00001027raw_ostream &polly::operator<<(raw_ostream &OS,
1028 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001029 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001030 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001031 else
1032 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001033 return OS;
1034}
1035
Tobias Grosser75805372011-04-29 06:27:02 +00001036void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001037 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001038 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001039 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001040 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001041 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001042 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001043 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001044 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001045 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001046 break;
1047 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001048 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +00001049 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001050 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001051 if (hasNewAccessRelation())
1052 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001053}
1054
Tobias Grosser74394f02013-01-14 22:40:23 +00001055void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +00001056
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001057__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
1058 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001059 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +00001060 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
1061 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
1062 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +00001063 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001064}
1065
Tobias Grosser75805372011-04-29 06:27:02 +00001066// Create a map in the size of the provided set domain, that maps from the
1067// one element of the provided set domain to another element of the provided
1068// set domain.
1069// The mapping is limited to all points that are equal in all but the last
1070// dimension and for which the last dimension of the input is strict smaller
1071// than the last dimension of the output.
1072//
1073// getEqualAndLarger(set[i0, i1, ..., iX]):
1074//
1075// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1076// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1077//
Tobias Grosser2a526fe2016-09-08 11:18:56 +00001078static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +00001079 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001080 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +00001081 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001082
1083 // Set all but the last dimension to be equal for the input and output
1084 //
1085 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1086 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001087 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +00001088 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001089
1090 // Set the last dimension of the input to be strict smaller than the
1091 // last dimension of the output.
1092 //
1093 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001094 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1095 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001096 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001097}
1098
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001099__isl_give isl_set *
1100MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001101 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +00001102 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +00001103 isl_space *Space = isl_space_range(isl_map_get_space(S));
1104 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001105
Sebastian Popa00a0292012-12-18 07:46:06 +00001106 S = isl_map_reverse(S);
1107 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001108
Sebastian Popa00a0292012-12-18 07:46:06 +00001109 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1110 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1111 NextScatt = isl_map_apply_domain(NextScatt, S);
1112 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001113
Sebastian Popa00a0292012-12-18 07:46:06 +00001114 isl_set *Deltas = isl_map_deltas(NextScatt);
1115 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001116}
1117
Sebastian Popa00a0292012-12-18 07:46:06 +00001118bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001119 int StrideWidth) const {
1120 isl_set *Stride, *StrideX;
1121 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001122
Sebastian Popa00a0292012-12-18 07:46:06 +00001123 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001124 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001125 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1126 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1127 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1128 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001129 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001130
Tobias Grosser28dd4862012-01-24 16:42:16 +00001131 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001132 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001133
Tobias Grosser28dd4862012-01-24 16:42:16 +00001134 return IsStrideX;
1135}
1136
Michael Krused56b90a2016-09-01 09:03:27 +00001137bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001138 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001139}
1140
Michael Krused56b90a2016-09-01 09:03:27 +00001141bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001142 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001143}
1144
Tobias Grosserbedef002016-12-02 08:10:56 +00001145void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
1146 isl_map_free(AccessRelation);
1147 AccessRelation = NewAccess;
1148}
1149
Michael Krused56b90a2016-09-01 09:03:27 +00001150void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001151 assert(NewAccess);
1152
1153#ifndef NDEBUG
1154 // Check domain space compatibility.
1155 auto *NewSpace = isl_map_get_space(NewAccess);
1156 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1157 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1158 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1159 isl_space_free(NewDomainSpace);
1160 isl_space_free(OriginalDomainSpace);
1161
1162 // Check whether there is an access for every statement instance.
1163 auto *StmtDomain = getStatement()->getDomain();
1164 StmtDomain = isl_set_intersect_params(
1165 StmtDomain, getStatement()->getParent()->getContext());
1166 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1167 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1168 "Partial accesses not supported");
1169 isl_set_free(NewDomain);
1170 isl_set_free(StmtDomain);
1171
Michael Kruse772ce722016-09-01 19:16:58 +00001172 auto *NewAccessSpace = isl_space_range(NewSpace);
1173 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1174 "Must specify the array that is accessed");
1175 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1176 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1177 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001178
1179 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1180 InvariantEquivClassTy *EqClass =
1181 getStatement()->getParent()->lookupInvariantEquivClass(
1182 SAI->getBasePtr());
1183 assert(EqClass &&
1184 "Access functions to indirect arrays must have an invariant and "
1185 "hoisted base pointer");
1186 }
1187
1188 // Check whether access dimensions correspond to number of dimensions of the
1189 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001190 auto Dims = SAI->getNumberOfDimensions();
1191 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1192 "Access dims must match array dims");
1193 isl_space_free(NewAccessSpace);
1194 isl_id_free(NewArrayId);
1195#endif
1196
Tobias Grosser166c4222015-09-05 07:46:40 +00001197 isl_map_free(NewAccessRelation);
1198 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001199}
Tobias Grosser75805372011-04-29 06:27:02 +00001200
1201//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001202
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001203__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001204 isl_set *Domain = getDomain();
1205 if (isl_set_is_empty(Domain)) {
1206 isl_set_free(Domain);
1207 return isl_map_from_aff(
1208 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1209 }
1210 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001211 if (!Schedule) {
1212 isl_set_free(Domain);
1213 return nullptr;
1214 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001215 Schedule = isl_union_map_intersect_domain(
1216 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1217 if (isl_union_map_is_empty(Schedule)) {
1218 isl_set_free(Domain);
1219 isl_union_map_free(Schedule);
1220 return isl_map_from_aff(
1221 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1222 }
1223 auto *M = isl_map_from_union_map(Schedule);
1224 M = isl_map_coalesce(M);
1225 M = isl_map_gist_domain(M, Domain);
1226 M = isl_map_coalesce(M);
1227 return M;
1228}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001229
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001230__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1231 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001232 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1233 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001234}
1235
Tobias Grosser37eb4222014-02-20 21:43:54 +00001236void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1237 assert(isl_set_is_subset(NewDomain, Domain) &&
1238 "New domain is not a subset of old domain!");
1239 isl_set_free(Domain);
1240 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001241}
1242
Michael Krusecac948e2015-10-02 13:53:07 +00001243void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001244 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001245 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001246 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001247
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001248 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001249 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001250 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001251 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001252 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001253 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001254 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001255 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001256 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001257
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001258 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1259 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001260 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001261 }
1262}
1263
Michael Krusecac948e2015-10-02 13:53:07 +00001264void ScopStmt::addAccess(MemoryAccess *Access) {
1265 Instruction *AccessInst = Access->getAccessInstruction();
1266
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001267 if (Access->isArrayKind()) {
1268 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1269 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001270 } else if (Access->isValueKind() && Access->isWrite()) {
1271 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001272 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001273 assert(!ValueWrites.lookup(AccessVal));
1274
1275 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001276 } else if (Access->isValueKind() && Access->isRead()) {
1277 Value *AccessVal = Access->getAccessValue();
1278 assert(!ValueReads.lookup(AccessVal));
1279
1280 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001281 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001282 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001283 assert(!PHIWrites.lookup(PHI));
1284
1285 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001286 }
1287
1288 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001289}
1290
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001291void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001292 for (MemoryAccess *MA : *this)
1293 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001294
Johannes Doerferta60ad842016-05-10 12:18:22 +00001295 auto *Ctx = Parent.getContext();
1296 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1297 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001298}
1299
Tobias Grosserc80d6972016-09-02 06:33:33 +00001300/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001301static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1302 void *User) {
1303 isl_set **BoundedParts = static_cast<isl_set **>(User);
1304 if (isl_basic_set_is_bounded(BSet))
1305 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1306 else
1307 isl_basic_set_free(BSet);
1308 return isl_stat_ok;
1309}
1310
Tobias Grosserc80d6972016-09-02 06:33:33 +00001311/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001312static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1313 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1314 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1315 isl_set_free(S);
1316 return BoundedParts;
1317}
1318
Tobias Grosserc80d6972016-09-02 06:33:33 +00001319/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001320///
1321/// @returns A separation of @p S into first an unbounded then a bounded subset,
1322/// both with regards to the dimension @p Dim.
1323static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1324partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1325
1326 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001327 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001328
1329 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001330 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001331
1332 // Remove dimensions that are greater than Dim as they are not interesting.
1333 assert(NumDimsS >= Dim + 1);
1334 OnlyDimS =
1335 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1336
1337 // Create artificial parametric upper bounds for dimensions smaller than Dim
1338 // as we are not interested in them.
1339 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1340 for (unsigned u = 0; u < Dim; u++) {
1341 isl_constraint *C = isl_inequality_alloc(
1342 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1343 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1344 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1345 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1346 }
1347
1348 // Collect all bounded parts of OnlyDimS.
1349 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1350
1351 // Create the dimensions greater than Dim again.
1352 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1353 NumDimsS - Dim - 1);
1354
1355 // Remove the artificial upper bound parameters again.
1356 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1357
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001358 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001359 return std::make_pair(UnboundedParts, BoundedParts);
1360}
1361
Tobias Grosserc80d6972016-09-02 06:33:33 +00001362/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001363static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1364 __isl_take isl_set *To) {
1365 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1366 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1367 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1368 }
1369 return To;
1370}
1371
Tobias Grosserc80d6972016-09-02 06:33:33 +00001372/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001373static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001374 __isl_take isl_pw_aff *L,
1375 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001376 switch (Pred) {
1377 case ICmpInst::ICMP_EQ:
1378 return isl_pw_aff_eq_set(L, R);
1379 case ICmpInst::ICMP_NE:
1380 return isl_pw_aff_ne_set(L, R);
1381 case ICmpInst::ICMP_SLT:
1382 return isl_pw_aff_lt_set(L, R);
1383 case ICmpInst::ICMP_SLE:
1384 return isl_pw_aff_le_set(L, R);
1385 case ICmpInst::ICMP_SGT:
1386 return isl_pw_aff_gt_set(L, R);
1387 case ICmpInst::ICMP_SGE:
1388 return isl_pw_aff_ge_set(L, R);
1389 case ICmpInst::ICMP_ULT:
1390 return isl_pw_aff_lt_set(L, R);
1391 case ICmpInst::ICMP_UGT:
1392 return isl_pw_aff_gt_set(L, R);
1393 case ICmpInst::ICMP_ULE:
1394 return isl_pw_aff_le_set(L, R);
1395 case ICmpInst::ICMP_UGE:
1396 return isl_pw_aff_ge_set(L, R);
1397 default:
1398 llvm_unreachable("Non integer predicate not supported");
1399 }
1400}
1401
Tobias Grosserc80d6972016-09-02 06:33:33 +00001402/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001403///
1404/// Helper function that will make sure the dimensions of the result have the
1405/// same isl_id's as the @p Domain.
1406static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1407 __isl_take isl_pw_aff *L,
1408 __isl_take isl_pw_aff *R,
1409 __isl_keep isl_set *Domain) {
1410 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1411 return setDimensionIds(Domain, ConsequenceCondSet);
1412}
1413
Tobias Grosserc80d6972016-09-02 06:33:33 +00001414/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001415///
1416/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001417/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1418/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001419static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001420buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1421 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001422 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1423
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001424 Value *Condition = getConditionFromTerminator(SI);
1425 assert(Condition && "No condition for switch");
1426
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001427 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001428 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001429 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001430 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001431
1432 unsigned NumSuccessors = SI->getNumSuccessors();
1433 ConditionSets.resize(NumSuccessors);
1434 for (auto &Case : SI->cases()) {
1435 unsigned Idx = Case.getSuccessorIndex();
1436 ConstantInt *CaseValue = Case.getCaseValue();
1437
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001438 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001439 isl_set *CaseConditionSet =
1440 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1441 ConditionSets[Idx] = isl_set_coalesce(
1442 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1443 }
1444
1445 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1446 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1447 for (unsigned u = 2; u < NumSuccessors; u++)
1448 ConditionSetUnion =
1449 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1450 ConditionSets[0] = setDimensionIds(
1451 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1452
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001453 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001454
1455 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001456}
1457
Tobias Grosserc80d6972016-09-02 06:33:33 +00001458/// Build the conditions sets for the branch condition @p Condition in
1459/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001460///
1461/// This will fill @p ConditionSets with the conditions under which control
1462/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001463/// have as many elements as @p TI has successors. If @p TI is nullptr the
1464/// context under which @p Condition is true/false will be returned as the
1465/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001466static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001467buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1468 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001469 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1470
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001471 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001472 isl_set *ConsequenceCondSet = nullptr;
1473 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1474 if (CCond->isZero())
1475 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1476 else
1477 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1478 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1479 auto Opcode = BinOp->getOpcode();
1480 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1481
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001482 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1483 ConditionSets) &&
1484 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1485 ConditionSets);
1486 if (!Valid) {
1487 while (!ConditionSets.empty())
1488 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001489 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001490 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001491
1492 isl_set_free(ConditionSets.pop_back_val());
1493 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1494 isl_set_free(ConditionSets.pop_back_val());
1495 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1496
1497 if (Opcode == Instruction::And)
1498 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1499 else
1500 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1501 } else {
1502 auto *ICond = dyn_cast<ICmpInst>(Condition);
1503 assert(ICond &&
1504 "Condition of exiting branch was neither constant nor ICmp!");
1505
1506 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001507 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001508 // For unsigned comparisons we assumed the signed bit of neither operand
1509 // to be set. The comparison is equal to a signed comparison under this
1510 // assumption.
1511 bool NonNeg = ICond->isUnsigned();
1512 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1513 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001514 ConsequenceCondSet =
1515 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1516 }
1517
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001518 // If no terminator was given we are only looking for parameter constraints
1519 // under which @p Condition is true/false.
1520 if (!TI)
1521 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001522 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001523 ConsequenceCondSet = isl_set_coalesce(
1524 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001525
Johannes Doerfertb2885792016-04-26 09:20:41 +00001526 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001527 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001528 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001529
Michael Krusef7a4a942016-05-02 12:25:36 +00001530 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001531 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1532 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001533 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001534 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001535 }
1536
Michael Krusef7a4a942016-05-02 12:25:36 +00001537 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001538 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001539 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001540 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001541 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001542 }
1543
1544 ConditionSets.push_back(ConsequenceCondSet);
1545 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001546
1547 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001548}
1549
Tobias Grosserc80d6972016-09-02 06:33:33 +00001550/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001551///
1552/// This will fill @p ConditionSets with the conditions under which control
1553/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1554/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001555static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001556buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001557 __isl_keep isl_set *Domain,
1558 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1559
1560 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001561 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001562
1563 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1564
1565 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001566 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001567 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001568 }
1569
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001570 Value *Condition = getConditionFromTerminator(TI);
1571 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001572
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001573 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001574}
1575
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001576void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001577 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001578
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001579 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001580 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001581}
1582
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001583void ScopStmt::collectSurroundingLoops() {
1584 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1585 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1586 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1587 isl_id_free(DimId);
1588 }
1589}
1590
Michael Kruse55454072017-03-15 22:16:43 +00001591ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001592 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
Michael Kruse55454072017-03-15 22:16:43 +00001593 R(&R), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001594
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001595 BaseName = getIslCompatibleName(
1596 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001597}
1598
Michael Kruse55454072017-03-15 22:16:43 +00001599ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001600 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Michael Kruse55454072017-03-15 22:16:43 +00001601 R(nullptr), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Tobias Grosser75805372011-04-29 06:27:02 +00001602
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001603 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), "",
1604 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001605}
1606
Roman Gareevb3224ad2016-09-14 06:26:09 +00001607ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1608 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1609 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1610 R(nullptr), Build(nullptr) {
1611 BaseName = getIslCompatibleName("CopyStmt_", "",
1612 std::to_string(parent.getCopyStmtsNum()));
1613 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1614 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1615 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1616 auto *Access =
1617 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1618 parent.addAccessFunction(Access);
1619 addAccess(Access);
1620 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1621 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1622 parent.addAccessFunction(Access);
1623 addAccess(Access);
1624}
1625
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001626void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001627 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001628
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001629 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001630 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001631 buildAccessRelations();
1632
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001633 if (DetectReductions)
1634 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001635}
1636
Tobias Grosserc80d6972016-09-02 06:33:33 +00001637/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001638///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001639/// Check if the stored value for @p StoreMA is a binary operator with one or
1640/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001641/// used only once (by @p StoreMA) and its load operands are also used only
1642/// once, we have found a possible reduction chain. It starts at an operand
1643/// load and includes the binary operator and @p StoreMA.
1644///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001645/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001646/// escape this block or into any other store except @p StoreMA.
1647void ScopStmt::collectCandiateReductionLoads(
1648 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1649 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1650 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001651 return;
1652
1653 // Skip if there is not one binary operator between the load and the store
1654 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001655 if (!BinOp)
1656 return;
1657
1658 // Skip if the binary operators has multiple uses
1659 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001660 return;
1661
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001662 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001663 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1664 return;
1665
Johannes Doerfert9890a052014-07-01 00:32:29 +00001666 // Skip if the binary operator is outside the current SCoP
1667 if (BinOp->getParent() != Store->getParent())
1668 return;
1669
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001670 // Skip if it is a multiplicative reduction and we disabled them
1671 if (DisableMultiplicativeReductions &&
1672 (BinOp->getOpcode() == Instruction::Mul ||
1673 BinOp->getOpcode() == Instruction::FMul))
1674 return;
1675
Johannes Doerferte58a0122014-06-27 20:31:28 +00001676 // Check the binary operator operands for a candidate load
1677 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1678 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1679 if (!PossibleLoad0 && !PossibleLoad1)
1680 return;
1681
1682 // A load is only a candidate if it cannot escape (thus has only this use)
1683 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001684 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001685 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001686 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001687 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001688 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001689}
1690
Tobias Grosserc80d6972016-09-02 06:33:33 +00001691/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001692///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001693/// Iterate over all store memory accesses and check for valid binary reduction
1694/// like chains. For all candidates we check if they have the same base address
1695/// and there are no other accesses which overlap with them. The base address
1696/// check rules out impossible reductions candidates early. The overlap check,
1697/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001698/// guarantees that none of the intermediate results will escape during
1699/// execution of the loop nest. We basically check here that no other memory
1700/// access can access the same memory as the potential reduction.
1701void ScopStmt::checkForReductions() {
1702 SmallVector<MemoryAccess *, 2> Loads;
1703 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1704
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001705 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001706 // stores and collecting possible reduction loads.
1707 for (MemoryAccess *StoreMA : MemAccs) {
1708 if (StoreMA->isRead())
1709 continue;
1710
1711 Loads.clear();
1712 collectCandiateReductionLoads(StoreMA, Loads);
1713 for (MemoryAccess *LoadMA : Loads)
1714 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1715 }
1716
1717 // Then check each possible candidate pair.
1718 for (const auto &CandidatePair : Candidates) {
1719 bool Valid = true;
1720 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1721 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1722
1723 // Skip those with obviously unequal base addresses.
1724 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1725 isl_map_free(LoadAccs);
1726 isl_map_free(StoreAccs);
1727 continue;
1728 }
1729
1730 // And check if the remaining for overlap with other memory accesses.
1731 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1732 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1733 isl_set *AllAccs = isl_map_range(AllAccsRel);
1734
1735 for (MemoryAccess *MA : MemAccs) {
1736 if (MA == CandidatePair.first || MA == CandidatePair.second)
1737 continue;
1738
1739 isl_map *AccRel =
1740 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1741 isl_set *Accs = isl_map_range(AccRel);
1742
Tobias Grosser55a7af72016-09-08 14:08:07 +00001743 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001744 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1745 Valid = Valid && isl_set_is_empty(OverlapAccs);
1746 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001747 } else {
1748 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001749 }
1750 }
1751
1752 isl_set_free(AllAccs);
1753 if (!Valid)
1754 continue;
1755
Johannes Doerfertf6183392014-07-01 20:52:51 +00001756 const LoadInst *Load =
1757 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1758 MemoryAccess::ReductionType RT =
1759 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1760
Johannes Doerferte58a0122014-06-27 20:31:28 +00001761 // If no overlapping access was found we mark the load and store as
1762 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001763 CandidatePair.first->markAsReductionLike(RT);
1764 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001765 }
Tobias Grosser75805372011-04-29 06:27:02 +00001766}
1767
Tobias Grosser74394f02013-01-14 22:40:23 +00001768std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001769
Tobias Grosser54839312015-04-21 11:37:25 +00001770std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001771 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001772 if (!S)
1773 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001774 auto Str = stringFromIslObj(S);
1775 isl_map_free(S);
1776 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001777}
1778
Johannes Doerferta3519512016-04-23 13:02:23 +00001779void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1780 isl_set_free(InvalidDomain);
1781 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001782}
1783
Michael Kruse375cb5f2016-02-24 22:08:24 +00001784BasicBlock *ScopStmt::getEntryBlock() const {
1785 if (isBlockStmt())
1786 return getBasicBlock();
1787 return getRegion()->getEntry();
1788}
1789
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001790unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001791
Tobias Grosser75805372011-04-29 06:27:02 +00001792const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1793
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001794Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001795 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001796}
1797
Tobias Grosser74394f02013-01-14 22:40:23 +00001798isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001799
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001800__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001801
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001802__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001803 return isl_set_get_space(Domain);
1804}
1805
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001806__isl_give isl_id *ScopStmt::getDomainId() const {
1807 return isl_set_get_tuple_id(Domain);
1808}
Tobias Grossercd95b772012-08-30 11:49:38 +00001809
Johannes Doerfert7c013572016-04-12 09:57:34 +00001810ScopStmt::~ScopStmt() {
1811 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001812 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001813}
Tobias Grosser75805372011-04-29 06:27:02 +00001814
1815void ScopStmt::print(raw_ostream &OS) const {
1816 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001817 OS.indent(12) << "Domain :=\n";
1818
1819 if (Domain) {
1820 OS.indent(16) << getDomainStr() << ";\n";
1821 } else
1822 OS.indent(16) << "n/a\n";
1823
Tobias Grosser54839312015-04-21 11:37:25 +00001824 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001825
1826 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001827 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001828 } else
1829 OS.indent(16) << "n/a\n";
1830
Tobias Grosser083d3d32014-06-28 08:59:45 +00001831 for (MemoryAccess *Access : MemAccs)
1832 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001833}
1834
1835void ScopStmt::dump() const { print(dbgs()); }
1836
Michael Kruse10071822016-05-23 14:45:58 +00001837void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001838 // Remove the memory accesses from this statement together with all scalar
1839 // accesses that were caused by it. MemoryKind::Value READs have no access
1840 // instruction, hence would not be removed by this function. However, it is
1841 // only used for invariant LoadInst accesses, its arguments are always affine,
1842 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1843 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001844 auto Predicate = [&](MemoryAccess *Acc) {
1845 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1846 };
1847 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1848 MemAccs.end());
1849 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001850}
1851
Michael Kruse0446d812017-03-10 16:05:24 +00001852void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
1853 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1854 assert(MAIt != MemAccs.end());
1855 MemAccs.erase(MAIt);
1856
1857 auto It = InstructionToAccess.find(MA->getAccessInstruction());
1858 if (It != InstructionToAccess.end()) {
1859 It->second.remove(MA);
1860 if (It->second.empty())
1861 InstructionToAccess.erase(MA->getAccessInstruction());
1862 }
1863}
1864
Tobias Grosser75805372011-04-29 06:27:02 +00001865//===----------------------------------------------------------------------===//
1866/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001867
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001868void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001869 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1870 isl_set_free(Context);
1871 Context = NewContext;
1872}
1873
Tobias Grosserc80d6972016-09-02 06:33:33 +00001874/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001875struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001876 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001877 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001878
1879public:
1880 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001881 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001882
1883 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1884 ValueToValueMap &VMap) {
1885 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1886 return SSPR.visit(E);
1887 }
1888
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001889 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1890 auto *Start = visit(E->getStart());
1891 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1892 visit(E->getStepRecurrence(SE)),
1893 E->getLoop(), SCEV::FlagAnyWrap);
1894 return SE.getAddExpr(Start, AddRec);
1895 }
1896
1897 const SCEV *visitUnknown(const SCEVUnknown *E) {
1898 if (auto *NewValue = VMap.lookup(E->getValue()))
1899 return SE.getUnknown(NewValue);
1900 return E;
1901 }
1902};
1903
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001904const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001905 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001906}
1907
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001908void Scop::createParameterId(const SCEV *Parameter) {
1909 assert(Parameters.count(Parameter));
1910 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001911
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001912 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001913
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001914 if (UseInstructionNames) {
1915 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1916 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001917
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001918 // If this parameter references a specific Value and this value has a name
1919 // we use this name as it is likely to be unique and more useful than just
1920 // a number.
1921 if (Val->hasName())
1922 ParameterName = Val->getName();
1923 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1924 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1925 if (LoadOrigin->hasName()) {
1926 ParameterName += "_loaded_from_";
1927 ParameterName +=
1928 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1929 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001930 }
1931 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001932
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001933 ParameterName = getIslCompatibleName("", ParameterName, "");
1934 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001935
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001936 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1937 const_cast<void *>((const void *)Parameter));
1938 ParameterIds[Parameter] = Id;
1939}
1940
1941void Scop::addParams(const ParameterSetTy &NewParameters) {
1942 for (const SCEV *Parameter : NewParameters) {
1943 // Normalize the SCEV to get the representing element for an invariant load.
1944 Parameter = extractConstantFactor(Parameter, *SE).second;
1945 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1946
1947 if (Parameters.insert(Parameter))
1948 createParameterId(Parameter);
1949 }
1950}
1951
1952__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1953 // Normalize the SCEV to get the representing element for an invariant load.
1954 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1955 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001956}
Tobias Grosser75805372011-04-29 06:27:02 +00001957
Michael Krused56b90a2016-09-01 09:03:27 +00001958__isl_give isl_set *
1959Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001960 isl_set *DomainContext = isl_union_set_params(getDomains());
1961 return isl_set_intersect_params(C, DomainContext);
1962}
1963
Johannes Doerferte0b08072016-05-23 12:43:44 +00001964bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1965 return DT.dominates(BB, getEntry());
1966}
1967
Michael Kruse89b1f942017-03-17 13:56:53 +00001968void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1969 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001970 auto &F = getFunction();
Michael Kruse89b1f942017-03-17 13:56:53 +00001971 for (auto &Assumption : AC.assumptions()) {
1972 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1973 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001974 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001975
Michael Kruse89b1f942017-03-17 13:56:53 +00001976 bool InScop = contains(CI);
1977 if (!InScop && !isDominatedBy(DT, CI->getParent()))
1978 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001979
Michael Kruse89b1f942017-03-17 13:56:53 +00001980 auto *L = LI.getLoopFor(CI->getParent());
1981 auto *Val = CI->getArgOperand(0);
1982 ParameterSetTy DetectedParams;
1983 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
1984 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1985 CI->getDebugLoc(),
1986 "Non-affine user assumption ignored.");
1987 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00001988 }
Michael Kruse89b1f942017-03-17 13:56:53 +00001989
1990 // Collect all newly introduced parameters.
1991 ParameterSetTy NewParams;
1992 for (auto *Param : DetectedParams) {
1993 Param = extractConstantFactor(Param, *SE).second;
1994 Param = getRepresentingInvariantLoadSCEV(Param);
1995 if (Parameters.count(Param))
1996 continue;
1997 NewParams.insert(Param);
1998 }
1999
2000 SmallVector<isl_set *, 2> ConditionSets;
2001 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
2002 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
2003 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
2004 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
2005 isl_set_free(Dom);
2006
2007 if (!Valid)
2008 continue;
2009
2010 isl_set *AssumptionCtx = nullptr;
2011 if (InScop) {
2012 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2013 isl_set_free(ConditionSets[0]);
2014 } else {
2015 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2016 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2017 }
2018
2019 // Project out newly introduced parameters as they are not otherwise useful.
2020 if (!NewParams.empty()) {
2021 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2022 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2023 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2024 isl_id_free(Id);
2025
2026 if (!NewParams.count(Param))
2027 continue;
2028
2029 AssumptionCtx =
2030 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2031 }
2032 }
2033
2034 emitOptimizationRemarkAnalysis(
2035 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
2036 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
2037 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002038 }
2039}
2040
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002041void Scop::addUserContext() {
2042 if (UserContextStr.empty())
2043 return;
2044
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002045 isl_set *UserContext =
2046 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002047 isl_space *Space = getParamSpace();
2048 if (isl_space_dim(Space, isl_dim_param) !=
2049 isl_set_dim(UserContext, isl_dim_param)) {
2050 auto SpaceStr = isl_space_to_str(Space);
2051 errs() << "Error: the context provided in -polly-context has not the same "
2052 << "number of dimensions than the computed context. Due to this "
2053 << "mismatch, the -polly-context option is ignored. Please provide "
2054 << "the context in the parameter space: " << SpaceStr << ".\n";
2055 free(SpaceStr);
2056 isl_set_free(UserContext);
2057 isl_space_free(Space);
2058 return;
2059 }
2060
2061 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002062 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2063 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002064
2065 if (strcmp(NameContext, NameUserContext) != 0) {
2066 auto SpaceStr = isl_space_to_str(Space);
2067 errs() << "Error: the name of dimension " << i
2068 << " provided in -polly-context "
2069 << "is '" << NameUserContext << "', but the name in the computed "
2070 << "context is '" << NameContext
2071 << "'. Due to this name mismatch, "
2072 << "the -polly-context option is ignored. Please provide "
2073 << "the context in the parameter space: " << SpaceStr << ".\n";
2074 free(SpaceStr);
2075 isl_set_free(UserContext);
2076 isl_space_free(Space);
2077 return;
2078 }
2079
2080 UserContext =
2081 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2082 isl_space_get_dim_id(Space, isl_dim_param, i));
2083 }
2084
2085 Context = isl_set_intersect(Context, UserContext);
2086 isl_space_free(Space);
2087}
2088
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002089void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002090 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002091
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002092 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002093 for (LoadInst *LInst : RIL) {
2094 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2095
Johannes Doerfert96e54712016-02-07 17:30:13 +00002096 Type *Ty = LInst->getType();
2097 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002098 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002099 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002100 continue;
2101 }
2102
2103 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002104 InvariantEquivClasses.emplace_back(
2105 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002106 }
2107}
2108
Tobias Grosser6be480c2011-11-08 15:41:13 +00002109void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002110 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002111 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002112 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002113 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002114}
2115
Tobias Grosser18daaca2012-05-22 10:47:27 +00002116void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002117 unsigned PDim = 0;
2118 for (auto *Parameter : Parameters) {
2119 ConstantRange SRange = SE->getSignedRange(Parameter);
2120 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002121 }
2122}
2123
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002124void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002125 if (PollyIgnoreParamBounds)
2126 return;
2127
Tobias Grosser6be480c2011-11-08 15:41:13 +00002128 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002129 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002130
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002131 unsigned PDim = 0;
2132 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002133 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002134 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002135 }
2136
2137 // Align the parameters of all data structures to the model.
2138 Context = isl_set_align_params(Context, Space);
2139
Johannes Doerferta60ad842016-05-10 12:18:22 +00002140 // As all parameters are known add bounds to them.
2141 addParameterBounds();
2142
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002143 for (ScopStmt &Stmt : *this)
2144 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002145
2146 // Simplify the schedule according to the context too.
2147 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002148}
2149
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002150static __isl_give isl_set *
2151simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2152 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002153 // If we have modeled all blocks in the SCoP that have side effects we can
2154 // simplify the context with the constraints that are needed for anything to
2155 // be executed at all. However, if we have error blocks in the SCoP we already
2156 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002157 // domains, thus we cannot use the remaining domain to simplify the
2158 // assumptions.
2159 if (!S.hasErrorBlock()) {
2160 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2161 AssumptionContext =
2162 isl_set_gist_params(AssumptionContext, DomainParameters);
2163 }
2164
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002165 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2166 return AssumptionContext;
2167}
2168
2169void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002170 // The parameter constraints of the iteration domains give us a set of
2171 // constraints that need to hold for all cases where at least a single
2172 // statement iteration is executed in the whole scop. We now simplify the
2173 // assumed context under the assumption that such constraints hold and at
2174 // least a single statement iteration is executed. For cases where no
2175 // statement instances are executed, the assumptions we have taken about
2176 // the executed code do not matter and can be changed.
2177 //
2178 // WARNING: This only holds if the assumptions we have taken do not reduce
2179 // the set of statement instances that are executed. Otherwise we
2180 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002181 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002182 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002183 // performed. In such a case, modifying the run-time conditions and
2184 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002185 // to not be executed.
2186 //
2187 // Example:
2188 //
2189 // When delinearizing the following code:
2190 //
2191 // for (long i = 0; i < 100; i++)
2192 // for (long j = 0; j < m; j++)
2193 // A[i+p][j] = 1.0;
2194 //
2195 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002196 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002197 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002198 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002199 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002200}
2201
Tobias Grosserc80d6972016-09-02 06:33:33 +00002202/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002203static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002204 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2205 isl_pw_multi_aff *MinPMA, *MaxPMA;
2206 isl_pw_aff *LastDimAff;
2207 isl_aff *OneAff;
2208 unsigned Pos;
2209
Johannes Doerfert6296d952016-04-22 11:38:19 +00002210 Set = isl_set_remove_divs(Set);
2211
Tobias Grosser90411a92017-02-16 19:11:33 +00002212 if (isl_set_n_basic_set(Set) >= MaxDisjunctsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002213 isl_set_free(Set);
2214 return isl_stat_error;
2215 }
2216
Johannes Doerfert9143d672014-09-27 11:02:39 +00002217 // Restrict the number of parameters involved in the access as the lexmin/
2218 // lexmax computation will take too long if this number is high.
2219 //
2220 // Experiments with a simple test case using an i7 4800MQ:
2221 //
2222 // #Parameters involved | Time (in sec)
2223 // 6 | 0.01
2224 // 7 | 0.04
2225 // 8 | 0.12
2226 // 9 | 0.40
2227 // 10 | 1.54
2228 // 11 | 6.78
2229 // 12 | 30.38
2230 //
2231 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2232 unsigned InvolvedParams = 0;
2233 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2234 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2235 InvolvedParams++;
2236
2237 if (InvolvedParams > RunTimeChecksMaxParameters) {
2238 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002239 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002240 }
2241 }
2242
Johannes Doerfertb164c792014-09-18 11:17:17 +00002243 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2244 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2245
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002246 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2247 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2248
Johannes Doerfertb164c792014-09-18 11:17:17 +00002249 // Adjust the last dimension of the maximal access by one as we want to
2250 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2251 // we test during code generation might now point after the end of the
2252 // allocated array but we will never dereference it anyway.
2253 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2254 "Assumed at least one output dimension");
2255 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2256 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2257 OneAff = isl_aff_zero_on_domain(
2258 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2259 OneAff = isl_aff_add_constant_si(OneAff, 1);
2260 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2261 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2262
2263 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2264
2265 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002266 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002267}
2268
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002269static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2270 isl_set *Domain = MA->getStatement()->getDomain();
2271 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2272 return isl_set_reset_tuple_id(Domain);
2273}
2274
Tobias Grosserc80d6972016-09-02 06:33:33 +00002275/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002276static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002277 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002278
Tobias Grossere9522232017-01-16 15:49:04 +00002279 MinMaxAccesses.reserve(AliasGroup.size());
2280
2281 isl_union_set *Domains = S.getDomains();
2282 isl_union_map *Accesses = isl_union_map_empty(S.getParamSpace());
2283
2284 for (MemoryAccess *MA : AliasGroup)
2285 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2286
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002287 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2288 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002289 Locations = isl_union_set_coalesce(Locations);
2290 Locations = isl_union_set_detect_equalities(Locations);
Tobias Grosserff400872017-02-01 10:12:09 +00002291 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
2292 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002293 isl_union_set_free(Locations);
2294 return Valid;
2295}
2296
Tobias Grosserc80d6972016-09-02 06:33:33 +00002297/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002298///
2299///{
2300
Tobias Grosserc80d6972016-09-02 06:33:33 +00002301/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002302static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2303 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2304 : RN->getNodeAs<BasicBlock>();
2305}
2306
Tobias Grosserc80d6972016-09-02 06:33:33 +00002307/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002308static inline BasicBlock *
2309getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002310 if (RN->isSubRegion()) {
2311 assert(idx == 0);
2312 return RN->getNodeAs<Region>()->getExit();
2313 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002314 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002315}
2316
Tobias Grosserc80d6972016-09-02 06:33:33 +00002317/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002318static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002319 if (!RN->isSubRegion()) {
2320 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2321 Loop *L = LI.getLoopFor(BB);
2322
2323 // Unreachable statements are not considered to belong to a LLVM loop, as
2324 // they are not part of an actual loop in the control flow graph.
2325 // Nevertheless, we handle certain unreachable statements that are common
2326 // when modeling run-time bounds checks as being part of the loop to be
2327 // able to model them and to later eliminate the run-time bounds checks.
2328 //
2329 // Specifically, for basic blocks that terminate in an unreachable and
2330 // where the immeditate predecessor is part of a loop, we assume these
2331 // basic blocks belong to the loop the predecessor belongs to. This
2332 // allows us to model the following code.
2333 //
2334 // for (i = 0; i < N; i++) {
2335 // if (i > 1024)
2336 // abort(); <- this abort might be translated to an
2337 // unreachable
2338 //
2339 // A[i] = ...
2340 // }
2341 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2342 L = LI.getLoopFor(BB->getPrevNode());
2343 return L;
2344 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002345
2346 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2347 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2348 while (L && NonAffineSubRegion->contains(L))
2349 L = L->getParentLoop();
2350 return L;
2351}
2352
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002353/// Get the number of blocks in @p L.
2354///
2355/// The number of blocks in a loop are the number of basic blocks actually
2356/// belonging to the loop, as well as all single basic blocks that the loop
2357/// exits to and which terminate in an unreachable instruction. We do not
2358/// allow such basic blocks in the exit of a scop, hence they belong to the
2359/// scop and represent run-time conditions which we want to model and
2360/// subsequently speculate away.
2361///
2362/// @see getRegionNodeLoop for additional details.
2363long getNumBlocksInLoop(Loop *L) {
2364 long NumBlocks = L->getNumBlocks();
2365 SmallVector<llvm::BasicBlock *, 4> ExitBlocks;
2366 L->getExitBlocks(ExitBlocks);
2367
2368 for (auto ExitBlock : ExitBlocks) {
2369 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2370 NumBlocks++;
2371 }
2372 return NumBlocks;
2373}
2374
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002375static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2376 if (!RN->isSubRegion())
2377 return 1;
2378
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002379 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002380 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002381}
2382
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002383static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2384 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002385 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002386 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002387 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002388 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002389 return true;
2390 return false;
2391}
2392
Johannes Doerfert96425c22015-08-30 21:13:53 +00002393///}
2394
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002395static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2396 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002397 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002398 isl_id *DimId =
2399 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2400 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2401}
2402
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002403__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002404 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002405}
2406
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002407__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002408 auto DIt = DomainMap.find(BB);
2409 if (DIt != DomainMap.end())
2410 return isl_set_copy(DIt->getSecond());
2411
2412 auto &RI = *R.getRegionInfo();
2413 auto *BBR = RI.getRegionFor(BB);
2414 while (BBR->getEntry() == BB)
2415 BBR = BBR->getParent();
2416 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002417}
2418
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002419bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002420
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002421 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002422 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002423 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2424 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002425 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002426
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002427 while (LD-- >= 0) {
2428 S = addDomainDimId(S, LD + 1, L);
2429 L = L->getParentLoop();
2430 }
2431
Johannes Doerferta3519512016-04-23 13:02:23 +00002432 // Initialize the invalid domain.
2433 auto *EntryStmt = getStmtFor(EntryBB);
2434 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2435
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002436 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002437
Johannes Doerfert432658d2016-01-26 11:01:41 +00002438 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002439 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002440
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002441 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002442 return false;
2443
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002444 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002445 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002446
2447 // Error blocks and blocks dominated by them have been assumed to never be
2448 // executed. Representing them in the Scop does not add any value. In fact,
2449 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002450 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002451 // will cause problems when building up a ScopStmt for them.
2452 // Furthermore, basic blocks dominated by error blocks may reference
2453 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002454 // can themselves not be constructed properly. To this end we will replace
2455 // the domains of error blocks and those only reachable via error blocks
2456 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002457 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002458 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002459 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002460 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002461
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002462 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002463}
2464
Tobias Grosserc80d6972016-09-02 06:33:33 +00002465/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002466/// to be compatible to domains constructed for loop @p NewL.
2467///
2468/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2469/// edge from @p OldL to @p NewL.
2470static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2471 __isl_take isl_set *Dom,
2472 Loop *OldL, Loop *NewL) {
2473
2474 // If the loops are the same there is nothing to do.
2475 if (NewL == OldL)
2476 return Dom;
2477
2478 int OldDepth = S.getRelativeLoopDepth(OldL);
2479 int NewDepth = S.getRelativeLoopDepth(NewL);
2480 // If both loops are non-affine loops there is nothing to do.
2481 if (OldDepth == -1 && NewDepth == -1)
2482 return Dom;
2483
2484 // Distinguish three cases:
2485 // 1) The depth is the same but the loops are not.
2486 // => One loop was left one was entered.
2487 // 2) The depth increased from OldL to NewL.
2488 // => One loop was entered, none was left.
2489 // 3) The depth decreased from OldL to NewL.
2490 // => Loops were left were difference of the depths defines how many.
2491 if (OldDepth == NewDepth) {
2492 assert(OldL->getParentLoop() == NewL->getParentLoop());
2493 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2494 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2495 Dom = addDomainDimId(Dom, NewDepth, NewL);
2496 } else if (OldDepth < NewDepth) {
2497 assert(OldDepth + 1 == NewDepth);
2498 auto &R = S.getRegion();
2499 (void)R;
2500 assert(NewL->getParentLoop() == OldL ||
2501 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2502 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2503 Dom = addDomainDimId(Dom, NewDepth, NewL);
2504 } else {
2505 assert(OldDepth > NewDepth);
2506 int Diff = OldDepth - NewDepth;
2507 int NumDim = isl_set_n_dim(Dom);
2508 assert(NumDim >= Diff);
2509 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2510 }
2511
2512 return Dom;
2513}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002514
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002515bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2516 LoopInfo &LI) {
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002517 ReversePostOrderTraversal<Region *> RTraversal(R);
2518 for (auto *RN : RTraversal) {
2519
2520 // Recurse for affine subregions but go on for basic blocks and non-affine
2521 // subregions.
2522 if (RN->isSubRegion()) {
2523 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002524 if (!isNonAffineSubRegion(SubRegion)) {
2525 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002526 continue;
2527 }
2528 }
2529
2530 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2531 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002532 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002533 isl_set *&Domain = DomainMap[BB];
2534 assert(Domain && "Cannot propagate a nullptr");
2535
Johannes Doerferta3519512016-04-23 13:02:23 +00002536 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002537 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002538 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002539
Johannes Doerferta3519512016-04-23 13:02:23 +00002540 if (!IsInvalidBlock) {
2541 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002542 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002543 isl_set_free(InvalidDomain);
2544 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002545 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2546 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2547 AS_RESTRICTION);
2548 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002549 }
2550
Johannes Doerferta3519512016-04-23 13:02:23 +00002551 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002552 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002553 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002554 }
2555
Johannes Doerferta3519512016-04-23 13:02:23 +00002556 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002557 auto *TI = BB->getTerminator();
2558 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2559 for (unsigned u = 0; u < NumSuccs; u++) {
2560 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002561 auto *SuccStmt = getStmtFor(SuccBB);
2562
2563 // Skip successors outside the SCoP.
2564 if (!SuccStmt)
2565 continue;
2566
Johannes Doerferte4459a22016-04-25 13:34:50 +00002567 // Skip backedges.
2568 if (DT.dominates(SuccBB, BB))
2569 continue;
2570
Michael Kruse55454072017-03-15 22:16:43 +00002571 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta3519512016-04-23 13:02:23 +00002572 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2573 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2574 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2575 SuccInvalidDomain =
2576 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2577 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2578 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2579 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002580
Michael Krusebc150122016-05-02 12:25:18 +00002581 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002582 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002583 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002584 continue;
2585
Johannes Doerferta3519512016-04-23 13:02:23 +00002586 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002587 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002588 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002589 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002590
2591 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002592 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002593
2594 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002595}
2596
Johannes Doerfert642594a2016-04-04 07:57:39 +00002597void Scop::propagateDomainConstraintsToRegionExit(
2598 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002599 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002600
2601 // Check if the block @p BB is the entry of a region. If so we propagate it's
2602 // domain to the exit block of the region. Otherwise we are done.
2603 auto *RI = R.getRegionInfo();
2604 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2605 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002606 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002607 return;
2608
Johannes Doerfert642594a2016-04-04 07:57:39 +00002609 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002610 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002611 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002612 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002613 SmallVector<BasicBlock *, 4> LatchBBs;
2614 BBLoop->getLoopLatches(LatchBBs);
2615 for (auto *LatchBB : LatchBBs)
2616 if (BB != LatchBB && BBReg->contains(LatchBB))
2617 return;
2618 L = L->getParentLoop();
2619 }
2620
2621 auto *Domain = DomainMap[BB];
2622 assert(Domain && "Cannot propagate a nullptr");
2623
Michael Kruse55454072017-03-15 22:16:43 +00002624 auto *ExitStmt = getStmtFor(ExitBB);
2625 auto *ExitBBLoop = ExitStmt->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002626
2627 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2628 // adjust the domain before we can propagate it.
2629 auto *AdjustedDomain =
2630 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2631 auto *&ExitDomain = DomainMap[ExitBB];
2632
2633 // If the exit domain is not yet created we set it otherwise we "add" the
2634 // current domain.
2635 ExitDomain =
2636 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2637
Johannes Doerferta3519512016-04-23 13:02:23 +00002638 // Initialize the invalid domain.
Johannes Doerferta3519512016-04-23 13:02:23 +00002639 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2640
Johannes Doerfert642594a2016-04-04 07:57:39 +00002641 FinishedExitBlocks.insert(ExitBB);
2642}
2643
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002644bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2645 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002646 // To create the domain for each block in R we iterate over all blocks and
2647 // subregions in R and propagate the conditions under which the current region
2648 // element is executed. To this end we iterate in reverse post order over R as
2649 // it ensures that we first visit all predecessors of a region node (either a
2650 // basic block or a subregion) before we visit the region node itself.
2651 // Initially, only the domain for the SCoP region entry block is set and from
2652 // there we propagate the current domain to all successors, however we add the
2653 // condition that the successor is actually executed next.
2654 // As we are only interested in non-loop carried constraints here we can
2655 // simply skip loop back edges.
2656
Johannes Doerfert642594a2016-04-04 07:57:39 +00002657 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002658 ReversePostOrderTraversal<Region *> RTraversal(R);
2659 for (auto *RN : RTraversal) {
2660
2661 // Recurse for affine subregions but go on for basic blocks and non-affine
2662 // subregions.
2663 if (RN->isSubRegion()) {
2664 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002665 if (!isNonAffineSubRegion(SubRegion)) {
2666 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002667 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002668 continue;
2669 }
2670 }
2671
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002672 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002673 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002674
Johannes Doerfert96425c22015-08-30 21:13:53 +00002675 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002676 TerminatorInst *TI = BB->getTerminator();
2677
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002678 if (isa<UnreachableInst>(TI))
2679 continue;
2680
Johannes Doerfertf5673802015-10-01 23:48:18 +00002681 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002682 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002683 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002684 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002685
Johannes Doerfert642594a2016-04-04 07:57:39 +00002686 auto *BBLoop = getRegionNodeLoop(RN, LI);
2687 // Propagate the domain from BB directly to blocks that have a superset
2688 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002689 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002690
2691 // If all successors of BB have been set a domain through the propagation
2692 // above we do not need to build condition sets but can just skip this
2693 // block. However, it is important to note that this is a local property
2694 // with regards to the region @p R. To this end FinishedExitBlocks is a
2695 // local variable.
2696 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2697 return FinishedExitBlocks.count(SuccBB);
2698 };
2699 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2700 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002701
2702 // Build the condition sets for the successor nodes of the current region
2703 // node. If it is a non-affine subregion we will always execute the single
2704 // exit node, hence the single entry node domain is the condition set. For
2705 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002706 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002707 if (RN->isSubRegion())
2708 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002709 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2710 ConditionSets))
2711 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002712
2713 // Now iterate over the successors and set their initial domain based on
2714 // their condition set. We skip back edges here and have to be careful when
2715 // we leave a loop not to keep constraints over a dimension that doesn't
2716 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002717 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002718 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002719 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002720 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002721
Johannes Doerfert535de032016-04-19 14:49:05 +00002722 auto *SuccStmt = getStmtFor(SuccBB);
2723 // Skip blocks outside the region.
2724 if (!SuccStmt) {
2725 isl_set_free(CondSet);
2726 continue;
2727 }
2728
Johannes Doerfert642594a2016-04-04 07:57:39 +00002729 // If we propagate the domain of some block to "SuccBB" we do not have to
2730 // adjust the domain.
2731 if (FinishedExitBlocks.count(SuccBB)) {
2732 isl_set_free(CondSet);
2733 continue;
2734 }
2735
Johannes Doerfert96425c22015-08-30 21:13:53 +00002736 // Skip back edges.
2737 if (DT.dominates(SuccBB, BB)) {
2738 isl_set_free(CondSet);
2739 continue;
2740 }
2741
Michael Kruse55454072017-03-15 22:16:43 +00002742 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002743 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002744
2745 // Set the domain for the successor or merge it with an existing domain in
2746 // case there are multiple paths (without loop back edges) to the
2747 // successor block.
2748 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002749
Johannes Doerferta3519512016-04-23 13:02:23 +00002750 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002751 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002752 } else {
2753 // Initialize the invalid domain.
2754 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2755 SuccDomain = CondSet;
2756 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002757
Michael Krusebc150122016-05-02 12:25:18 +00002758 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002759 // In case this happens we will clean up and bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002760 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002761 continue;
2762
2763 invalidate(COMPLEXITY, DebugLoc());
2764 while (++u < ConditionSets.size())
2765 isl_set_free(ConditionSets[u]);
2766 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002767 }
2768 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002769
2770 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002771}
2772
Michael Krused56b90a2016-09-01 09:03:27 +00002773__isl_give isl_set *
2774Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2775 __isl_keep isl_set *Domain,
2776 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002777 // If @p BB is the ScopEntry we are done
2778 if (R.getEntry() == BB)
2779 return isl_set_universe(isl_set_get_space(Domain));
2780
Johannes Doerfert642594a2016-04-04 07:57:39 +00002781 // The region info of this function.
2782 auto &RI = *R.getRegionInfo();
2783
Michael Kruse55454072017-03-15 22:16:43 +00002784 auto *BBLoop = getStmtFor(BB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002785
2786 // A domain to collect all predecessor domains, thus all conditions under
2787 // which the block is executed. To this end we start with the empty domain.
2788 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2789
2790 // Set of regions of which the entry block domain has been propagated to BB.
2791 // all predecessors inside any of the regions can be skipped.
2792 SmallSet<Region *, 8> PropagatedRegions;
2793
2794 for (auto *PredBB : predecessors(BB)) {
2795 // Skip backedges.
2796 if (DT.dominates(BB, PredBB))
2797 continue;
2798
2799 // If the predecessor is in a region we used for propagation we can skip it.
2800 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2801 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2802 PredBBInRegion)) {
2803 continue;
2804 }
2805
2806 // Check if there is a valid region we can use for propagation, thus look
2807 // for a region that contains the predecessor and has @p BB as exit block.
2808 auto *PredR = RI.getRegionFor(PredBB);
2809 while (PredR->getExit() != BB && !PredR->contains(BB))
2810 PredR->getParent();
2811
2812 // If a valid region for propagation was found use the entry of that region
2813 // for propagation, otherwise the PredBB directly.
2814 if (PredR->getExit() == BB) {
2815 PredBB = PredR->getEntry();
2816 PropagatedRegions.insert(PredR);
2817 }
2818
Johannes Doerfert41cda152016-04-08 10:32:26 +00002819 auto *PredBBDom = getDomainConditions(PredBB);
Michael Kruse55454072017-03-15 22:16:43 +00002820 auto *PredBBLoop = getStmtFor(PredBB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002821 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2822
2823 PredDom = isl_set_union(PredDom, PredBBDom);
2824 }
2825
2826 return PredDom;
2827}
2828
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002829bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2830 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002831 // Iterate over the region R and propagate the domain constrains from the
2832 // predecessors to the current node. In contrast to the
2833 // buildDomainsWithBranchConstraints function, this one will pull the domain
2834 // information from the predecessors instead of pushing it to the successors.
2835 // Additionally, we assume the domains to be already present in the domain
2836 // map here. However, we iterate again in reverse post order so we know all
2837 // predecessors have been visited before a block or non-affine subregion is
2838 // visited.
2839
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002840 ReversePostOrderTraversal<Region *> RTraversal(R);
2841 for (auto *RN : RTraversal) {
2842
2843 // Recurse for affine subregions but go on for basic blocks and non-affine
2844 // subregions.
2845 if (RN->isSubRegion()) {
2846 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002847 if (!isNonAffineSubRegion(SubRegion)) {
2848 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002849 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002850 continue;
2851 }
2852 }
2853
2854 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002855 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002856 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002857
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002858 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002859 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002860 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002861 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002862
Johannes Doerfert642594a2016-04-04 07:57:39 +00002863 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002864 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002865 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2866 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002867 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002868
2869 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002870}
2871
Tobias Grosserc80d6972016-09-02 06:33:33 +00002872/// Create a map to map from a given iteration to a subsequent iteration.
2873///
2874/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2875/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002876/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002877///
2878/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002879static __isl_give isl_map *
2880createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2881 auto *MapSpace = isl_space_map_from_set(SetSpace);
2882 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00002883 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002884 if (u != Dim)
2885 NextIterationMap =
2886 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2887 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2888 C = isl_constraint_set_constant_si(C, 1);
2889 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2890 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2891 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2892 return NextIterationMap;
2893}
2894
Johannes Doerfert297c7202016-05-10 13:06:42 +00002895bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002896 int LoopDepth = getRelativeLoopDepth(L);
2897 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002898
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002899 BasicBlock *HeaderBB = L->getHeader();
2900 assert(DomainMap.count(HeaderBB));
2901 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002902
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002903 isl_map *NextIterationMap =
2904 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002905
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002906 isl_set *UnionBackedgeCondition =
2907 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002908
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002909 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2910 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002911
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002912 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002913
2914 // If the latch is only reachable via error statements we skip it.
2915 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2916 if (!LatchBBDom)
2917 continue;
2918
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002919 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002920
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002921 TerminatorInst *TI = LatchBB->getTerminator();
2922 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00002923 assert(BI && "Only branch instructions allowed in loop latches");
2924
2925 if (BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002926 BackedgeCondition = isl_set_copy(LatchBBDom);
2927 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002928 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002929 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002930 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
Michael Krusee1dc3872016-11-03 15:19:41 +00002931 ConditionSets)) {
2932 isl_map_free(NextIterationMap);
2933 isl_set_free(UnionBackedgeCondition);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002934 return false;
Michael Krusee1dc3872016-11-03 15:19:41 +00002935 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002936
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002937 // Free the non back edge condition set as we do not need it.
2938 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002939
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002940 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002941 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002942
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002943 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2944 assert(LatchLoopDepth >= LoopDepth);
2945 BackedgeCondition =
2946 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2947 LatchLoopDepth - LoopDepth);
2948 UnionBackedgeCondition =
2949 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002950 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002951
2952 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2953 for (int i = 0; i < LoopDepth; i++)
2954 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2955
2956 isl_set *UnionBackedgeConditionComplement =
2957 isl_set_complement(UnionBackedgeCondition);
2958 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2959 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2960 UnionBackedgeConditionComplement =
2961 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2962 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2963 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2964
2965 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2966 HeaderBBDom = Parts.second;
2967
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002968 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2969 // the bounded assumptions to the context as they are already implied by the
2970 // <nsw> tag.
2971 if (Affinator.hasNSWAddRecForLoop(L)) {
2972 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002973 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002974 }
2975
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002976 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002977 recordAssumption(INFINITELOOP, UnboundedCtx,
2978 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002979 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002980}
2981
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002982MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00002983 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002984
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00002985 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002986 if (!PointerBaseInst)
2987 return nullptr;
2988
2989 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2990 if (!BasePtrStmt)
2991 return nullptr;
2992
2993 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2994}
2995
2996bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2997 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00002998 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
2999 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
3000 bool Hoistable = NHCtx != nullptr;
3001 isl_set_free(NHCtx);
3002 return !Hoistable;
3003 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003004
Tobias Grosserbe372d52017-02-09 10:11:58 +00003005 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003006 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003007 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003008 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003009
3010 return false;
3011}
3012
Johannes Doerfert5210da52016-06-02 11:06:54 +00003013bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003014 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003015 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003016
Johannes Doerfertcd195322016-11-17 21:41:08 +00003017 if (buildAliasGroups(AA)) {
3018 // Aliasing assumptions do not go through addAssumption but we still want to
3019 // collect statistics so we do it here explicitly.
3020 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003021 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003022 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003023 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003024
3025 // If a problem occurs while building the alias groups we need to delete
3026 // this SCoP and pretend it wasn't valid in the first place. To this end
3027 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003028 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003029
3030 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3031 << " could not be created as the number of parameters involved "
3032 "is too high. The SCoP will be "
3033 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3034 "the maximal number of parameters but be advised that the "
3035 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003036 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003037}
3038
Tobias Grosser889830b2017-02-09 23:12:22 +00003039std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003040Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003041 AliasSetTracker AST(AA);
3042
3043 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003044 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003045 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003046
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003047 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003048 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3049 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003050
3051 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003052 if (StmtDomainEmpty)
3053 continue;
3054
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003055 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003056 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003057 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003058 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003059 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003060 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003061 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003062 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003063 else
3064 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003065 AST.add(Acc);
3066 }
3067 }
3068
Tobias Grosser9edcf072017-01-16 14:07:57 +00003069 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003070 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003071 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003072 continue;
3073 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003074 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003075 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003076 if (AG.size() < 2)
3077 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003078 AliasGroups.push_back(std::move(AG));
3079 }
3080
Tobias Grosser9edcf072017-01-16 14:07:57 +00003081 return std::make_tuple(AliasGroups, HasWriteAccess);
3082}
3083
Tobias Grossere39f9122017-01-16 14:08:00 +00003084void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003085 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3086 AliasGroupTy NewAG;
3087 AliasGroupTy &AG = AliasGroups[u];
3088 AliasGroupTy::iterator AGI = AG.begin();
3089 isl_set *AGDomain = getAccessDomain(*AGI);
3090 while (AGI != AG.end()) {
3091 MemoryAccess *MA = *AGI;
3092 isl_set *MADomain = getAccessDomain(MA);
3093 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3094 NewAG.push_back(MA);
3095 AGI = AG.erase(AGI);
3096 isl_set_free(MADomain);
3097 } else {
3098 AGDomain = isl_set_union(AGDomain, MADomain);
3099 AGI++;
3100 }
3101 }
3102 if (NewAG.size() > 1)
3103 AliasGroups.push_back(std::move(NewAG));
3104 isl_set_free(AGDomain);
3105 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003106}
3107
3108bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3109 // To create sound alias checks we perform the following steps:
3110 // o) We partition each group into read only and non read only accesses.
3111 // o) For each group with more than one base pointer we then compute minimal
3112 // and maximal accesses to each array of a group in read only and non
3113 // read only partitions separately.
3114 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003115 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003116
3117 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3118
3119 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003120
Johannes Doerfert13771732014-10-01 12:40:46 +00003121 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003122 bool Valid = buildAliasGroup(AG, HasWriteAccess);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003123 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003124 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003125 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003126
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003127 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003128}
3129
Tobias Grosser77f32572017-01-16 15:49:07 +00003130bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003131 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003132 AliasGroupTy ReadOnlyAccesses;
3133 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003134 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003135 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003136
3137 auto &F = getFunction();
3138
3139 if (AliasGroup.size() < 2)
3140 return true;
3141
3142 for (MemoryAccess *Access : AliasGroup) {
3143 emitOptimizationRemarkAnalysis(
3144 F.getContext(), DEBUG_TYPE, F,
3145 Access->getAccessInstruction()->getDebugLoc(),
3146 "Possibly aliasing pointer, use restrict keyword.");
3147
Tobias Grosser889830b2017-02-09 23:12:22 +00003148 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3149 if (HasWriteAccess.count(Array)) {
3150 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003151 ReadWriteAccesses.push_back(Access);
3152 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003153 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003154 ReadOnlyAccesses.push_back(Access);
3155 }
3156 }
3157
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003158 // If there are no read-only pointers, and less than two read-write pointers,
3159 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003160 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003161 return true;
3162
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003163 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003164 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003165 return true;
3166
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003167 // For non-affine accesses, no alias check can be generated as we cannot
3168 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003169 for (MemoryAccess *MA : AliasGroup) {
3170 if (!MA->isAffine()) {
3171 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3172 return false;
3173 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003174 }
3175
3176 // Ensure that for all memory accesses for which we generate alias checks,
3177 // their base pointers are available.
3178 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003179 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3180 addRequiredInvariantLoad(
3181 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3182 }
3183
3184 MinMaxAliasGroups.emplace_back();
3185 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3186 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3187 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3188
3189 bool Valid;
3190
3191 Valid =
3192 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3193
3194 if (!Valid)
3195 return false;
3196
3197 // Bail out if the number of values we need to compare is too large.
3198 // This is important as the number of comparisons grows quadratically with
3199 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003200 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003201 RunTimeChecksMaxArraysPerGroup)
3202 return false;
3203
3204 Valid =
3205 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3206
3207 if (!Valid)
3208 return false;
3209
3210 return true;
3211}
3212
Tobias Grosserc80d6972016-09-02 06:33:33 +00003213/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003214static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003215 // Start with the smallest loop containing the entry and expand that
3216 // loop until it contains all blocks in the region. If there is a loop
3217 // containing all blocks in the region check if it is itself contained
3218 // and if so take the parent loop as it will be the smallest containing
3219 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003220 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003221 while (L) {
3222 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003223 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003224 AllContained &= L->contains(BB);
3225 if (AllContained)
3226 break;
3227 L = L->getParentLoop();
3228 }
3229
Johannes Doerfertef744432016-05-23 12:42:38 +00003230 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003231}
3232
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003233Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003234 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003235 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003236 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003237 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3238 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3239 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3240 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003241 if (IslOnErrorAbort)
3242 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003243 buildContext();
3244}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003245
Tobias Grosserbedef002016-12-02 08:10:56 +00003246void Scop::foldSizeConstantsToRight() {
3247 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3248
3249 for (auto Array : arrays()) {
3250 if (Array->getNumberOfDimensions() <= 1)
3251 continue;
3252
3253 isl_space *Space = Array->getSpace();
3254
3255 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3256
3257 if (!isl_union_set_contains(Accessed, Space)) {
3258 isl_space_free(Space);
3259 continue;
3260 }
3261
3262 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3263
3264 isl_map *Transform =
3265 isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3266
3267 std::vector<int> Int;
3268
3269 int Dims = isl_set_dim(Elements, isl_dim_set);
3270 for (int i = 0; i < Dims; i++) {
3271 isl_set *DimOnly =
3272 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3273 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3274 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3275
3276 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3277
3278 if (i == Dims - 1) {
3279 Int.push_back(1);
3280 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3281 isl_basic_set_free(DimHull);
3282 continue;
3283 }
3284
3285 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3286 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3287 isl_val *Val = isl_aff_get_denominator_val(Diff);
3288 isl_aff_free(Diff);
3289
3290 int ValInt = 1;
3291
3292 if (isl_val_is_int(Val))
3293 ValInt = isl_val_get_num_si(Val);
3294 isl_val_free(Val);
3295
3296 Int.push_back(ValInt);
3297
3298 isl_constraint *C = isl_constraint_alloc_equality(
3299 isl_local_space_from_space(isl_map_get_space(Transform)));
3300 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3301 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3302 Transform = isl_map_add_constraint(Transform, C);
3303 isl_basic_set_free(DimHull);
3304 continue;
3305 }
3306
3307 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3308 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3309
3310 int ValInt = 1;
3311 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3312 ValInt = 0;
3313 }
3314
3315 Int.push_back(ValInt);
3316 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3317 isl_basic_set_free(DimHull);
3318 isl_basic_set_free(ZeroSet);
3319 }
3320
3321 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3322
3323 if (!isl_set_is_subset(Elements, MappedElements)) {
3324 isl_set_free(Elements);
3325 isl_set_free(MappedElements);
3326 isl_map_free(Transform);
3327 continue;
3328 }
3329
3330 isl_set_free(MappedElements);
3331
3332 bool CanFold = true;
3333
3334 if (Int[0] <= 1)
3335 CanFold = false;
3336
3337 unsigned NumDims = Array->getNumberOfDimensions();
3338 for (unsigned i = 1; i < NumDims - 1; i++)
3339 if (Int[0] != Int[i] && Int[i])
3340 CanFold = false;
3341
3342 if (!CanFold) {
3343 isl_set_free(Elements);
3344 isl_map_free(Transform);
3345 continue;
3346 }
3347
Tobias Grosserbedef002016-12-02 08:10:56 +00003348 for (auto &Access : AccessFunctions)
3349 if (Access->getScopArrayInfo() == Array)
3350 Access->setAccessRelation(isl_map_apply_range(
3351 Access->getAccessRelation(), isl_map_copy(Transform)));
3352
3353 isl_map_free(Transform);
3354
3355 std::vector<const SCEV *> Sizes;
3356 for (unsigned i = 0; i < NumDims; i++) {
3357 auto Size = Array->getDimensionSize(i);
3358
3359 if (i == NumDims - 1)
3360 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3361 Sizes.push_back(Size);
3362 }
3363
3364 Array->updateSizes(Sizes, false /* CheckConsistency */);
3365
3366 isl_set_free(Elements);
3367 }
3368 isl_union_set_free(Accessed);
3369 return;
3370}
3371
Tobias Grosser491b7992016-12-02 05:21:22 +00003372void Scop::finalizeAccesses() {
3373 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003374 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003375 foldAccessRelations();
3376 assumeNoOutOfBounds();
3377}
3378
Tobias Grosser75805372011-04-29 06:27:02 +00003379Scop::~Scop() {
3380 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003381 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003382 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003383 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003384
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003385 for (auto &It : ParameterIds)
3386 isl_id_free(It.second);
3387
Johannes Doerfert96425c22015-08-30 21:13:53 +00003388 for (auto It : DomainMap)
3389 isl_set_free(It.second);
3390
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003391 for (auto &AS : RecordedAssumptions)
3392 isl_set_free(AS.Set);
3393
Johannes Doerfertb164c792014-09-18 11:17:17 +00003394 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003395 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003396 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003397 isl_pw_multi_aff_free(MMA.first);
3398 isl_pw_multi_aff_free(MMA.second);
3399 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003400 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003401 isl_pw_multi_aff_free(MMA.first);
3402 isl_pw_multi_aff_free(MMA.second);
3403 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003404 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003405
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003406 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003407 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003408
3409 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003410 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003411 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003412 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003413 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003414 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003415 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003416}
3417
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003418void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003419 // Check all array accesses for each base pointer and find a (virtual) element
3420 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003421 for (ScopStmt &Stmt : *this)
3422 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003423 if (!Access->isArrayKind())
3424 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003425 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003426 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3427
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003428 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003429 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003430 unsigned DivisibleSize = Array->getElemSizeInBytes();
3431 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003432 while (!isDivisible(Subscript, DivisibleSize, *SE))
3433 DivisibleSize /= 2;
3434 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003435 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003436 }
3437
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003438 for (auto &Stmt : *this)
3439 for (auto &Access : Stmt)
3440 Access->updateDimensionality();
3441}
3442
Tobias Grosser491b7992016-12-02 05:21:22 +00003443void Scop::foldAccessRelations() {
3444 for (auto &Stmt : *this)
3445 for (auto &Access : Stmt)
3446 Access->foldAccessRelation();
3447}
3448
3449void Scop::assumeNoOutOfBounds() {
3450 for (auto &Stmt : *this)
3451 for (auto &Access : Stmt)
3452 Access->assumeNoOutOfBound();
3453}
3454
Michael Kruse977d38b2016-07-22 17:31:17 +00003455void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003456 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3457 ScopStmt &Stmt = *StmtIt;
3458
Johannes Doerfert26404542016-05-10 12:19:47 +00003459 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003460 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003461 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003462
Johannes Doerferteca9e892015-11-03 16:54:49 +00003463 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003464 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003465 bool OnlyRead = true;
3466 for (MemoryAccess *MA : Stmt) {
3467 if (MA->isRead())
3468 continue;
3469
3470 OnlyRead = false;
3471 break;
3472 }
3473
3474 RemoveStmt = OnlyRead;
3475 }
3476
Johannes Doerfert26404542016-05-10 12:19:47 +00003477 if (!RemoveStmt) {
3478 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003479 continue;
3480 }
3481
Johannes Doerfert26404542016-05-10 12:19:47 +00003482 // Remove the statement because it is unnecessary.
3483 if (Stmt.isRegionStmt())
3484 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3485 StmtMap.erase(BB);
3486 else
3487 StmtMap.erase(Stmt.getBasicBlock());
3488
3489 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003490 }
3491}
3492
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003493InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003494 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3495 if (!LInst)
3496 return nullptr;
3497
3498 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3499 LInst = cast<LoadInst>(Rep);
3500
Johannes Doerfert96e54712016-02-07 17:30:13 +00003501 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003502 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003503 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003504 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003505 continue;
3506
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003507 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003508 for (auto *MA : MAs)
3509 if (MA->getAccessInstruction() == Val)
3510 return &IAClass;
3511 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003512
3513 return nullptr;
3514}
3515
Tobias Grosserc80d6972016-09-02 06:33:33 +00003516/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003517static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003518 bool MAInvalidCtxIsEmpty,
3519 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003520 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3521 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3522 // TODO: We can provide more information for better but more expensive
3523 // results.
3524 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3525 LInst->getAlignment(), DL))
3526 return false;
3527
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003528 // If the location might be overwritten we do not hoist it unconditionally.
3529 //
3530 // TODO: This is probably to conservative.
3531 if (!NonHoistableCtxIsEmpty)
3532 return false;
3533
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003534 // If a dereferencable load is in a statement that is modeled precisely we can
3535 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003536 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003537 return true;
3538
3539 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003540 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003541 // statement domain.
3542 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3543 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3544 return false;
3545 return true;
3546}
3547
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003548void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003549
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003550 if (InvMAs.empty())
3551 return;
3552
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003553 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003554 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003555
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003556 // Get the context under which the statement is executed but remove the error
3557 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003558 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003559 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003560
Tobias Grosser90411a92017-02-16 19:11:33 +00003561 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003562 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003563 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3564 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003565 for (auto &InvMA : InvMAs)
3566 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003567 return;
3568 }
3569
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003570 // Project out all parameters that relate to loads in the statement. Otherwise
3571 // we could have cyclic dependences on the constraints under which the
3572 // hoisted loads are executed and we could not determine an order in which to
3573 // pre-load them. This happens because not only lower bounds are part of the
3574 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003575 for (auto &InvMA : InvMAs) {
3576 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003577 Instruction *AccInst = MA->getAccessInstruction();
3578 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003579 SetVector<Value *> Values;
3580 for (const SCEV *Parameter : Parameters) {
3581 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003582 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003583 if (!Values.count(AccInst))
3584 continue;
3585
3586 if (isl_id *ParamId = getIdForParam(Parameter)) {
3587 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003588 if (Dim >= 0)
3589 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003590 isl_id_free(ParamId);
3591 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003592 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003593 }
3594 }
3595
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003596 for (auto &InvMA : InvMAs) {
3597 auto *MA = InvMA.MA;
3598 auto *NHCtx = InvMA.NonHoistableCtx;
3599
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003600 // Check for another invariant access that accesses the same location as
3601 // MA and if found consolidate them. Otherwise create a new equivalence
3602 // class at the end of InvariantEquivClasses.
3603 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003604 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003605 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3606
Johannes Doerfert85676e32016-04-23 14:32:34 +00003607 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003608 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003609 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3610
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003611 isl_set *MACtx;
3612 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003613 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3614 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003615 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003616 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003617 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003618 } else {
3619 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003620 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003621 MACtx = isl_set_gist_params(MACtx, getContext());
3622 }
3623
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003624 bool Consolidated = false;
3625 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003626 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003627 continue;
3628
Johannes Doerfertdf880232016-03-03 12:26:58 +00003629 // If the pointer and the type is equal check if the access function wrt.
3630 // to the domain is equal too. It can happen that the domain fixes
3631 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003632 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003633 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003634 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003635 if (!MAs.empty()) {
3636 auto *LastMA = MAs.front();
3637
3638 auto *AR = isl_map_range(MA->getAccessRelation());
3639 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3640 bool SameAR = isl_set_is_equal(AR, LastAR);
3641 isl_set_free(AR);
3642 isl_set_free(LastAR);
3643
3644 if (!SameAR)
3645 continue;
3646 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003647
3648 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003649 MAs.push_front(MA);
3650
Johannes Doerfertdf880232016-03-03 12:26:58 +00003651 Consolidated = true;
3652
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003653 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003654 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003655 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003656 IAClassDomainCtx =
3657 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003658 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003659 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003660 break;
3661 }
3662
3663 if (Consolidated)
3664 continue;
3665
3666 // If we did not consolidate MA, thus did not find an equivalence class
3667 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003668 InvariantEquivClasses.emplace_back(
3669 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003670 }
3671
3672 isl_set_free(DomainCtx);
3673}
3674
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003675__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3676 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003677 // TODO: Loads that are not loop carried, hence are in a statement with
3678 // zero iterators, are by construction invariant, though we
3679 // currently "hoist" them anyway. This is necessary because we allow
3680 // them to be treated as parameters (e.g., in conditions) and our code
3681 // generation would otherwise use the old value.
3682
3683 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003684 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003685
Johannes Doerfertc9765462016-11-17 22:11:56 +00003686 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3687 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003688 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003689
3690 // Skip accesses that have an invariant base pointer which is defined but
3691 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3692 // returns a pointer that is used as a base address. However, as we want
3693 // to hoist indirect pointers, we allow the base pointer to be defined in
3694 // the region if it is also a memory access. Each ScopArrayInfo object
3695 // that has a base pointer origin has a base pointer that is loaded and
3696 // that it is invariant, thus it will be hoisted too. However, if there is
3697 // no base pointer origin we check that the base pointer is defined
3698 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003699 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003700 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003701 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003702
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003703 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003704 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003705
3706 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3707 Stmt.getNumIterators())) {
3708 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003709 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003710 }
3711
3712 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003713 isl_set *SafeToLoad;
3714
3715 auto &DL = getFunction().getParent()->getDataLayout();
3716 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
3717 DL)) {
3718 SafeToLoad =
3719 isl_set_universe(isl_space_range(isl_map_get_space(AccessRelation)));
3720 isl_map_free(AccessRelation);
3721 } else if (BB != LI->getParent()) {
3722 // Skip accesses in non-affine subregions as they might not be executed
3723 // under the same condition as the entry of the non-affine subregion.
3724 isl_map_free(AccessRelation);
3725 return nullptr;
3726 } else {
3727 SafeToLoad = isl_map_range(AccessRelation);
3728 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003729
3730 isl_union_map *Written = isl_union_map_intersect_range(
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003731 isl_union_map_copy(Writes), isl_union_set_from_set(SafeToLoad));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003732 auto *WrittenCtx = isl_union_map_params(Written);
3733 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003734
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003735 if (!IsWritten)
3736 return WrittenCtx;
3737
3738 WrittenCtx = isl_set_remove_divs(WrittenCtx);
Tobias Grosser90411a92017-02-16 19:11:33 +00003739 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctsInDomain;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003740 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3741 isl_set_free(WrittenCtx);
3742 return nullptr;
3743 }
3744
3745 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3746 AS_RESTRICTION);
3747 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003748}
3749
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003750void Scop::verifyInvariantLoads() {
3751 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003752 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003753 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003754 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003755 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003756 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3757 return;
3758 }
3759 }
3760}
3761
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003762void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003763 if (!PollyInvariantLoadHoisting)
3764 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003765
Tobias Grosser0865e7752016-02-29 07:29:42 +00003766 isl_union_map *Writes = getWrites();
3767 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003768 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003769
Tobias Grosser0865e7752016-02-29 07:29:42 +00003770 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003771 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3772 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003773
3774 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003775 for (auto InvMA : InvariantAccesses)
3776 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003777 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003778 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003779 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003780}
3781
Tobias Grosserf3adab42017-05-10 10:59:58 +00003782/// Find the canonical scop array info object for a set of invariant load
3783/// hoisted loads. The canonical array is the one that corresponds to the
3784/// first load in the list of accesses which is used as base pointer of a
3785/// scop array.
3786static const ScopArrayInfo *findCanonicalArray(Scop *S,
3787 MemoryAccessList &Accesses) {
3788 for (MemoryAccess *Access : Accesses) {
3789 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
3790 Access->getAccessInstruction(), MemoryKind::Array);
3791 if (CanonicalArray)
3792 return CanonicalArray;
3793 }
3794 return nullptr;
3795}
3796
3797/// Check if @p Array severs as base array in an invariant load.
3798static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
3799 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
3800 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
3801 if (Access2->getScopArrayInfo() == Array)
3802 return true;
3803 return false;
3804}
3805
3806/// Replace the base pointer arrays in all memory accesses referencing @p Old,
3807/// with a reference to @p New.
3808static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
3809 const ScopArrayInfo *New) {
3810 for (ScopStmt &Stmt : *S)
3811 for (MemoryAccess *Access : Stmt) {
3812 if (Access->getLatestScopArrayInfo() != Old)
3813 continue;
3814
3815 isl_id *Id = New->getBasePtrId();
3816 isl_map *Map = Access->getAccessRelation();
3817 Map = isl_map_set_tuple_id(Map, isl_dim_out, Id);
3818 Access->setAccessRelation(Map);
3819 }
3820}
3821
3822void Scop::canonicalizeDynamicBasePtrs() {
3823 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
3824 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
3825
3826 const ScopArrayInfo *CanonicalBasePtrSAI =
3827 findCanonicalArray(this, BasePtrAccesses);
3828
3829 if (!CanonicalBasePtrSAI)
3830 continue;
3831
3832 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
3833 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
3834 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
3835 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
3836 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
3837 continue;
3838
3839 // we currently do not canonicalize arrays where some accesses are
3840 // hoisted as invariant loads. If we would, we need to update the access
3841 // function of the invariant loads as well. However, as this is not a
3842 // very common situation, we leave this for now to avoid further
3843 // complexity increases.
3844 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
3845 continue;
3846
3847 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
3848 }
3849 }
3850}
3851
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003852const ScopArrayInfo *
3853Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
3854 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
3855 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00003856 assert((BasePtr || BaseName) &&
3857 "BasePtr and BaseName can not be nullptr at the same time.");
3858 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3859 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3860 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003861 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003862 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003863 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003864 DL, this, BaseName));
3865 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003866 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003867 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003868 // In case of mismatching array sizes, we bail out by setting the run-time
3869 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003870 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003871 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003872 }
Tobias Grosserab671442015-05-23 05:58:27 +00003873 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003874}
3875
Roman Gareevd7754a12016-07-30 09:25:51 +00003876const ScopArrayInfo *
3877Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3878 const std::vector<unsigned> &Sizes) {
3879 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3880 std::vector<const SCEV *> SCEVSizes;
3881
3882 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003883 if (size)
3884 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3885 else
3886 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003887
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003888 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3889 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00003890 return SAI;
3891}
3892
Tobias Grosserf3adab42017-05-10 10:59:58 +00003893const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
3894 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003895 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00003896 return SAI;
3897}
3898
3899const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
3900 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003901 assert(SAI && "No ScopArrayInfo available for this base pointer");
3902 return SAI;
3903}
3904
Tobias Grosser74394f02013-01-14 22:40:23 +00003905std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003906
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003907std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003908 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003909 return stringFromIslObj(AssumedContext);
3910}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003911
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003912std::string Scop::getInvalidContextStr() const {
3913 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003914}
Tobias Grosser75805372011-04-29 06:27:02 +00003915
3916std::string Scop::getNameStr() const {
3917 std::string ExitName, EntryName;
3918 raw_string_ostream ExitStr(ExitName);
3919 raw_string_ostream EntryStr(EntryName);
3920
Tobias Grosserf240b482014-01-09 10:42:15 +00003921 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003922 EntryStr.str();
3923
3924 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003925 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003926 ExitStr.str();
3927 } else
3928 ExitName = "FunctionExit";
3929
3930 return EntryName + "---" + ExitName;
3931}
3932
Tobias Grosser74394f02013-01-14 22:40:23 +00003933__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003934__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003935 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003936}
3937
Tobias Grossere86109f2013-10-29 21:05:49 +00003938__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003939 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003940 return isl_set_copy(AssumedContext);
3941}
3942
Michael Krusef3091bf2017-03-17 13:09:52 +00003943bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003944 if (PollyProcessUnprofitable)
3945 return true;
3946
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003947 if (isEmpty())
3948 return false;
3949
3950 unsigned OptimizableStmtsOrLoops = 0;
3951 for (auto &Stmt : *this) {
3952 if (Stmt.getNumIterators() == 0)
3953 continue;
3954
3955 bool ContainsArrayAccs = false;
3956 bool ContainsScalarAccs = false;
3957 for (auto *MA : Stmt) {
3958 if (MA->isRead())
3959 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00003960 ContainsArrayAccs |= MA->isLatestArrayKind();
3961 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003962 }
3963
Michael Krusef3091bf2017-03-17 13:09:52 +00003964 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003965 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3966 }
3967
3968 return OptimizableStmtsOrLoops > 1;
3969}
3970
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003971bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003972 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003973 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003974 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3975 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3976 isl_set_is_subset(PositiveContext, NegativeContext));
3977 isl_set_free(PositiveContext);
3978 if (!IsFeasible) {
3979 isl_set_free(NegativeContext);
3980 return false;
3981 }
3982
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003983 auto *DomainContext = isl_union_set_params(getDomains());
3984 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003985 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003986 isl_set_free(NegativeContext);
3987 isl_set_free(DomainContext);
3988
Johannes Doerfert43788c52015-08-20 05:58:56 +00003989 return IsFeasible;
3990}
3991
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003992static std::string toString(AssumptionKind Kind) {
3993 switch (Kind) {
3994 case ALIASING:
3995 return "No-aliasing";
3996 case INBOUNDS:
3997 return "Inbounds";
3998 case WRAPPING:
3999 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004000 case UNSIGNED:
4001 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004002 case COMPLEXITY:
4003 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004004 case PROFITABLE:
4005 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004006 case ERRORBLOCK:
4007 return "No-error";
4008 case INFINITELOOP:
4009 return "Finite loop";
4010 case INVARIANTLOAD:
4011 return "Invariant load";
4012 case DELINEARIZATION:
4013 return "Delinearization";
4014 }
4015 llvm_unreachable("Unknown AssumptionKind!");
4016}
4017
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004018bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4019 if (Sign == AS_ASSUMPTION) {
4020 if (isl_set_is_subset(Context, Set))
4021 return false;
4022
4023 if (isl_set_is_subset(AssumedContext, Set))
4024 return false;
4025 } else {
4026 if (isl_set_is_disjoint(Set, Context))
4027 return false;
4028
4029 if (isl_set_is_subset(Set, InvalidContext))
4030 return false;
4031 }
4032 return true;
4033}
4034
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004035bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
4036 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004037 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4038 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004039
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004040 // Do never emit trivial assumptions as they only clutter the output.
4041 if (!PollyRemarksMinimal) {
4042 isl_set *Univ = nullptr;
4043 if (Sign == AS_ASSUMPTION)
4044 Univ = isl_set_universe(isl_set_get_space(Set));
4045
4046 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4047 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4048 isl_set_free(Univ);
4049
4050 if (IsTrivial)
4051 return false;
4052 }
4053
Johannes Doerfertcd195322016-11-17 21:41:08 +00004054 switch (Kind) {
4055 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004056 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004057 break;
4058 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004059 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004060 break;
4061 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004062 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004063 break;
4064 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004065 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004066 break;
4067 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004068 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004069 break;
4070 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004071 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004072 break;
4073 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004074 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004075 break;
4076 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004077 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004078 break;
4079 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004080 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004081 break;
4082 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004083 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004084 break;
4085 }
4086
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004087 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004088 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4089 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004090 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004091 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004092}
4093
4094void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004095 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004096 // Simplify the assumptions/restrictions first.
4097 Set = isl_set_gist_params(Set, getContext());
4098
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004099 if (!trackAssumption(Kind, Set, Loc, Sign)) {
4100 isl_set_free(Set);
4101 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004102 }
4103
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004104 if (Sign == AS_ASSUMPTION) {
4105 AssumedContext = isl_set_intersect(AssumedContext, Set);
4106 AssumedContext = isl_set_coalesce(AssumedContext);
4107 } else {
4108 InvalidContext = isl_set_union(InvalidContext, Set);
4109 InvalidContext = isl_set_coalesce(InvalidContext);
4110 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004111}
4112
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004113void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004114 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004115 assert((isl_set_is_params(Set) || BB) &&
4116 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004117 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004118}
4119
4120void Scop::addRecordedAssumptions() {
4121 while (!RecordedAssumptions.empty()) {
4122 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004123
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004124 if (!AS.BB) {
4125 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
4126 continue;
4127 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004128
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004129 // If the domain was deleted the assumptions are void.
4130 isl_set *Dom = getDomainConditions(AS.BB);
4131 if (!Dom) {
4132 isl_set_free(AS.Set);
4133 continue;
4134 }
4135
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004136 // If a basic block was given use its domain to simplify the assumption.
4137 // In case of restrictions we know they only have to hold on the domain,
4138 // thus we can intersect them with the domain of the block. However, for
4139 // assumptions the domain has to imply them, thus:
4140 // _ _____
4141 // Dom => S <==> A v B <==> A - B
4142 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004143 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004144 // assumption.
4145 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004146 if (AS.Sign == AS_RESTRICTION)
4147 S = isl_set_params(isl_set_intersect(S, Dom));
4148 else /* (AS.Sign == AS_ASSUMPTION) */
4149 S = isl_set_params(isl_set_subtract(Dom, S));
4150
4151 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004152 }
4153}
4154
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004155void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004156 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004157}
4158
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004159__isl_give isl_set *Scop::getInvalidContext() const {
4160 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004161}
4162
Tobias Grosser75805372011-04-29 06:27:02 +00004163void Scop::printContext(raw_ostream &OS) const {
4164 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004165 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004166
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004167 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004168 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004169
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004170 OS.indent(4) << "Invalid Context:\n";
4171 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004172
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004173 unsigned Dim = 0;
4174 for (const SCEV *Parameter : Parameters)
4175 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004176}
4177
Johannes Doerfertb164c792014-09-18 11:17:17 +00004178void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004179 int noOfGroups = 0;
4180 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004181 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004182 noOfGroups += 1;
4183 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004184 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004185 }
4186
Tobias Grosserbb853c22015-07-25 12:31:03 +00004187 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004188 if (MinMaxAliasGroups.empty()) {
4189 OS.indent(8) << "n/a\n";
4190 return;
4191 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004192
Tobias Grosserbb853c22015-07-25 12:31:03 +00004193 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004194
4195 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004196 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004197 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004198 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004199 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4200 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004201 }
4202 OS << " ]]\n";
4203 }
4204
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004205 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004206 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004207 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004208 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004209 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4210 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004211 }
4212 OS << " ]]\n";
4213 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004214 }
4215}
4216
Tobias Grosser75805372011-04-29 06:27:02 +00004217void Scop::printStatements(raw_ostream &OS) const {
4218 OS << "Statements {\n";
4219
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004220 for (const ScopStmt &Stmt : *this)
4221 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00004222
4223 OS.indent(4) << "}\n";
4224}
4225
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004226void Scop::printArrayInfo(raw_ostream &OS) const {
4227 OS << "Arrays {\n";
4228
Tobias Grosserab671442015-05-23 05:58:27 +00004229 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004230 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004231
4232 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004233
4234 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4235
4236 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004237 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004238
4239 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004240}
4241
Tobias Grosser75805372011-04-29 06:27:02 +00004242void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004243 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004244 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004245 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004246 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004247 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004248 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004249 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004250 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004251 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004252 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004253 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4254 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004255 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004256 }
4257 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004258 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004259 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004260 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00004261 printStatements(OS.indent(4));
4262}
4263
4264void Scop::dump() const { print(dbgs()); }
4265
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004266isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004267
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004268__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4269 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004270 // First try to use the SCEVAffinator to generate a piecewise defined
4271 // affine function from @p E in the context of @p BB. If that tasks becomes to
4272 // complex the affinator might return a nullptr. In such a case we invalidate
4273 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004274 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004275 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004276 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004277 // TODO: We could use a heuristic and either use:
4278 // SCEVAffinator::takeNonNegativeAssumption
4279 // or
4280 // SCEVAffinator::interpretAsUnsigned
4281 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004282 if (NonNegative)
4283 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004284 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004285 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004286
4287 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
4288 invalidate(COMPLEXITY, DL);
4289 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004290}
4291
Tobias Grosser808cd692015-07-14 09:33:13 +00004292__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004293 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4294 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004295
Tobias Grosser808cd692015-07-14 09:33:13 +00004296 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004297 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004298
4299 return Domain;
4300}
4301
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004302__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4303 PWACtx PWAC = getPwAff(E, BB);
4304 isl_set_free(PWAC.second);
4305 return PWAC.first;
4306}
4307
Tobias Grossere5a35142015-11-12 14:07:09 +00004308__isl_give isl_union_map *
4309Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4310 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004311
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004312 for (ScopStmt &Stmt : *this) {
4313 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004314 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004315 continue;
4316
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004317 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004318 isl_map *AccessDomain = MA->getAccessRelation();
4319 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004320 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004321 }
4322 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004323 return isl_union_map_coalesce(Accesses);
4324}
4325
4326__isl_give isl_union_map *Scop::getMustWrites() {
4327 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004328}
4329
4330__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004331 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004332}
4333
Tobias Grosser37eb4222014-02-20 21:43:54 +00004334__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004335 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004336}
4337
4338__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004339 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004340}
4341
Tobias Grosser2ac23382015-11-12 14:07:13 +00004342__isl_give isl_union_map *Scop::getAccesses() {
4343 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4344}
4345
Roman Gareevb3224ad2016-09-14 06:26:09 +00004346// Check whether @p Node is an extension node.
4347//
4348// @return true if @p Node is an extension node.
4349isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4350 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4351 return isl_bool_error;
4352 else
4353 return isl_bool_true;
4354}
4355
4356bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4357 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4358 nullptr) == isl_stat_error;
4359}
4360
Tobias Grosser808cd692015-07-14 09:33:13 +00004361__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004362 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004363 if (containsExtensionNode(Tree)) {
4364 isl_schedule_free(Tree);
4365 return nullptr;
4366 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004367 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004368 isl_schedule_free(Tree);
4369 return S;
4370}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004371
Tobias Grosser808cd692015-07-14 09:33:13 +00004372__isl_give isl_schedule *Scop::getScheduleTree() const {
4373 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4374 getDomains());
4375}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004376
Tobias Grosser808cd692015-07-14 09:33:13 +00004377void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4378 auto *S = isl_schedule_from_domain(getDomains());
4379 S = isl_schedule_insert_partial_schedule(
4380 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4381 isl_schedule_free(Schedule);
4382 Schedule = S;
4383}
4384
4385void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4386 isl_schedule_free(Schedule);
4387 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004388}
4389
4390bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4391 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004392 for (ScopStmt &Stmt : *this) {
4393 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004394 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4395 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4396
4397 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4398 isl_union_set_free(StmtDomain);
4399 isl_union_set_free(NewStmtDomain);
4400 continue;
4401 }
4402
4403 Changed = true;
4404
4405 isl_union_set_free(StmtDomain);
4406 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4407
4408 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004409 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004410 isl_union_set_free(NewStmtDomain);
4411 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004412 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004413 }
4414 isl_union_set_free(Domain);
4415 return Changed;
4416}
4417
Tobias Grosser75805372011-04-29 06:27:02 +00004418ScalarEvolution *Scop::getSE() const { return SE; }
4419
Tobias Grosser808cd692015-07-14 09:33:13 +00004420struct MapToDimensionDataTy {
4421 int N;
4422 isl_union_pw_multi_aff *Res;
4423};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004424
Tobias Grosserc80d6972016-09-02 06:33:33 +00004425// Create a function that maps the elements of 'Set' to its N-th dimension and
4426// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004427//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004428// @param Set The input set.
4429// @param User->N The dimension to map to.
4430// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004431//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004432// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004433static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4434 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4435 int Dim;
4436 isl_space *Space;
4437 isl_pw_multi_aff *PMA;
4438
4439 Dim = isl_set_dim(Set, isl_dim_set);
4440 Space = isl_set_get_space(Set);
4441 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4442 Dim - Data->N);
4443 if (Data->N > 1)
4444 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4445 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4446
4447 isl_set_free(Set);
4448
4449 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004450}
4451
Tobias Grosserc80d6972016-09-02 06:33:33 +00004452// Create an isl_multi_union_aff that defines an identity mapping from the
4453// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004454//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004455// # Example:
4456//
4457// Domain: { A[i,j]; B[i,j,k] }
4458// N: 1
4459//
4460// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4461//
4462// @param USet A union set describing the elements for which to generate a
4463// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004464// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004465// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004466static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004467mapToDimension(__isl_take isl_union_set *USet, int N) {
4468 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004469 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004470 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004471
Tobias Grosser808cd692015-07-14 09:33:13 +00004472 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004473
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004474 auto *Space = isl_union_set_get_space(USet);
4475 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004476
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004477 Data = {N, PwAff};
4478
4479 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004480 (void)Res;
4481
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004482 assert(Res == isl_stat_ok);
4483
4484 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004485 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4486}
4487
Michael Kruse55454072017-03-15 22:16:43 +00004488void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004489 assert(BB && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004490 Stmts.emplace_back(*this, *BB, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004491 auto *Stmt = &Stmts.back();
4492 StmtMap[BB] = Stmt;
4493}
4494
Michael Kruse55454072017-03-15 22:16:43 +00004495void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004496 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004497 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004498 auto *Stmt = &Stmts.back();
4499 for (BasicBlock *BB : R->blocks())
Tobias Grosser808cd692015-07-14 09:33:13 +00004500 StmtMap[BB] = Stmt;
Tobias Grosser808cd692015-07-14 09:33:13 +00004501}
4502
Roman Gareevb3224ad2016-09-14 06:26:09 +00004503ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4504 __isl_take isl_map *TargetRel,
4505 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004506#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004507 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4508 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4509 assert(isl_set_is_subset(Domain, TargetDomain) &&
4510 "Target access not defined for complete statement domain");
4511 assert(isl_set_is_subset(Domain, SourceDomain) &&
4512 "Source access not defined for complete statement domain");
4513 isl_set_free(SourceDomain);
4514 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004515#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004516 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4517 CopyStmtsNum++;
4518 return &(Stmts.back());
4519}
4520
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004521void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004522 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004523 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004524 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004525 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4526 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004527}
4528
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004529/// To generate a schedule for the elements in a Region we traverse the Region
4530/// in reverse-post-order and add the contained RegionNodes in traversal order
4531/// to the schedule of the loop that is currently at the top of the LoopStack.
4532/// For loop-free codes, this results in a correct sequential ordering.
4533///
4534/// Example:
4535/// bb1(0)
4536/// / \.
4537/// bb2(1) bb3(2)
4538/// \ / \.
4539/// bb4(3) bb5(4)
4540/// \ /
4541/// bb6(5)
4542///
4543/// Including loops requires additional processing. Whenever a loop header is
4544/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4545/// from an empty schedule, we first process all RegionNodes that are within
4546/// this loop and complete the sequential schedule at this loop-level before
4547/// processing about any other nodes. To implement this
4548/// loop-nodes-first-processing, the reverse post-order traversal is
4549/// insufficient. Hence, we additionally check if the traversal yields
4550/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4551/// These region-nodes are then queue and only traverse after the all nodes
4552/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004553void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004554 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004555
4556 ReversePostOrderTraversal<Region *> RTraversal(R);
4557 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4558 std::deque<RegionNode *> DelayList;
4559 bool LastRNWaiting = false;
4560
4561 // Iterate over the region @p R in reverse post-order but queue
4562 // sub-regions/blocks iff they are not part of the last encountered but not
4563 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4564 // that we queued the last sub-region/block from the reverse post-order
4565 // iterator. If it is set we have to explore the next sub-region/block from
4566 // the iterator (if any) to guarantee progress. If it is not set we first try
4567 // the next queued sub-region/blocks.
4568 while (!WorkList.empty() || !DelayList.empty()) {
4569 RegionNode *RN;
4570
4571 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4572 RN = WorkList.front();
4573 WorkList.pop_front();
4574 LastRNWaiting = false;
4575 } else {
4576 RN = DelayList.front();
4577 DelayList.pop_front();
4578 }
4579
4580 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004581 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004582 L = OuterScopLoop;
4583
Tobias Grosser151ae322016-04-03 19:36:52 +00004584 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004585 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004586 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004587 LastRNWaiting = true;
4588 DelayList.push_back(RN);
4589 continue;
4590 }
4591 LoopStack.push_back({L, nullptr, 0});
4592 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004593 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004594 }
4595
4596 return;
4597}
4598
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004599void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004600
Tobias Grosser8362c262016-01-06 15:30:06 +00004601 if (RN->isSubRegion()) {
4602 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004603 if (!isNonAffineSubRegion(LocalRegion)) {
4604 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004605 return;
4606 }
4607 }
Michael Kruse046dde42015-08-10 13:01:57 +00004608
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004609 auto &LoopData = LoopStack.back();
4610 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004611
Michael Kruse6f7721f2016-02-24 22:08:19 +00004612 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004613 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4614 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004615 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004616 }
4617
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004618 // Check if we just processed the last node in this loop. If we did, finalize
4619 // the loop by:
4620 //
4621 // - adding new schedule dimensions
4622 // - folding the resulting schedule into the parent loop schedule
4623 // - dropping the loop schedule from the LoopStack.
4624 //
4625 // Then continue to check surrounding loops, which might also have been
4626 // completed by this node.
4627 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00004628 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004629 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004630 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004631
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004632 LoopStack.pop_back();
4633 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004634
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004635 if (Schedule) {
4636 auto *Domain = isl_schedule_get_domain(Schedule);
4637 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4638 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4639 NextLoopData.Schedule =
4640 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004641 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004642
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004643 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4644 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004645 }
Tobias Grosser75805372011-04-29 06:27:02 +00004646}
4647
Michael Kruse6f7721f2016-02-24 22:08:19 +00004648ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004649 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004650 if (StmtMapIt == StmtMap.end())
4651 return nullptr;
4652 return StmtMapIt->second;
4653}
4654
Michael Kruse6f7721f2016-02-24 22:08:19 +00004655ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4656 if (RN->isSubRegion())
4657 return getStmtFor(RN->getNodeAs<Region>());
4658 return getStmtFor(RN->getNodeAs<BasicBlock>());
4659}
4660
4661ScopStmt *Scop::getStmtFor(Region *R) const {
4662 ScopStmt *Stmt = getStmtFor(R->getEntry());
4663 assert(!Stmt || Stmt->getRegion() == R);
4664 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004665}
4666
Johannes Doerfert96425c22015-08-30 21:13:53 +00004667int Scop::getRelativeLoopDepth(const Loop *L) const {
4668 Loop *OuterLoop =
4669 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4670 if (!OuterLoop)
4671 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004672 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4673}
4674
Roman Gareevd7754a12016-07-30 09:25:51 +00004675ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4676 for (auto &SAI : arrays()) {
4677 if (SAI->getName() == BaseName)
4678 return SAI;
4679 }
4680 return nullptr;
4681}
4682
Johannes Doerfert99191c72016-05-31 09:41:04 +00004683//===----------------------------------------------------------------------===//
4684void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4685 AU.addRequired<LoopInfoWrapperPass>();
4686 AU.addRequired<RegionInfoPass>();
4687 AU.addRequired<DominatorTreeWrapperPass>();
4688 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4689 AU.addRequiredTransitive<ScopDetection>();
4690 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004691 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004692 AU.setPreservesAll();
4693}
4694
Tobias Grossercd01a362017-02-17 08:12:36 +00004695void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
4696 NumLoopsInScop += Stats.NumLoops;
4697 MaxNumLoopsInScop =
4698 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
4699
Tobias Grossercd01a362017-02-17 08:12:36 +00004700 if (Stats.MaxDepth == 1)
4701 NumScopsDepthOne++;
4702 else if (Stats.MaxDepth == 2)
4703 NumScopsDepthTwo++;
4704 else if (Stats.MaxDepth == 3)
4705 NumScopsDepthThree++;
4706 else if (Stats.MaxDepth == 4)
4707 NumScopsDepthFour++;
4708 else if (Stats.MaxDepth == 5)
4709 NumScopsDepthFive++;
4710 else
4711 NumScopsDepthLarger++;
4712}
4713
Johannes Doerfert99191c72016-05-31 09:41:04 +00004714bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4715 auto &SD = getAnalysis<ScopDetection>();
4716
4717 if (!SD.isMaxRegionInScop(*R))
4718 return false;
4719
4720 Function *F = R->getEntry()->getParent();
4721 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4722 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4723 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4724 auto const &DL = F->getParent()->getDataLayout();
4725 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004726 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004727
Michael Kruse89b1f942017-03-17 13:56:53 +00004728 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004729 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00004730
4731 if (S) {
4732 ScopDetection::LoopStats Stats =
4733 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
4734 updateLoopCountStatistic(Stats);
4735 }
4736
Tobias Grosser75805372011-04-29 06:27:02 +00004737 return false;
4738}
4739
Johannes Doerfert99191c72016-05-31 09:41:04 +00004740void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004741 if (S)
4742 S->print(OS);
4743 else
4744 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004745}
Tobias Grosser75805372011-04-29 06:27:02 +00004746
Johannes Doerfert99191c72016-05-31 09:41:04 +00004747char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004748
Johannes Doerfert99191c72016-05-31 09:41:04 +00004749Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4750
4751INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004752 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004753 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004754INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00004755INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004756INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004757INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004758INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004759INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004760INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004761INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004762 "Polly - Create polyhedral description of Scops", false,
4763 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004764
4765//===----------------------------------------------------------------------===//
4766void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4767 AU.addRequired<LoopInfoWrapperPass>();
4768 AU.addRequired<RegionInfoPass>();
4769 AU.addRequired<DominatorTreeWrapperPass>();
4770 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4771 AU.addRequiredTransitive<ScopDetection>();
4772 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004773 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004774 AU.setPreservesAll();
4775}
4776
4777bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4778 auto &SD = getAnalysis<ScopDetection>();
4779
4780 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4781 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4782 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4783 auto const &DL = F.getParent()->getDataLayout();
4784 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004785 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004786
4787 /// Create polyhedral descripton of scops for all the valid regions of a
4788 /// function.
4789 for (auto &It : SD) {
4790 Region *R = const_cast<Region *>(It);
4791 if (!SD.isMaxRegionInScop(*R))
4792 continue;
4793
Michael Kruse89b1f942017-03-17 13:56:53 +00004794 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004795 std::unique_ptr<Scop> S = SB.getScop();
4796 if (!S)
4797 continue;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004798 bool Inserted =
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004799 RegionToScopMap.insert(std::make_pair(R, std::move(S))).second;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004800 assert(Inserted && "Building Scop for the same region twice!");
4801 (void)Inserted;
4802 }
4803 return false;
4804}
4805
4806void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4807 for (auto &It : RegionToScopMap) {
4808 if (It.second)
4809 It.second->print(OS);
4810 else
4811 OS << "Invalid Scop!\n";
4812 }
4813}
4814
4815char ScopInfoWrapperPass::ID = 0;
4816
4817Pass *polly::createScopInfoWrapperPassPass() {
4818 return new ScopInfoWrapperPass();
4819}
4820
4821INITIALIZE_PASS_BEGIN(
4822 ScopInfoWrapperPass, "polly-function-scops",
4823 "Polly - Create polyhedral description of all Scops of a function", false,
4824 false);
4825INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00004826INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004827INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4828INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4829INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4830INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4831INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4832INITIALIZE_PASS_END(
4833 ScopInfoWrapperPass, "polly-function-scops",
4834 "Polly - Create polyhedral description of all Scops of a function", false,
4835 false)