blob: 4c640997410e997070b71998f530dabae73a0c82 [file] [log] [blame]
Michael Kruse2133cb92016-06-28 01:37:20 +00001//===--------- ScopInfo.cpp ----------------------------------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser5624d3c2015-12-21 12:38:56 +000020#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000021#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000022#include "polly/Options.h"
Michael Kruse73fa33b2016-06-28 01:37:28 +000023#include "polly/ScopBuilder.h"
Tobias Grosser75805372011-04-29 06:27:02 +000024#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000025#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000026#include "polly/Support/ScopHelper.h"
Tobias Grosser9737c7b2015-11-22 11:06:51 +000027#include "llvm/ADT/DepthFirstIterator.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000028#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000029#include "llvm/ADT/PostOrderIterator.h"
30#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000031#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000032#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000033#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000034#include "llvm/Analysis/AliasAnalysis.h"
Michael Kruse89b1f942017-03-17 13:56:53 +000035#include "llvm/Analysis/AssumptionCache.h"
Johannes Doerfert1dc12af2016-04-23 12:59:18 +000036#include "llvm/Analysis/Loads.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000037#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000038#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000039#include "llvm/Analysis/RegionIterator.h"
40#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000041#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000042#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000043#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000045#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000047#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000048#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000049#include "isl/schedule.h"
50#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000051#include "isl/set.h"
52#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000053#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000054#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000055#include <sstream>
56#include <string>
57#include <vector>
58
59using namespace llvm;
60using namespace polly;
61
Chandler Carruth95fef942014-04-22 03:30:19 +000062#define DEBUG_TYPE "polly-scops"
63
Johannes Doerfert81aa6e82016-11-18 14:37:08 +000064STATISTIC(AssumptionsAliasing, "Number of aliasing assumptions taken.");
65STATISTIC(AssumptionsInbounds, "Number of inbounds assumptions taken.");
66STATISTIC(AssumptionsWrapping, "Number of wrapping assumptions taken.");
67STATISTIC(AssumptionsUnsigned, "Number of unsigned assumptions taken.");
68STATISTIC(AssumptionsComplexity, "Number of too complex SCoPs.");
69STATISTIC(AssumptionsUnprofitable, "Number of unprofitable SCoPs.");
70STATISTIC(AssumptionsErrorBlock, "Number of error block assumptions taken.");
71STATISTIC(AssumptionsInfiniteLoop, "Number of bounded loop assumptions taken.");
72STATISTIC(AssumptionsInvariantLoad,
Johannes Doerfertcd195322016-11-17 21:41:08 +000073 "Number of invariant loads assumptions taken.");
Johannes Doerfert81aa6e82016-11-18 14:37:08 +000074STATISTIC(AssumptionsDelinearization,
Johannes Doerfertcd195322016-11-17 21:41:08 +000075 "Number of delinearization assumptions taken.");
76
Tobias Grossercd01a362017-02-17 08:12:36 +000077STATISTIC(NumLoopsInScop, "Number of loops in scops");
78STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
79STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
80STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
81STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
82STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
83STATISTIC(NumScopsDepthLarger,
84 "Number of scops with maximal loop depth 6 and larger");
85STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
86
Tobias Grosser75dc40c2015-12-20 13:31:48 +000087// The maximal number of basic sets we allow during domain construction to
88// be created. More complex scops will result in very high compile time and
89// are also unlikely to result in good code
Tobias Grosser90411a92017-02-16 19:11:33 +000090static int const MaxDisjunctsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +000091
Tobias Grosserc8a82762017-02-16 19:11:25 +000092// The number of disjunct in the context after which we stop to add more
93// disjuncts. This parameter is there to avoid exponential growth in the
94// number of disjunct when adding non-convex sets to the context.
95static int const MaxDisjunctsInContext = 4;
96
Tobias Grosser97715842017-05-19 04:01:52 +000097static cl::opt<int>
98 OptComputeOut("polly-analysis-computeout",
99 cl::desc("Bound the scop analysis by a maximal amount of "
100 "computational steps (0 means no bound)"),
Tobias Grosserc8d13f52017-05-24 21:24:04 +0000101 cl::Hidden, cl::init(600000), cl::ZeroOrMore,
Tobias Grosser97715842017-05-19 04:01:52 +0000102 cl::cat(PollyCategory));
Tobias Grosser45e9fd12017-05-19 03:45:00 +0000103
Johannes Doerfert2f705842016-04-12 16:09:44 +0000104static cl::opt<bool> PollyRemarksMinimal(
105 "polly-remarks-minimal",
106 cl::desc("Do not emit remarks about assumptions that are known"),
107 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
108
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +0000109// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000110// operations can overflow easily. Additive reductions and bit operations
111// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +0000112static cl::opt<bool> DisableMultiplicativeReductions(
113 "polly-disable-multiplicative-reductions",
114 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
115 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000116
Johannes Doerfert9143d672014-09-27 11:02:39 +0000117static cl::opt<unsigned> RunTimeChecksMaxParameters(
118 "polly-rtc-max-parameters",
119 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
120 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
121
Tobias Grosser71500722015-03-28 15:11:14 +0000122static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
123 "polly-rtc-max-arrays-per-group",
124 cl::desc("The maximal number of arrays to compare in each alias group."),
125 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000126
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000127static cl::opt<std::string> UserContextStr(
128 "polly-context", cl::value_desc("isl parameter set"),
129 cl::desc("Provide additional constraints on the context parameters"),
130 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000131
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000132static cl::opt<bool> DetectReductions("polly-detect-reductions",
133 cl::desc("Detect and exploit reductions"),
134 cl::Hidden, cl::ZeroOrMore,
135 cl::init(true), cl::cat(PollyCategory));
136
Tobias Grosser2937b592016-04-29 11:43:20 +0000137static cl::opt<bool>
138 IslOnErrorAbort("polly-on-isl-error-abort",
139 cl::desc("Abort if an isl error is encountered"),
140 cl::init(true), cl::cat(PollyCategory));
141
Tobias Grosserd7c49752017-02-28 09:45:54 +0000142static cl::opt<bool> PollyPreciseInbounds(
143 "polly-precise-inbounds",
144 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
145 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
146
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000147static cl::opt<bool>
148 PollyIgnoreInbounds("polly-ignore-inbounds",
149 cl::desc("Do not take inbounds assumptions at all"),
150 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
151
Tobias Grosser5842dee2017-03-17 13:00:53 +0000152static cl::opt<bool> PollyIgnoreParamBounds(
153 "polly-ignore-parameter-bounds",
154 cl::desc(
155 "Do not add parameter bounds and do no gist simplify sets accordingly"),
156 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
157
Tobias Grosserc2f15102017-03-01 21:11:27 +0000158static cl::opt<bool> PollyPreciseFoldAccesses(
159 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000160 cl::desc("Fold memory accesses to model more possible delinearizations "
161 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000162 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000163
Michael Kruse5ae08c02017-05-06 14:03:58 +0000164bool polly::UseInstructionNames;
165static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000166 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000167 cl::desc("Use LLVM-IR names when deriving statement names"),
168 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
169 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000170
Michael Kruse7bf39442015-09-10 12:46:52 +0000171//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000172
Michael Kruse046dde42015-08-10 13:01:57 +0000173// Create a sequence of two schedules. Either argument may be null and is
174// interpreted as the empty schedule. Can also return null if both schedules are
175// empty.
176static __isl_give isl_schedule *
177combineInSequence(__isl_take isl_schedule *Prev,
178 __isl_take isl_schedule *Succ) {
179 if (!Prev)
180 return Succ;
181 if (!Succ)
182 return Prev;
183
184 return isl_schedule_sequence(Prev, Succ);
185}
186
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000187static isl::set addRangeBoundsToSet(isl::set S, const ConstantRange &Range,
188 int dim, isl::dim type) {
189 isl::val V;
190 isl::ctx Ctx = S.get_ctx();
Johannes Doerferte7044942015-02-24 11:58:30 +0000191
Tobias Grosser3281f602017-02-16 18:39:14 +0000192 // The upper and lower bound for a parameter value is derived either from
193 // the data type of the parameter or from the - possibly more restrictive -
194 // range metadata.
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000195 V = valFromAPInt(Ctx.get(), Range.getSignedMin(), true);
196 S = S.lower_bound_val(type, dim, V);
197 V = valFromAPInt(Ctx.get(), Range.getSignedMax(), true);
198 S = S.upper_bound_val(type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000199
Tobias Grosser3281f602017-02-16 18:39:14 +0000200 if (Range.isFullSet())
201 return S;
202
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000203 if (isl_set_n_basic_set(S.get()) > MaxDisjunctsInContext)
Tobias Grosserc8a82762017-02-16 19:11:25 +0000204 return S;
205
Tobias Grosser3281f602017-02-16 18:39:14 +0000206 // In case of signed wrapping, we can refine the set of valid values by
207 // excluding the part not covered by the wrapping range.
208 if (Range.isSignWrappedSet()) {
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000209 V = valFromAPInt(Ctx.get(), Range.getLower(), true);
210 isl::set SLB = S.lower_bound_val(type, dim, V);
Tobias Grosser3281f602017-02-16 18:39:14 +0000211
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000212 V = valFromAPInt(Ctx.get(), Range.getUpper(), true);
213 V = V.sub_ui(1);
214 isl::set SUB = S.upper_bound_val(type, dim, V);
215 S = SLB.unite(SUB);
Tobias Grosser3281f602017-02-16 18:39:14 +0000216 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000217
Tobias Grosser3281f602017-02-16 18:39:14 +0000218 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000219}
220
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000221static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
222 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
223 if (!BasePtrLI)
224 return nullptr;
225
Johannes Doerfert952b5302016-05-23 12:40:48 +0000226 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000227 return nullptr;
228
229 ScalarEvolution &SE = *S->getSE();
230
231 auto *OriginBaseSCEV =
232 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
233 if (!OriginBaseSCEV)
234 return nullptr;
235
236 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
237 if (!OriginBaseSCEVUnknown)
238 return nullptr;
239
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000240 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000241 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000242}
243
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000244ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000245 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000246 const DataLayout &DL, Scop *S,
247 const char *BaseName)
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000248 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S),
249 FAD(nullptr) {
Tobias Grosser92245222015-07-28 14:53:44 +0000250 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000251 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000252 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
253 Kind == MemoryKind::PHI ? "__phi" : "",
254 UseInstructionNames);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000255 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000256
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000257 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000258
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000259 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000260 BasePtrOriginSAI = nullptr;
261 return;
262 }
263
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000264 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
265 if (BasePtrOriginSAI)
266 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000267}
268
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000269__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000270 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000271 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
272 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
273 return Space;
274}
275
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000276bool ScopArrayInfo::isReadOnly() {
Tobias Grosser2ade9862017-05-23 06:41:04 +0000277 isl::union_set WriteSet = give(S.getWrites()).range();
278 isl::space Space = give(getSpace());
279 WriteSet = WriteSet.extract_set(Space);
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000280
Tobias Grosser2ade9862017-05-23 06:41:04 +0000281 return bool(WriteSet.is_empty());
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000282}
283
Tobias Grosserf3adab42017-05-10 10:59:58 +0000284bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
285 if (Array->getElementType() != getElementType())
286 return false;
287
288 if (Array->getNumberOfDimensions() != getNumberOfDimensions())
289 return false;
290
291 for (unsigned i = 0; i < getNumberOfDimensions(); i++)
292 if (Array->getDimensionSize(i) != getDimensionSize(i))
293 return false;
294
295 return true;
296}
297
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000298void ScopArrayInfo::updateElementType(Type *NewElementType) {
299 if (NewElementType == ElementType)
300 return;
301
Tobias Grosserd840fc72016-02-04 13:18:42 +0000302 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
303 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
304
Johannes Doerferta7920982016-02-25 14:08:48 +0000305 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000306 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000307
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000308 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
309 ElementType = NewElementType;
310 } else {
311 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
312 ElementType = IntegerType::get(ElementType->getContext(), GCD);
313 }
314}
315
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000316/// Make the ScopArrayInfo model a Fortran Array
317void ScopArrayInfo::applyAndSetFAD(Value *FAD) {
318 assert(FAD && "got invalid Fortran array descriptor");
319 if (this->FAD) {
320 assert(this->FAD == FAD &&
321 "receiving different array descriptors for same array");
322 return;
323 }
324
325 assert(DimensionSizesPw.size() > 0 && !DimensionSizesPw[0]);
326 assert(!this->FAD);
327 this->FAD = FAD;
328
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000329 isl::space Space(S.getIslCtx(), 1, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000330
331 std::string param_name = getName();
332 param_name += "_fortranarr_size";
333 // TODO: see if we need to add `this` as the id user pointer
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000334 isl::id IdPwAff = isl::id::alloc(S.getIslCtx(), param_name.c_str(), nullptr);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000335
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000336 Space = Space.set_dim_id(isl::dim::param, 0, IdPwAff);
337 isl::pw_aff PwAff =
338 isl::aff::var_on_domain(isl::local_space(Space), isl::dim::param, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000339
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000340 DimensionSizesPw[0] = PwAff.release();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000341}
342
Tobias Grosserbedef002016-12-02 08:10:56 +0000343bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
344 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000345 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
346 int ExtraDimsNew = NewSizes.size() - SharedDims;
347 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000348
Tobias Grosserbedef002016-12-02 08:10:56 +0000349 if (CheckConsistency) {
350 for (int i = 0; i < SharedDims; i++) {
351 auto *NewSize = NewSizes[i + ExtraDimsNew];
352 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
353 if (NewSize && KnownSize && NewSize != KnownSize)
354 return false;
355 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000356
Tobias Grosserbedef002016-12-02 08:10:56 +0000357 if (DimensionSizes.size() >= NewSizes.size())
358 return true;
359 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000360
361 DimensionSizes.clear();
362 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
363 NewSizes.end());
364 for (isl_pw_aff *Size : DimensionSizesPw)
365 isl_pw_aff_free(Size);
366 DimensionSizesPw.clear();
367 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000368 if (!Expr) {
369 DimensionSizesPw.push_back(nullptr);
370 continue;
371 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000372 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000373 DimensionSizesPw.push_back(Size);
374 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000375 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000376}
377
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000378ScopArrayInfo::~ScopArrayInfo() {
379 isl_id_free(Id);
380 for (isl_pw_aff *Size : DimensionSizesPw)
381 isl_pw_aff_free(Size);
382}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000383
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000384std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
385
386int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000387 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000388}
389
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000390__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
391 return isl_id_copy(Id);
392}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000393
394void ScopArrayInfo::dump() const { print(errs()); }
395
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000396void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000397 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000398 unsigned u = 0;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000399 // If this is a Fortran array, then we can print the outermost dimension
400 // as a isl_pw_aff even though there is no SCEV information.
401 bool IsOutermostSizeKnown = SizeAsPwAff && FAD;
402
403 if (!IsOutermostSizeKnown && getNumberOfDimensions() > 0 &&
404 !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000405 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000406 u++;
407 }
408 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000409 OS << "[";
410
Tobias Grosser26253842015-11-10 14:24:21 +0000411 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000412 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000413 OS << " " << Size << " ";
414 isl_pw_aff_free(Size);
415 } else {
416 OS << *getDimensionSize(u);
417 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000418
419 OS << "]";
420 }
421
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000422 OS << ";";
423
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000424 if (BasePtrOriginSAI)
425 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
426
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000427 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000428}
429
430const ScopArrayInfo *
431ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
432 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
433 assert(Id && "Output dimension didn't have an ID");
434 return getFromId(Id);
435}
436
Michael Krused56b90a2016-09-01 09:03:27 +0000437const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000438 void *User = isl_id_get_user(Id);
439 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
440 isl_id_free(Id);
441 return SAI;
442}
443
Michael Kruse3b425ff2016-04-11 14:34:08 +0000444void MemoryAccess::wrapConstantDimensions() {
445 auto *SAI = getScopArrayInfo();
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000446 isl::space ArraySpace = give(SAI->getSpace());
447 isl::ctx Ctx = ArraySpace.get_ctx();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000448 unsigned DimsArray = SAI->getNumberOfDimensions();
449
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000450 isl::multi_aff DivModAff = isl::multi_aff::identity(
451 ArraySpace.map_from_domain_and_range(ArraySpace));
452 isl::local_space LArraySpace = isl::local_space(ArraySpace);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000453
454 // Begin with last dimension, to iteratively carry into higher dimensions.
455 for (int i = DimsArray - 1; i > 0; i--) {
456 auto *DimSize = SAI->getDimensionSize(i);
457 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
458
459 // This transformation is not applicable to dimensions with dynamic size.
460 if (!DimSizeCst)
461 continue;
462
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000463 // This transformation is not applicable to dimensions of size zero.
464 if (DimSize->isZero())
465 continue;
466
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000467 isl::val DimSizeVal =
468 valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
469 isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
470 isl::aff PrevVar =
471 isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000472
473 // Compute: index % size
474 // Modulo must apply in the divide of the previous iteration, if any.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000475 isl::aff Modulo = Var.mod_val(DimSizeVal);
476 Modulo = Modulo.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000477
478 // Compute: floor(index / size)
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000479 isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
480 Divide = Divide.floor();
481 Divide = Divide.add(PrevVar);
482 Divide = Divide.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000483
484 // Apply Modulo and Divide.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000485 DivModAff = DivModAff.set_aff(i, Modulo);
486 DivModAff = DivModAff.set_aff(i - 1, Divide);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000487 }
488
489 // Apply all modulo/divides on the accesses.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000490 isl::map Relation = give(AccessRelation);
491 Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
492 Relation = Relation.detect_equalities();
493 AccessRelation = Relation.release();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000494}
495
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000496void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000497 auto *SAI = getScopArrayInfo();
Tobias Grosser7be82452017-05-21 20:38:33 +0000498 isl::space ArraySpace = give(SAI->getSpace());
499 isl::space AccessSpace = give(isl_map_get_space(AccessRelation)).range();
500 isl::ctx Ctx = ArraySpace.get_ctx();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000501
Tobias Grosser7be82452017-05-21 20:38:33 +0000502 auto DimsArray = ArraySpace.dim(isl::dim::set);
503 auto DimsAccess = AccessSpace.dim(isl::dim::set);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000504 auto DimsMissing = DimsArray - DimsAccess;
505
Michael Kruse375cb5f2016-02-24 22:08:24 +0000506 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000507 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000508 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000509 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000510
Tobias Grosser7be82452017-05-21 20:38:33 +0000511 isl::map Map = isl::map::from_domain_and_range(
512 isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000513
514 for (unsigned i = 0; i < DimsMissing; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000515 Map = Map.fix_si(isl::dim::out, i, 0);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000516
517 for (unsigned i = DimsMissing; i < DimsArray; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000518 Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000519
Tobias Grosser7be82452017-05-21 20:38:33 +0000520 AccessRelation = isl_map_apply_range(AccessRelation, Map.release());
Roman Gareev10595a12016-01-08 14:01:59 +0000521
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000522 // For the non delinearized arrays, divide the access function of the last
523 // subscript by the size of the elements in the array.
524 //
525 // A stride one array access in C expressed as A[i] is expressed in
526 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
527 // two subsequent values of 'i' index two values that are stored next to
528 // each other in memory. By this division we make this characteristic
529 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000530 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000531 // that divides the offsets of all accesses to this base pointer.
532 if (DimsAccess == 1) {
Tobias Grosser7be82452017-05-21 20:38:33 +0000533 isl::val V = isl::val(Ctx, ArrayElemSize);
534 AccessRelation = isl_map_floordiv_val(AccessRelation, V.release());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000535 }
536
Michael Kruse3b425ff2016-04-11 14:34:08 +0000537 // We currently do this only if we added at least one dimension, which means
538 // some dimension's indices have not been specified, an indicator that some
539 // index values have been added together.
540 // TODO: Investigate general usefulness; Effect on unit tests is to make index
541 // expressions more complicated.
542 if (DimsMissing)
543 wrapConstantDimensions();
544
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000545 if (!isAffine())
546 computeBoundsOnAccessRelation(ArrayElemSize);
547
Tobias Grosserd840fc72016-02-04 13:18:42 +0000548 // Introduce multi-element accesses in case the type loaded by this memory
549 // access is larger than the canonical element type of the array.
550 //
551 // An access ((float *)A)[i] to an array char *A is modeled as
552 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000553 if (ElemBytes > ArrayElemSize) {
554 assert(ElemBytes % ArrayElemSize == 0 &&
555 "Loaded element size should be multiple of canonical element size");
Tobias Grosser7be82452017-05-21 20:38:33 +0000556 isl::map Map = isl::map::from_domain_and_range(
557 isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000558 for (unsigned i = 0; i < DimsArray - 1; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000559 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000560
Tobias Grosser7be82452017-05-21 20:38:33 +0000561 isl::constraint C;
562 isl::local_space LS;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000563
Tobias Grosser7be82452017-05-21 20:38:33 +0000564 LS = isl::local_space(Map.get_space());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000565 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
566
Tobias Grosser7be82452017-05-21 20:38:33 +0000567 C = isl::constraint::alloc_inequality(LS);
568 C = C.set_constant_val(isl::val(Ctx, Num - 1));
569 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
570 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
571 Map = Map.add_constraint(C);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000572
Tobias Grosser7be82452017-05-21 20:38:33 +0000573 C = isl::constraint::alloc_inequality(LS);
574 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, -1);
575 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, 1);
576 C = C.set_constant_val(isl::val(Ctx, 0));
577 Map = Map.add_constraint(C);
578 AccessRelation = isl_map_apply_range(AccessRelation, Map.release());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000579 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000580}
581
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000582const std::string
583MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
584 switch (RT) {
585 case MemoryAccess::RT_NONE:
586 llvm_unreachable("Requested a reduction operator string for a memory "
587 "access which isn't a reduction");
588 case MemoryAccess::RT_ADD:
589 return "+";
590 case MemoryAccess::RT_MUL:
591 return "*";
592 case MemoryAccess::RT_BOR:
593 return "|";
594 case MemoryAccess::RT_BXOR:
595 return "^";
596 case MemoryAccess::RT_BAND:
597 return "&";
598 }
599 llvm_unreachable("Unknown reduction type");
600 return "";
601}
602
Tobias Grosserc80d6972016-09-02 06:33:33 +0000603/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000604static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
605 const Instruction *Load) {
606 if (!BinOp)
607 return MemoryAccess::RT_NONE;
608 switch (BinOp->getOpcode()) {
609 case Instruction::FAdd:
610 if (!BinOp->hasUnsafeAlgebra())
611 return MemoryAccess::RT_NONE;
612 // Fall through
613 case Instruction::Add:
614 return MemoryAccess::RT_ADD;
615 case Instruction::Or:
616 return MemoryAccess::RT_BOR;
617 case Instruction::Xor:
618 return MemoryAccess::RT_BXOR;
619 case Instruction::And:
620 return MemoryAccess::RT_BAND;
621 case Instruction::FMul:
622 if (!BinOp->hasUnsafeAlgebra())
623 return MemoryAccess::RT_NONE;
624 // Fall through
625 case Instruction::Mul:
626 if (DisableMultiplicativeReductions)
627 return MemoryAccess::RT_NONE;
628 return MemoryAccess::RT_MUL;
629 default:
630 return MemoryAccess::RT_NONE;
631 }
632}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000633
Tobias Grosser75805372011-04-29 06:27:02 +0000634MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000635 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000636 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000637 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000638 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000639}
640
Michael Kruse2fa35192016-09-01 19:53:31 +0000641const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000642 isl_id *ArrayId = getArrayId();
643 void *User = isl_id_get_user(ArrayId);
644 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
645 isl_id_free(ArrayId);
646 return SAI;
647}
648
Michael Kruse2fa35192016-09-01 19:53:31 +0000649const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
650 isl_id *ArrayId = getLatestArrayId();
651 void *User = isl_id_get_user(ArrayId);
652 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
653 isl_id_free(ArrayId);
654 return SAI;
655}
656
657__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000658 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
659}
660
Michael Kruse2fa35192016-09-01 19:53:31 +0000661__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
662 if (!hasNewAccessRelation())
663 return getOriginalArrayId();
664 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
665}
666
Tobias Grosserd840fc72016-02-04 13:18:42 +0000667__isl_give isl_map *MemoryAccess::getAddressFunction() const {
668 return isl_map_lexmin(getAccessRelation());
669}
670
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000671__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
672 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000673 isl_map *Schedule, *ScheduledAccRel;
674 isl_union_set *UDomain;
675
676 UDomain = isl_union_set_from_set(getStatement()->getDomain());
677 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
678 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000679 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000680 return isl_pw_multi_aff_from_map(ScheduledAccRel);
681}
682
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000683__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000684 return isl_map_copy(AccessRelation);
685}
686
Johannes Doerferta99130f2014-10-13 12:58:03 +0000687std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000688 return stringFromIslObj(AccessRelation);
689}
690
Johannes Doerferta99130f2014-10-13 12:58:03 +0000691__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000692 return isl_map_get_space(AccessRelation);
693}
694
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000695__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000696 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000697}
698
Tobias Grosser6f730082015-09-05 07:46:47 +0000699std::string MemoryAccess::getNewAccessRelationStr() const {
700 return stringFromIslObj(NewAccessRelation);
701}
702
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000703__isl_give isl_basic_map *
704MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000705 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000706 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000707
Tobias Grosser084d8f72012-05-29 09:29:44 +0000708 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000709 isl_basic_set_universe(Statement->getDomainSpace()),
710 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000711}
712
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000713// Formalize no out-of-bound access assumption
714//
715// When delinearizing array accesses we optimistically assume that the
716// delinearized accesses do not access out of bound locations (the subscript
717// expression of each array evaluates for each statement instance that is
718// executed to a value that is larger than zero and strictly smaller than the
719// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000720// dimension for which we do not need to assume any upper bound. At this point
721// we formalize this assumption to ensure that at code generation time the
722// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000723//
724// To find the set of constraints necessary to avoid out of bound accesses, we
725// first build the set of data locations that are not within array bounds. We
726// then apply the reverse access relation to obtain the set of iterations that
727// may contain invalid accesses and reduce this set of iterations to the ones
728// that are actually executed by intersecting them with the domain of the
729// statement. If we now project out all loop dimensions, we obtain a set of
730// parameters that may cause statement instances to be executed that may
731// possibly yield out of bound memory accesses. The complement of these
732// constraints is the set of constraints that needs to be assumed to ensure such
733// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000734void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000735 if (PollyIgnoreInbounds)
736 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000737 auto *SAI = getScopArrayInfo();
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000738 isl::space Space = give(getOriginalAccessRelationSpace()).range();
739 isl::set Outside = isl::set::empty(Space);
740 for (int i = 1, Size = Space.dim(isl::dim::set); i < Size; ++i) {
741 isl::local_space LS(Space);
742 isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
743 isl::pw_aff Zero = isl::pw_aff(LS);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000744
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000745 isl::set DimOutside = Var.lt_set(Zero);
746 isl::pw_aff SizeE = give(SAI->getDimensionSizePw(i));
747 SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set));
748 SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
749 DimOutside = DimOutside.unite(SizeE.le_set(Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000750
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000751 Outside = Outside.unite(DimOutside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000752 }
753
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000754 Outside = Outside.apply(give(getAccessRelation()).reverse());
755 Outside = Outside.intersect(give(Statement->getDomain()));
756 Outside = Outside.params();
Tobias Grosserf54bb772015-06-26 12:09:28 +0000757
758 // Remove divs to avoid the construction of overly complicated assumptions.
759 // Doing so increases the set of parameter combinations that are assumed to
760 // not appear. This is always save, but may make the resulting run-time check
761 // bail out more often than strictly necessary.
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000762 Outside = Outside.remove_divs();
763 Outside = Outside.complement();
Michael Kruse7071e8b2016-04-11 13:24:29 +0000764 const auto &Loc = getAccessInstruction()
765 ? getAccessInstruction()->getDebugLoc()
766 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000767 if (!PollyPreciseInbounds)
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000768 Outside = Outside.gist_params(give(Statement->getDomain()).params());
769 Statement->getParent()->recordAssumption(INBOUNDS, Outside.release(), Loc,
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000770 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000771}
772
Johannes Doerfertcea61932016-02-21 19:13:19 +0000773void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000774 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000775 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000776
Tobias Grosser53fc3552017-05-23 07:07:09 +0000777 isl::pw_aff SubscriptPWA = give(getPwAff(Subscripts[0]));
778 isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000779
Tobias Grosser53fc3552017-05-23 07:07:09 +0000780 isl::map LengthMap;
Johannes Doerferta7920982016-02-25 14:08:48 +0000781 if (Subscripts[1] == nullptr) {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000782 LengthMap = isl::map::universe(SubscriptMap.get_space());
Johannes Doerferta7920982016-02-25 14:08:48 +0000783 } else {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000784 isl::pw_aff LengthPWA = give(getPwAff(Subscripts[1]));
785 LengthMap = isl::map::from_pw_aff(LengthPWA);
786 isl::space RangeSpace = LengthMap.get_space().range();
787 LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
Johannes Doerferta7920982016-02-25 14:08:48 +0000788 }
Tobias Grosser53fc3552017-05-23 07:07:09 +0000789 LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
790 LengthMap = LengthMap.align_params(SubscriptMap.get_space());
791 SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
792 LengthMap = LengthMap.sum(SubscriptMap);
793 AccessRelation =
794 LengthMap.set_tuple_id(isl::dim::in, give(getStatement()->getDomainId()))
795 .release();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000796}
797
Johannes Doerferte7044942015-02-24 11:58:30 +0000798void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
799 ScalarEvolution *SE = Statement->getParent()->getSE();
800
Johannes Doerfertcea61932016-02-21 19:13:19 +0000801 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000802 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000803 return;
804
805 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000806 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
807 return;
808
809 auto *PtrSCEV = SE->getSCEV(Ptr);
810 if (isa<SCEVCouldNotCompute>(PtrSCEV))
811 return;
812
813 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
814 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
815 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
816
817 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
818 if (Range.isFullSet())
819 return;
820
Michael Kruse960c0d02017-05-18 21:55:36 +0000821 if (Range.isWrappedSet() || Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000822 return;
823
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000824 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000825
Johannes Doerferte7044942015-02-24 11:58:30 +0000826 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000827 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000828 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000829 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000830
831 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000832 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000833
Tobias Grosserb3a85882017-02-12 08:11:12 +0000834 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
835
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000836 isl::map Relation = give(AccessRelation);
837 isl::set AccessRange = Relation.range();
838 AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
839 isl::dim::set);
840 AccessRelation = Relation.intersect_range(AccessRange).release();
Johannes Doerferte7044942015-02-24 11:58:30 +0000841}
842
Tobias Grosser491b7992016-12-02 05:21:22 +0000843void MemoryAccess::foldAccessRelation() {
844 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
845 return;
846
Michael Krusee2bccbb2015-09-18 19:59:43 +0000847 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000848
Tobias Grossera32de132017-05-23 07:22:56 +0000849 isl::map NewAccessRelation = give(isl_map_copy(AccessRelation));
Tobias Grosserc2f15102017-03-01 21:11:27 +0000850
Tobias Grosser619190d2015-03-30 17:22:28 +0000851 for (int i = Size - 2; i >= 0; --i) {
Tobias Grossera32de132017-05-23 07:22:56 +0000852 isl::space Space;
853 isl::map MapOne, MapTwo;
854 isl::pw_aff DimSize = give(getPwAff(Sizes[i + 1]));
Tobias Grosser619190d2015-03-30 17:22:28 +0000855
Tobias Grossera32de132017-05-23 07:22:56 +0000856 isl::space SpaceSize = DimSize.get_space();
857 isl::id ParamId =
858 give(isl_space_get_dim_id(SpaceSize.get(), isl_dim_param, 0));
Tobias Grosser619190d2015-03-30 17:22:28 +0000859
Tobias Grossera32de132017-05-23 07:22:56 +0000860 Space = give(isl_map_copy(AccessRelation)).get_space();
861 Space = Space.range().map_from_set();
862 Space = Space.align_params(SpaceSize);
Tobias Grosser619190d2015-03-30 17:22:28 +0000863
Tobias Grossera32de132017-05-23 07:22:56 +0000864 int ParamLocation = Space.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosser619190d2015-03-30 17:22:28 +0000865
Tobias Grossera32de132017-05-23 07:22:56 +0000866 MapOne = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000867 for (int j = 0; j < Size; ++j)
Tobias Grossera32de132017-05-23 07:22:56 +0000868 MapOne = MapOne.equate(isl::dim::in, j, isl::dim::out, j);
869 MapOne = MapOne.lower_bound_si(isl::dim::in, i + 1, 0);
Tobias Grosser619190d2015-03-30 17:22:28 +0000870
Tobias Grossera32de132017-05-23 07:22:56 +0000871 MapTwo = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000872 for (int j = 0; j < Size; ++j)
873 if (j < i || j > i + 1)
Tobias Grossera32de132017-05-23 07:22:56 +0000874 MapTwo = MapTwo.equate(isl::dim::in, j, isl::dim::out, j);
Tobias Grosser619190d2015-03-30 17:22:28 +0000875
Tobias Grossera32de132017-05-23 07:22:56 +0000876 isl::local_space LS(Space);
877 isl::constraint C;
878 C = isl::constraint::alloc_equality(LS);
879 C = C.set_constant_si(-1);
880 C = C.set_coefficient_si(isl::dim::in, i, 1);
881 C = C.set_coefficient_si(isl::dim::out, i, -1);
882 MapTwo = MapTwo.add_constraint(C);
883 C = isl::constraint::alloc_equality(LS);
884 C = C.set_coefficient_si(isl::dim::in, i + 1, 1);
885 C = C.set_coefficient_si(isl::dim::out, i + 1, -1);
886 C = C.set_coefficient_si(isl::dim::param, ParamLocation, 1);
887 MapTwo = MapTwo.add_constraint(C);
888 MapTwo = MapTwo.upper_bound_si(isl::dim::in, i + 1, -1);
Tobias Grosser619190d2015-03-30 17:22:28 +0000889
Tobias Grossera32de132017-05-23 07:22:56 +0000890 MapOne = MapOne.unite(MapTwo);
891 NewAccessRelation = NewAccessRelation.apply_range(MapOne);
Tobias Grosser619190d2015-03-30 17:22:28 +0000892 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000893
Tobias Grossera32de132017-05-23 07:22:56 +0000894 isl::id BaseAddrId = give(getScopArrayInfo()->getBasePtrId());
895 isl::space Space = give(Statement->getDomainSpace());
896 NewAccessRelation = NewAccessRelation.set_tuple_id(
897 isl::dim::in, Space.get_tuple_id(isl::dim::set));
898 NewAccessRelation = NewAccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
899 NewAccessRelation =
900 NewAccessRelation.gist_domain(give(Statement->getDomain()));
Tobias Grosserc2f15102017-03-01 21:11:27 +0000901
902 // Access dimension folding might in certain cases increase the number of
903 // disjuncts in the memory access, which can possibly complicate the generated
904 // run-time checks and can lead to costly compilation.
Tobias Grossera32de132017-05-23 07:22:56 +0000905 if (!PollyPreciseFoldAccesses &&
906 isl_map_n_basic_map(NewAccessRelation.get()) >
907 isl_map_n_basic_map(AccessRelation)) {
Tobias Grosserc2f15102017-03-01 21:11:27 +0000908 } else {
Tobias Grossera32de132017-05-23 07:22:56 +0000909 isl_map_free(AccessRelation);
910 AccessRelation = NewAccessRelation.release();
Tobias Grosserc2f15102017-03-01 21:11:27 +0000911 }
Tobias Grosser619190d2015-03-30 17:22:28 +0000912}
913
Tobias Grosserc80d6972016-09-02 06:33:33 +0000914/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000915static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000916 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000917 if (Size == 1)
918 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000919
920 // Only one factor needs to be divisible.
921 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
922 for (auto *FactorExpr : MulExpr->operands())
923 if (isDivisible(FactorExpr, Size, SE))
924 return true;
925 return false;
926 }
927
928 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
929 // to be divisble.
930 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
931 for (auto *OpExpr : NAryExpr->operands())
932 if (!isDivisible(OpExpr, Size, SE))
933 return false;
934 return true;
935 }
936
937 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
938 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
939 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
940 return MulSCEV == Expr;
941}
942
Michael Krusee2bccbb2015-09-18 19:59:43 +0000943void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
944 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000945
Johannes Doerfert85676e32016-04-23 14:32:34 +0000946 // Initialize the invalid domain which describes all iterations for which the
947 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000948 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
949 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
950 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000951
Michael Krusee2bccbb2015-09-18 19:59:43 +0000952 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000953 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000954
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000955 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
956 buildMemIntrinsicAccessRelation();
957 AccessRelation =
958 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
959 return;
960 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000961
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000962 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000963 // We overapproximate non-affine accesses with a possible access to the
964 // whole array. For read accesses it does not make a difference, if an
965 // access must or may happen. However, for write accesses it is important to
966 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000967 if (!AccessRelation)
968 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
969
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000970 AccessRelation =
971 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000972 return;
973 }
974
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000975 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000976 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000977
Michael Krusee2bccbb2015-09-18 19:59:43 +0000978 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000979 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000980 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000981 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000982 }
983
Tobias Grosser79baa212014-04-10 08:38:02 +0000984 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000985 AccessRelation = isl_map_set_tuple_id(
986 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000987 AccessRelation =
988 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
989
Tobias Grosseraa660a92015-03-30 00:07:50 +0000990 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000991 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000992}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000993
Michael Krusecac948e2015-10-02 13:53:07 +0000994MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000995 AccessType AccType, Value *BaseAddress,
996 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000997 ArrayRef<const SCEV *> Subscripts,
998 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +0000999 MemoryKind Kind)
Johannes Doerfertcea61932016-02-21 19:13:19 +00001000 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Tobias Grosser81331282017-05-03 07:57:35 +00001001 InvalidDomain(nullptr), BaseAddr(BaseAddress), ElementType(ElementType),
1002 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
1003 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +00001004 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001005 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +00001006 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001007 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001008
Tobias Grosser81331282017-05-03 07:57:35 +00001009 std::string IdName = Stmt->getBaseName() + Access;
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001010 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1011}
Michael Krusee2bccbb2015-09-18 19:59:43 +00001012
Roman Gareevb3224ad2016-09-14 06:26:09 +00001013MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
1014 __isl_take isl_map *AccRel)
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001015 : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
1016 Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001017 IsAffine(true), AccessRelation(nullptr), NewAccessRelation(AccRel),
1018 FAD(nullptr) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001019 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
1020 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1021 Sizes.push_back(nullptr);
1022 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1023 Sizes.push_back(SAI->getDimensionSize(i));
1024 ElementType = SAI->getElementType();
1025 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001026 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001027 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001028
Tobias Grosser81331282017-05-03 07:57:35 +00001029 std::string IdName = Stmt->getBaseName() + Access;
Roman Gareevb3224ad2016-09-14 06:26:09 +00001030 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1031}
1032
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001033void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +00001034 auto *Ctx = Statement->getParent()->getContext();
1035 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1036 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001037}
1038
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001039const std::string MemoryAccess::getReductionOperatorStr() const {
1040 return MemoryAccess::getReductionOperatorStr(getReductionType());
1041}
1042
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001043__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
1044
Johannes Doerfertf6183392014-07-01 20:52:51 +00001045raw_ostream &polly::operator<<(raw_ostream &OS,
1046 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001047 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001048 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001049 else
1050 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001051 return OS;
1052}
1053
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001054void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001055
Tobias Grosser75805372011-04-29 06:27:02 +00001056void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001057 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001058 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001059 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001060 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001061 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001062 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001063 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001064 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001065 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001066 break;
1067 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001068
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001069 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001070
1071 if (FAD) {
1072 OS << "[Fortran array descriptor: " << FAD->getName();
1073 OS << "] ";
1074 };
1075
Tobias Grossera535dff2015-12-13 19:59:01 +00001076 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001077 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001078 if (hasNewAccessRelation())
1079 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001080}
1081
Tobias Grosser74394f02013-01-14 22:40:23 +00001082void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +00001083
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001084__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
1085 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001086 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +00001087 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
1088 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
1089 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +00001090 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001091}
1092
Tobias Grosser75805372011-04-29 06:27:02 +00001093// Create a map in the size of the provided set domain, that maps from the
1094// one element of the provided set domain to another element of the provided
1095// set domain.
1096// The mapping is limited to all points that are equal in all but the last
1097// dimension and for which the last dimension of the input is strict smaller
1098// than the last dimension of the output.
1099//
1100// getEqualAndLarger(set[i0, i1, ..., iX]):
1101//
1102// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1103// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1104//
Tobias Grosser2a526fe2016-09-08 11:18:56 +00001105static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +00001106 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001107 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +00001108 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001109
1110 // Set all but the last dimension to be equal for the input and output
1111 //
1112 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1113 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001114 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +00001115 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001116
1117 // Set the last dimension of the input to be strict smaller than the
1118 // last dimension of the output.
1119 //
1120 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001121 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1122 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001123 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001124}
1125
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001126__isl_give isl_set *
1127MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001128 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +00001129 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +00001130 isl_space *Space = isl_space_range(isl_map_get_space(S));
1131 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001132
Sebastian Popa00a0292012-12-18 07:46:06 +00001133 S = isl_map_reverse(S);
1134 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001135
Sebastian Popa00a0292012-12-18 07:46:06 +00001136 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1137 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1138 NextScatt = isl_map_apply_domain(NextScatt, S);
1139 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001140
Sebastian Popa00a0292012-12-18 07:46:06 +00001141 isl_set *Deltas = isl_map_deltas(NextScatt);
1142 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001143}
1144
Sebastian Popa00a0292012-12-18 07:46:06 +00001145bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001146 int StrideWidth) const {
1147 isl_set *Stride, *StrideX;
1148 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001149
Sebastian Popa00a0292012-12-18 07:46:06 +00001150 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001151 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001152 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1153 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1154 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1155 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001156 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001157
Tobias Grosser28dd4862012-01-24 16:42:16 +00001158 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001159 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001160
Tobias Grosser28dd4862012-01-24 16:42:16 +00001161 return IsStrideX;
1162}
1163
Michael Krused56b90a2016-09-01 09:03:27 +00001164bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001165 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001166}
1167
Michael Krused56b90a2016-09-01 09:03:27 +00001168bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001169 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001170}
1171
Tobias Grosserbedef002016-12-02 08:10:56 +00001172void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
1173 isl_map_free(AccessRelation);
1174 AccessRelation = NewAccess;
1175}
1176
Michael Krused56b90a2016-09-01 09:03:27 +00001177void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001178 assert(NewAccess);
1179
1180#ifndef NDEBUG
1181 // Check domain space compatibility.
1182 auto *NewSpace = isl_map_get_space(NewAccess);
1183 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1184 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1185 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1186 isl_space_free(NewDomainSpace);
1187 isl_space_free(OriginalDomainSpace);
1188
Michael Kruse706f79a2017-05-21 22:46:57 +00001189 // Reads must be executed unconditionally. Writes might be executed in a
1190 // subdomain only.
1191 if (isRead()) {
1192 // Check whether there is an access for every statement instance.
1193 auto *StmtDomain = getStatement()->getDomain();
1194 StmtDomain = isl_set_intersect_params(
1195 StmtDomain, getStatement()->getParent()->getContext());
1196 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1197 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1198 "Partial READ accesses not supported");
1199 isl_set_free(NewDomain);
1200 isl_set_free(StmtDomain);
1201 }
Michael Kruse772ce722016-09-01 19:16:58 +00001202
Michael Kruse772ce722016-09-01 19:16:58 +00001203 auto *NewAccessSpace = isl_space_range(NewSpace);
1204 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1205 "Must specify the array that is accessed");
1206 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1207 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1208 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001209
1210 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1211 InvariantEquivClassTy *EqClass =
1212 getStatement()->getParent()->lookupInvariantEquivClass(
1213 SAI->getBasePtr());
1214 assert(EqClass &&
1215 "Access functions to indirect arrays must have an invariant and "
1216 "hoisted base pointer");
1217 }
1218
1219 // Check whether access dimensions correspond to number of dimensions of the
1220 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001221 auto Dims = SAI->getNumberOfDimensions();
1222 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1223 "Access dims must match array dims");
1224 isl_space_free(NewAccessSpace);
1225 isl_id_free(NewArrayId);
1226#endif
1227
Tobias Grosser166c4222015-09-05 07:46:40 +00001228 isl_map_free(NewAccessRelation);
1229 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001230}
Tobias Grosser75805372011-04-29 06:27:02 +00001231
Michael Kruse706f79a2017-05-21 22:46:57 +00001232bool MemoryAccess::isLatestPartialAccess() const {
1233 isl::set StmtDom = give(getStatement()->getDomain());
1234 isl::set AccDom = give(isl_map_domain(getLatestAccessRelation()));
1235
1236 return isl_set_is_subset(StmtDom.keep(), AccDom.keep()) == isl_bool_false;
1237}
1238
Tobias Grosser75805372011-04-29 06:27:02 +00001239//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001240
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001241__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001242 isl_set *Domain = getDomain();
1243 if (isl_set_is_empty(Domain)) {
1244 isl_set_free(Domain);
1245 return isl_map_from_aff(
1246 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1247 }
1248 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001249 if (!Schedule) {
1250 isl_set_free(Domain);
1251 return nullptr;
1252 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001253 Schedule = isl_union_map_intersect_domain(
1254 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1255 if (isl_union_map_is_empty(Schedule)) {
1256 isl_set_free(Domain);
1257 isl_union_map_free(Schedule);
1258 return isl_map_from_aff(
1259 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1260 }
1261 auto *M = isl_map_from_union_map(Schedule);
1262 M = isl_map_coalesce(M);
1263 M = isl_map_gist_domain(M, Domain);
1264 M = isl_map_coalesce(M);
1265 return M;
1266}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001267
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001268__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1269 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001270 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1271 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001272}
1273
Tobias Grosser37eb4222014-02-20 21:43:54 +00001274void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1275 assert(isl_set_is_subset(NewDomain, Domain) &&
1276 "New domain is not a subset of old domain!");
1277 isl_set_free(Domain);
1278 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001279}
1280
Michael Krusecac948e2015-10-02 13:53:07 +00001281void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001282 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001283 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001284 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001285
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001286 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001287 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001288 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001289 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001290 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001291 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001292 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001293 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001294 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001295
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001296 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1297 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001298 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001299 }
1300}
1301
Michael Kruse4c276432017-05-11 22:56:46 +00001302MemoryAccess *ScopStmt::lookupPHIReadOf(PHINode *PHI) const {
1303 for (auto *MA : *this) {
1304 if (!MA->isRead())
1305 continue;
1306 if (!MA->isLatestAnyPHIKind())
1307 continue;
1308
1309 if (MA->getAccessInstruction() == PHI)
1310 return MA;
1311 }
1312 return nullptr;
1313}
1314
Michael Krusecac948e2015-10-02 13:53:07 +00001315void ScopStmt::addAccess(MemoryAccess *Access) {
1316 Instruction *AccessInst = Access->getAccessInstruction();
1317
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001318 if (Access->isArrayKind()) {
1319 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1320 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001321 } else if (Access->isValueKind() && Access->isWrite()) {
1322 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001323 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001324 assert(!ValueWrites.lookup(AccessVal));
1325
1326 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001327 } else if (Access->isValueKind() && Access->isRead()) {
1328 Value *AccessVal = Access->getAccessValue();
1329 assert(!ValueReads.lookup(AccessVal));
1330
1331 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001332 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001333 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001334 assert(!PHIWrites.lookup(PHI));
1335
1336 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001337 }
1338
1339 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001340}
1341
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001342void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001343 for (MemoryAccess *MA : *this)
1344 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001345
Johannes Doerferta60ad842016-05-10 12:18:22 +00001346 auto *Ctx = Parent.getContext();
1347 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1348 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001349}
1350
Tobias Grosserc80d6972016-09-02 06:33:33 +00001351/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001352static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1353 void *User) {
1354 isl_set **BoundedParts = static_cast<isl_set **>(User);
1355 if (isl_basic_set_is_bounded(BSet))
1356 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1357 else
1358 isl_basic_set_free(BSet);
1359 return isl_stat_ok;
1360}
1361
Tobias Grosserc80d6972016-09-02 06:33:33 +00001362/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001363static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1364 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1365 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1366 isl_set_free(S);
1367 return BoundedParts;
1368}
1369
Tobias Grosserc80d6972016-09-02 06:33:33 +00001370/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001371///
1372/// @returns A separation of @p S into first an unbounded then a bounded subset,
1373/// both with regards to the dimension @p Dim.
1374static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1375partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1376
1377 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001378 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001379
1380 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001381 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001382
1383 // Remove dimensions that are greater than Dim as they are not interesting.
1384 assert(NumDimsS >= Dim + 1);
1385 OnlyDimS =
1386 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1387
1388 // Create artificial parametric upper bounds for dimensions smaller than Dim
1389 // as we are not interested in them.
1390 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1391 for (unsigned u = 0; u < Dim; u++) {
1392 isl_constraint *C = isl_inequality_alloc(
1393 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1394 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1395 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1396 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1397 }
1398
1399 // Collect all bounded parts of OnlyDimS.
1400 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1401
1402 // Create the dimensions greater than Dim again.
1403 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1404 NumDimsS - Dim - 1);
1405
1406 // Remove the artificial upper bound parameters again.
1407 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1408
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001409 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001410 return std::make_pair(UnboundedParts, BoundedParts);
1411}
1412
Tobias Grosserc80d6972016-09-02 06:33:33 +00001413/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001414static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1415 __isl_take isl_set *To) {
1416 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1417 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1418 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1419 }
1420 return To;
1421}
1422
Tobias Grosserc80d6972016-09-02 06:33:33 +00001423/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001424static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001425 __isl_take isl_pw_aff *L,
1426 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001427 switch (Pred) {
1428 case ICmpInst::ICMP_EQ:
1429 return isl_pw_aff_eq_set(L, R);
1430 case ICmpInst::ICMP_NE:
1431 return isl_pw_aff_ne_set(L, R);
1432 case ICmpInst::ICMP_SLT:
1433 return isl_pw_aff_lt_set(L, R);
1434 case ICmpInst::ICMP_SLE:
1435 return isl_pw_aff_le_set(L, R);
1436 case ICmpInst::ICMP_SGT:
1437 return isl_pw_aff_gt_set(L, R);
1438 case ICmpInst::ICMP_SGE:
1439 return isl_pw_aff_ge_set(L, R);
1440 case ICmpInst::ICMP_ULT:
1441 return isl_pw_aff_lt_set(L, R);
1442 case ICmpInst::ICMP_UGT:
1443 return isl_pw_aff_gt_set(L, R);
1444 case ICmpInst::ICMP_ULE:
1445 return isl_pw_aff_le_set(L, R);
1446 case ICmpInst::ICMP_UGE:
1447 return isl_pw_aff_ge_set(L, R);
1448 default:
1449 llvm_unreachable("Non integer predicate not supported");
1450 }
1451}
1452
Tobias Grosserc80d6972016-09-02 06:33:33 +00001453/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001454///
1455/// Helper function that will make sure the dimensions of the result have the
1456/// same isl_id's as the @p Domain.
1457static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1458 __isl_take isl_pw_aff *L,
1459 __isl_take isl_pw_aff *R,
1460 __isl_keep isl_set *Domain) {
1461 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1462 return setDimensionIds(Domain, ConsequenceCondSet);
1463}
1464
Tobias Grosserc80d6972016-09-02 06:33:33 +00001465/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001466///
1467/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001468/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1469/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001470static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001471buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1472 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001473 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1474
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001475 Value *Condition = getConditionFromTerminator(SI);
1476 assert(Condition && "No condition for switch");
1477
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001478 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001479 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001480 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001481 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001482
1483 unsigned NumSuccessors = SI->getNumSuccessors();
1484 ConditionSets.resize(NumSuccessors);
1485 for (auto &Case : SI->cases()) {
1486 unsigned Idx = Case.getSuccessorIndex();
1487 ConstantInt *CaseValue = Case.getCaseValue();
1488
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001489 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001490 isl_set *CaseConditionSet =
1491 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1492 ConditionSets[Idx] = isl_set_coalesce(
1493 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1494 }
1495
1496 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1497 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1498 for (unsigned u = 2; u < NumSuccessors; u++)
1499 ConditionSetUnion =
1500 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1501 ConditionSets[0] = setDimensionIds(
1502 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1503
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001504 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001505
1506 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001507}
1508
Tobias Grosserc80d6972016-09-02 06:33:33 +00001509/// Build the conditions sets for the branch condition @p Condition in
1510/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001511///
1512/// This will fill @p ConditionSets with the conditions under which control
1513/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001514/// have as many elements as @p TI has successors. If @p TI is nullptr the
1515/// context under which @p Condition is true/false will be returned as the
1516/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001517static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001518buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1519 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001520 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1521
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001522 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001523 isl_set *ConsequenceCondSet = nullptr;
1524 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1525 if (CCond->isZero())
1526 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1527 else
1528 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1529 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1530 auto Opcode = BinOp->getOpcode();
1531 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1532
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001533 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1534 ConditionSets) &&
1535 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1536 ConditionSets);
1537 if (!Valid) {
1538 while (!ConditionSets.empty())
1539 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001540 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001541 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001542
1543 isl_set_free(ConditionSets.pop_back_val());
1544 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1545 isl_set_free(ConditionSets.pop_back_val());
1546 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1547
1548 if (Opcode == Instruction::And)
1549 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1550 else
1551 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1552 } else {
1553 auto *ICond = dyn_cast<ICmpInst>(Condition);
1554 assert(ICond &&
1555 "Condition of exiting branch was neither constant nor ICmp!");
1556
1557 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001558 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001559 // For unsigned comparisons we assumed the signed bit of neither operand
1560 // to be set. The comparison is equal to a signed comparison under this
1561 // assumption.
1562 bool NonNeg = ICond->isUnsigned();
1563 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1564 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001565 ConsequenceCondSet =
1566 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1567 }
1568
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001569 // If no terminator was given we are only looking for parameter constraints
1570 // under which @p Condition is true/false.
1571 if (!TI)
1572 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001573 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001574 ConsequenceCondSet = isl_set_coalesce(
1575 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001576
Johannes Doerfertb2885792016-04-26 09:20:41 +00001577 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001578 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001579 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001580
Michael Krusef7a4a942016-05-02 12:25:36 +00001581 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001582 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1583 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001584 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001585 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001586 }
1587
Michael Krusef7a4a942016-05-02 12:25:36 +00001588 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001589 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001590 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001591 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001592 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001593 }
1594
1595 ConditionSets.push_back(ConsequenceCondSet);
1596 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001597
1598 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001599}
1600
Tobias Grosserc80d6972016-09-02 06:33:33 +00001601/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001602///
1603/// This will fill @p ConditionSets with the conditions under which control
1604/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1605/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001606static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001607buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001608 __isl_keep isl_set *Domain,
1609 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1610
1611 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001612 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001613
1614 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1615
1616 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001617 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001618 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001619 }
1620
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001621 Value *Condition = getConditionFromTerminator(TI);
1622 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001623
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001624 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001625}
1626
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001627void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001628 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001629
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001630 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001631 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001632}
1633
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001634void ScopStmt::collectSurroundingLoops() {
1635 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1636 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1637 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1638 isl_id_free(DimId);
1639 }
1640}
1641
Michael Kruse55454072017-03-15 22:16:43 +00001642ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001643 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
Michael Kruse55454072017-03-15 22:16:43 +00001644 R(&R), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001645
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001646 BaseName = getIslCompatibleName(
1647 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001648}
1649
Michael Kruse55454072017-03-15 22:16:43 +00001650ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001651 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Michael Kruse55454072017-03-15 22:16:43 +00001652 R(nullptr), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Tobias Grosser75805372011-04-29 06:27:02 +00001653
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001654 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), "",
1655 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001656}
1657
Roman Gareevb3224ad2016-09-14 06:26:09 +00001658ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1659 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1660 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1661 R(nullptr), Build(nullptr) {
1662 BaseName = getIslCompatibleName("CopyStmt_", "",
1663 std::to_string(parent.getCopyStmtsNum()));
1664 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1665 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1666 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1667 auto *Access =
1668 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1669 parent.addAccessFunction(Access);
1670 addAccess(Access);
1671 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1672 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1673 parent.addAccessFunction(Access);
1674 addAccess(Access);
1675}
1676
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001677void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001678 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001679
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001680 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001681 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001682 buildAccessRelations();
1683
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001684 if (DetectReductions)
1685 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001686}
1687
Tobias Grosserc80d6972016-09-02 06:33:33 +00001688/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001689///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001690/// Check if the stored value for @p StoreMA is a binary operator with one or
1691/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001692/// used only once (by @p StoreMA) and its load operands are also used only
1693/// once, we have found a possible reduction chain. It starts at an operand
1694/// load and includes the binary operator and @p StoreMA.
1695///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001696/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001697/// escape this block or into any other store except @p StoreMA.
1698void ScopStmt::collectCandiateReductionLoads(
1699 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1700 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1701 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001702 return;
1703
1704 // Skip if there is not one binary operator between the load and the store
1705 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001706 if (!BinOp)
1707 return;
1708
1709 // Skip if the binary operators has multiple uses
1710 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001711 return;
1712
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001713 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001714 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1715 return;
1716
Johannes Doerfert9890a052014-07-01 00:32:29 +00001717 // Skip if the binary operator is outside the current SCoP
1718 if (BinOp->getParent() != Store->getParent())
1719 return;
1720
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001721 // Skip if it is a multiplicative reduction and we disabled them
1722 if (DisableMultiplicativeReductions &&
1723 (BinOp->getOpcode() == Instruction::Mul ||
1724 BinOp->getOpcode() == Instruction::FMul))
1725 return;
1726
Johannes Doerferte58a0122014-06-27 20:31:28 +00001727 // Check the binary operator operands for a candidate load
1728 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1729 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1730 if (!PossibleLoad0 && !PossibleLoad1)
1731 return;
1732
1733 // A load is only a candidate if it cannot escape (thus has only this use)
1734 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001735 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001736 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001737 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001738 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001739 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001740}
1741
Tobias Grosserc80d6972016-09-02 06:33:33 +00001742/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001743///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001744/// Iterate over all store memory accesses and check for valid binary reduction
1745/// like chains. For all candidates we check if they have the same base address
1746/// and there are no other accesses which overlap with them. The base address
1747/// check rules out impossible reductions candidates early. The overlap check,
1748/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001749/// guarantees that none of the intermediate results will escape during
1750/// execution of the loop nest. We basically check here that no other memory
1751/// access can access the same memory as the potential reduction.
1752void ScopStmt::checkForReductions() {
1753 SmallVector<MemoryAccess *, 2> Loads;
1754 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1755
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001756 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001757 // stores and collecting possible reduction loads.
1758 for (MemoryAccess *StoreMA : MemAccs) {
1759 if (StoreMA->isRead())
1760 continue;
1761
1762 Loads.clear();
1763 collectCandiateReductionLoads(StoreMA, Loads);
1764 for (MemoryAccess *LoadMA : Loads)
1765 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1766 }
1767
1768 // Then check each possible candidate pair.
1769 for (const auto &CandidatePair : Candidates) {
1770 bool Valid = true;
1771 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1772 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1773
1774 // Skip those with obviously unequal base addresses.
1775 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1776 isl_map_free(LoadAccs);
1777 isl_map_free(StoreAccs);
1778 continue;
1779 }
1780
1781 // And check if the remaining for overlap with other memory accesses.
1782 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1783 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1784 isl_set *AllAccs = isl_map_range(AllAccsRel);
1785
1786 for (MemoryAccess *MA : MemAccs) {
1787 if (MA == CandidatePair.first || MA == CandidatePair.second)
1788 continue;
1789
1790 isl_map *AccRel =
1791 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1792 isl_set *Accs = isl_map_range(AccRel);
1793
Tobias Grosser55a7af72016-09-08 14:08:07 +00001794 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001795 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1796 Valid = Valid && isl_set_is_empty(OverlapAccs);
1797 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001798 } else {
1799 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001800 }
1801 }
1802
1803 isl_set_free(AllAccs);
1804 if (!Valid)
1805 continue;
1806
Johannes Doerfertf6183392014-07-01 20:52:51 +00001807 const LoadInst *Load =
1808 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1809 MemoryAccess::ReductionType RT =
1810 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1811
Johannes Doerferte58a0122014-06-27 20:31:28 +00001812 // If no overlapping access was found we mark the load and store as
1813 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001814 CandidatePair.first->markAsReductionLike(RT);
1815 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001816 }
Tobias Grosser75805372011-04-29 06:27:02 +00001817}
1818
Tobias Grosser74394f02013-01-14 22:40:23 +00001819std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001820
Tobias Grosser54839312015-04-21 11:37:25 +00001821std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001822 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001823 if (!S)
1824 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001825 auto Str = stringFromIslObj(S);
1826 isl_map_free(S);
1827 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001828}
1829
Johannes Doerferta3519512016-04-23 13:02:23 +00001830void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1831 isl_set_free(InvalidDomain);
1832 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001833}
1834
Michael Kruse375cb5f2016-02-24 22:08:24 +00001835BasicBlock *ScopStmt::getEntryBlock() const {
1836 if (isBlockStmt())
1837 return getBasicBlock();
1838 return getRegion()->getEntry();
1839}
1840
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001841unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001842
Tobias Grosser75805372011-04-29 06:27:02 +00001843const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1844
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001845Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001846 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001847}
1848
Tobias Grosser74394f02013-01-14 22:40:23 +00001849isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001850
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001851__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001852
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001853__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001854 return isl_set_get_space(Domain);
1855}
1856
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001857__isl_give isl_id *ScopStmt::getDomainId() const {
1858 return isl_set_get_tuple_id(Domain);
1859}
Tobias Grossercd95b772012-08-30 11:49:38 +00001860
Johannes Doerfert7c013572016-04-12 09:57:34 +00001861ScopStmt::~ScopStmt() {
1862 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001863 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001864}
Tobias Grosser75805372011-04-29 06:27:02 +00001865
1866void ScopStmt::print(raw_ostream &OS) const {
1867 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001868 OS.indent(12) << "Domain :=\n";
1869
1870 if (Domain) {
1871 OS.indent(16) << getDomainStr() << ";\n";
1872 } else
1873 OS.indent(16) << "n/a\n";
1874
Tobias Grosser54839312015-04-21 11:37:25 +00001875 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001876
1877 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001878 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001879 } else
1880 OS.indent(16) << "n/a\n";
1881
Tobias Grosser083d3d32014-06-28 08:59:45 +00001882 for (MemoryAccess *Access : MemAccs)
1883 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001884}
1885
1886void ScopStmt::dump() const { print(dbgs()); }
1887
Michael Krusee60eca72017-05-11 22:56:12 +00001888void ScopStmt::removeAccessData(MemoryAccess *MA) {
1889 if (MA->isRead() && MA->isOriginalValueKind()) {
1890 bool Found = ValueReads.erase(MA->getAccessValue());
1891 (void)Found;
1892 assert(Found && "Expected access data not found");
1893 }
1894 if (MA->isWrite() && MA->isOriginalValueKind()) {
1895 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1896 (void)Found;
1897 assert(Found && "Expected access data not found");
1898 }
1899 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1900 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1901 (void)Found;
1902 assert(Found && "Expected access data not found");
1903 }
1904}
1905
Michael Kruse10071822016-05-23 14:45:58 +00001906void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001907 // Remove the memory accesses from this statement together with all scalar
1908 // accesses that were caused by it. MemoryKind::Value READs have no access
1909 // instruction, hence would not be removed by this function. However, it is
1910 // only used for invariant LoadInst accesses, its arguments are always affine,
1911 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1912 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001913 auto Predicate = [&](MemoryAccess *Acc) {
1914 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1915 };
Michael Krusee60eca72017-05-11 22:56:12 +00001916 for (auto *MA : MemAccs) {
1917 if (Predicate(MA))
1918 removeAccessData(MA);
1919 }
Michael Kruse10071822016-05-23 14:45:58 +00001920 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1921 MemAccs.end());
1922 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001923}
1924
Michael Kruse0446d812017-03-10 16:05:24 +00001925void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
1926 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1927 assert(MAIt != MemAccs.end());
1928 MemAccs.erase(MAIt);
1929
Michael Krusee60eca72017-05-11 22:56:12 +00001930 removeAccessData(MA);
1931
Michael Kruse0446d812017-03-10 16:05:24 +00001932 auto It = InstructionToAccess.find(MA->getAccessInstruction());
1933 if (It != InstructionToAccess.end()) {
1934 It->second.remove(MA);
1935 if (It->second.empty())
1936 InstructionToAccess.erase(MA->getAccessInstruction());
1937 }
1938}
1939
Tobias Grosser75805372011-04-29 06:27:02 +00001940//===----------------------------------------------------------------------===//
1941/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001942
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001943void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001944 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1945 isl_set_free(Context);
1946 Context = NewContext;
1947}
1948
Tobias Grosserc80d6972016-09-02 06:33:33 +00001949/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001950struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001951 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001952 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001953
1954public:
1955 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001956 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001957
1958 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1959 ValueToValueMap &VMap) {
1960 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1961 return SSPR.visit(E);
1962 }
1963
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001964 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1965 auto *Start = visit(E->getStart());
1966 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1967 visit(E->getStepRecurrence(SE)),
1968 E->getLoop(), SCEV::FlagAnyWrap);
1969 return SE.getAddExpr(Start, AddRec);
1970 }
1971
1972 const SCEV *visitUnknown(const SCEVUnknown *E) {
1973 if (auto *NewValue = VMap.lookup(E->getValue()))
1974 return SE.getUnknown(NewValue);
1975 return E;
1976 }
1977};
1978
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001979const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001980 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001981}
1982
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001983void Scop::createParameterId(const SCEV *Parameter) {
1984 assert(Parameters.count(Parameter));
1985 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001986
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001987 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001988
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001989 if (UseInstructionNames) {
1990 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1991 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001992
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001993 // If this parameter references a specific Value and this value has a name
1994 // we use this name as it is likely to be unique and more useful than just
1995 // a number.
1996 if (Val->hasName())
1997 ParameterName = Val->getName();
1998 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1999 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
2000 if (LoadOrigin->hasName()) {
2001 ParameterName += "_loaded_from_";
2002 ParameterName +=
2003 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
2004 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002005 }
2006 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00002007
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002008 ParameterName = getIslCompatibleName("", ParameterName, "");
2009 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00002010
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002011 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
2012 const_cast<void *>((const void *)Parameter));
2013 ParameterIds[Parameter] = Id;
2014}
2015
2016void Scop::addParams(const ParameterSetTy &NewParameters) {
2017 for (const SCEV *Parameter : NewParameters) {
2018 // Normalize the SCEV to get the representing element for an invariant load.
2019 Parameter = extractConstantFactor(Parameter, *SE).second;
2020 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2021
2022 if (Parameters.insert(Parameter))
2023 createParameterId(Parameter);
2024 }
2025}
2026
2027__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
2028 // Normalize the SCEV to get the representing element for an invariant load.
2029 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2030 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00002031}
Tobias Grosser75805372011-04-29 06:27:02 +00002032
Michael Krused56b90a2016-09-01 09:03:27 +00002033__isl_give isl_set *
2034Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002035 isl_set *DomainContext = isl_union_set_params(getDomains());
2036 return isl_set_intersect_params(C, DomainContext);
2037}
2038
Johannes Doerferte0b08072016-05-23 12:43:44 +00002039bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2040 return DT.dominates(BB, getEntry());
2041}
2042
Michael Kruse89b1f942017-03-17 13:56:53 +00002043void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
2044 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002045 auto &F = getFunction();
Michael Kruse89b1f942017-03-17 13:56:53 +00002046 for (auto &Assumption : AC.assumptions()) {
2047 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2048 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002049 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002050
Michael Kruse89b1f942017-03-17 13:56:53 +00002051 bool InScop = contains(CI);
2052 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2053 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002054
Michael Kruse89b1f942017-03-17 13:56:53 +00002055 auto *L = LI.getLoopFor(CI->getParent());
2056 auto *Val = CI->getArgOperand(0);
2057 ParameterSetTy DetectedParams;
2058 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
2059 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
2060 CI->getDebugLoc(),
2061 "Non-affine user assumption ignored.");
2062 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002063 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002064
2065 // Collect all newly introduced parameters.
2066 ParameterSetTy NewParams;
2067 for (auto *Param : DetectedParams) {
2068 Param = extractConstantFactor(Param, *SE).second;
2069 Param = getRepresentingInvariantLoadSCEV(Param);
2070 if (Parameters.count(Param))
2071 continue;
2072 NewParams.insert(Param);
2073 }
2074
2075 SmallVector<isl_set *, 2> ConditionSets;
2076 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
2077 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
2078 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
2079 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
2080 isl_set_free(Dom);
2081
2082 if (!Valid)
2083 continue;
2084
2085 isl_set *AssumptionCtx = nullptr;
2086 if (InScop) {
2087 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2088 isl_set_free(ConditionSets[0]);
2089 } else {
2090 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2091 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2092 }
2093
2094 // Project out newly introduced parameters as they are not otherwise useful.
2095 if (!NewParams.empty()) {
2096 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2097 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2098 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2099 isl_id_free(Id);
2100
2101 if (!NewParams.count(Param))
2102 continue;
2103
2104 AssumptionCtx =
2105 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2106 }
2107 }
2108
2109 emitOptimizationRemarkAnalysis(
2110 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
2111 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
2112 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002113 }
2114}
2115
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002116void Scop::addUserContext() {
2117 if (UserContextStr.empty())
2118 return;
2119
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002120 isl_set *UserContext =
2121 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002122 isl_space *Space = getParamSpace();
2123 if (isl_space_dim(Space, isl_dim_param) !=
2124 isl_set_dim(UserContext, isl_dim_param)) {
2125 auto SpaceStr = isl_space_to_str(Space);
2126 errs() << "Error: the context provided in -polly-context has not the same "
2127 << "number of dimensions than the computed context. Due to this "
2128 << "mismatch, the -polly-context option is ignored. Please provide "
2129 << "the context in the parameter space: " << SpaceStr << ".\n";
2130 free(SpaceStr);
2131 isl_set_free(UserContext);
2132 isl_space_free(Space);
2133 return;
2134 }
2135
2136 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002137 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2138 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002139
2140 if (strcmp(NameContext, NameUserContext) != 0) {
2141 auto SpaceStr = isl_space_to_str(Space);
2142 errs() << "Error: the name of dimension " << i
2143 << " provided in -polly-context "
2144 << "is '" << NameUserContext << "', but the name in the computed "
2145 << "context is '" << NameContext
2146 << "'. Due to this name mismatch, "
2147 << "the -polly-context option is ignored. Please provide "
2148 << "the context in the parameter space: " << SpaceStr << ".\n";
2149 free(SpaceStr);
2150 isl_set_free(UserContext);
2151 isl_space_free(Space);
2152 return;
2153 }
2154
2155 UserContext =
2156 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2157 isl_space_get_dim_id(Space, isl_dim_param, i));
2158 }
2159
2160 Context = isl_set_intersect(Context, UserContext);
2161 isl_space_free(Space);
2162}
2163
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002164void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002165 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002166
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002167 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002168 for (LoadInst *LInst : RIL) {
2169 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2170
Johannes Doerfert96e54712016-02-07 17:30:13 +00002171 Type *Ty = LInst->getType();
2172 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002173 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002174 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002175 continue;
2176 }
2177
2178 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002179 InvariantEquivClasses.emplace_back(
2180 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002181 }
2182}
2183
Tobias Grosser6be480c2011-11-08 15:41:13 +00002184void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002185 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002186 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002187 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002188 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002189}
2190
Tobias Grosser18daaca2012-05-22 10:47:27 +00002191void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002192 unsigned PDim = 0;
2193 for (auto *Parameter : Parameters) {
2194 ConstantRange SRange = SE->getSignedRange(Parameter);
Tobias Grosser99ea1d02017-05-21 20:23:20 +00002195 Context =
2196 addRangeBoundsToSet(give(Context), SRange, PDim++, isl::dim::param)
2197 .release();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002198 }
2199}
2200
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002201// We use the outermost dimension to generate GPU transfers for Fortran arrays
2202// even when the array bounds are not known statically. To do so, we need the
2203// outermost dimension information. We add this into the context so that the
2204// outermost dimension is available during codegen.
2205// We currently do not care about dimensions other than the outermost
2206// dimension since it doesn't affect transfers.
2207static isl_set *addFortranArrayOutermostDimParams(__isl_give isl_set *Context,
2208 Scop::array_range Arrays) {
2209
2210 std::vector<isl_id *> OutermostSizeIds;
2211 for (auto Array : Arrays) {
2212 // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2213 // for its outermost dimension. Fortran arrays will have this since the
2214 // outermost dimension size can be picked up from their runtime description.
2215 // TODO: actually need to check if it has a FAD, but for now this works.
2216 if (Array->getNumberOfDimensions() > 0) {
2217 isl_pw_aff *PwAff = Array->getDimensionSizePw(0);
2218 if (!PwAff)
2219 continue;
2220
2221 isl_id *Id = isl_pw_aff_get_dim_id(PwAff, isl_dim_param, 0);
2222 isl_pw_aff_free(PwAff);
2223 assert(Id && "Invalid Id for PwAff expression in Fortran array");
2224 OutermostSizeIds.push_back(Id);
2225 }
2226 }
2227
2228 const int NumTrueParams = isl_set_dim(Context, isl_dim_param);
2229 Context = isl_set_add_dims(Context, isl_dim_param, OutermostSizeIds.size());
2230
2231 for (size_t i = 0; i < OutermostSizeIds.size(); i++) {
2232 Context = isl_set_set_dim_id(Context, isl_dim_param, NumTrueParams + i,
2233 OutermostSizeIds[i]);
2234 Context =
2235 isl_set_lower_bound_si(Context, isl_dim_param, NumTrueParams + i, 0);
2236 }
2237
2238 return Context;
2239}
2240
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002241void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002242 if (PollyIgnoreParamBounds)
2243 return;
2244
Tobias Grosser6be480c2011-11-08 15:41:13 +00002245 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002246 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002247
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002248 unsigned PDim = 0;
2249 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002250 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002251 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002252 }
2253
2254 // Align the parameters of all data structures to the model.
2255 Context = isl_set_align_params(Context, Space);
2256
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002257 // Add the outermost dimension of the Fortran arrays into the Context.
2258 // See the description of the function for more information.
2259 Context = addFortranArrayOutermostDimParams(Context, arrays());
2260
Johannes Doerferta60ad842016-05-10 12:18:22 +00002261 // As all parameters are known add bounds to them.
2262 addParameterBounds();
2263
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002264 for (ScopStmt &Stmt : *this)
2265 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002266 // Simplify the schedule according to the context too.
2267 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002268}
2269
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002270static __isl_give isl_set *
2271simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2272 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002273 // If we have modeled all blocks in the SCoP that have side effects we can
2274 // simplify the context with the constraints that are needed for anything to
2275 // be executed at all. However, if we have error blocks in the SCoP we already
2276 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002277 // domains, thus we cannot use the remaining domain to simplify the
2278 // assumptions.
2279 if (!S.hasErrorBlock()) {
2280 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2281 AssumptionContext =
2282 isl_set_gist_params(AssumptionContext, DomainParameters);
2283 }
2284
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002285 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2286 return AssumptionContext;
2287}
2288
2289void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002290 // The parameter constraints of the iteration domains give us a set of
2291 // constraints that need to hold for all cases where at least a single
2292 // statement iteration is executed in the whole scop. We now simplify the
2293 // assumed context under the assumption that such constraints hold and at
2294 // least a single statement iteration is executed. For cases where no
2295 // statement instances are executed, the assumptions we have taken about
2296 // the executed code do not matter and can be changed.
2297 //
2298 // WARNING: This only holds if the assumptions we have taken do not reduce
2299 // the set of statement instances that are executed. Otherwise we
2300 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002301 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002302 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002303 // performed. In such a case, modifying the run-time conditions and
2304 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002305 // to not be executed.
2306 //
2307 // Example:
2308 //
2309 // When delinearizing the following code:
2310 //
2311 // for (long i = 0; i < 100; i++)
2312 // for (long j = 0; j < m; j++)
2313 // A[i+p][j] = 1.0;
2314 //
2315 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002316 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002317 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002318 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002319 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002320}
2321
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002322struct MinMaxData {
2323 Scop::MinMaxVectorTy &MinMaxAccesses;
2324 Scop &S;
2325};
2326
Tobias Grosserc80d6972016-09-02 06:33:33 +00002327/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002328static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002329 auto Data = (struct MinMaxData *)User;
2330 Scop::MinMaxVectorTy *MinMaxAccesses = &Data->MinMaxAccesses;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002331 isl_pw_multi_aff *MinPMA, *MaxPMA;
2332 isl_pw_aff *LastDimAff;
2333 isl_aff *OneAff;
2334 unsigned Pos;
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002335 isl_ctx *Ctx = isl_set_get_ctx(Set);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002336
Johannes Doerfert6296d952016-04-22 11:38:19 +00002337 Set = isl_set_remove_divs(Set);
2338
Tobias Grosser90411a92017-02-16 19:11:33 +00002339 if (isl_set_n_basic_set(Set) >= MaxDisjunctsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002340 isl_set_free(Set);
2341 return isl_stat_error;
2342 }
2343
Johannes Doerfert9143d672014-09-27 11:02:39 +00002344 // Restrict the number of parameters involved in the access as the lexmin/
2345 // lexmax computation will take too long if this number is high.
2346 //
2347 // Experiments with a simple test case using an i7 4800MQ:
2348 //
2349 // #Parameters involved | Time (in sec)
2350 // 6 | 0.01
2351 // 7 | 0.04
2352 // 8 | 0.12
2353 // 9 | 0.40
2354 // 10 | 1.54
2355 // 11 | 6.78
2356 // 12 | 30.38
2357 //
2358 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2359 unsigned InvolvedParams = 0;
2360 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2361 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2362 InvolvedParams++;
2363
2364 if (InvolvedParams > RunTimeChecksMaxParameters) {
2365 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002366 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002367 }
2368 }
2369
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002370 {
2371 IslMaxOperationsGuard MaxOpGuard(isl_set_get_ctx(Set), OptComputeOut);
2372 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2373 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2374 }
2375
2376 if (isl_ctx_last_error(Ctx) == isl_error_quota) {
2377 MinPMA = isl_pw_multi_aff_free(MinPMA);
2378 MaxPMA = isl_pw_multi_aff_free(MaxPMA);
2379 Set = isl_set_free(Set);
2380 Data->S.invalidate(COMPLEXITY, DebugLoc());
2381 return isl_stat_error;
2382 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002383
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002384 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2385 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2386
Johannes Doerfertb164c792014-09-18 11:17:17 +00002387 // Adjust the last dimension of the maximal access by one as we want to
2388 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2389 // we test during code generation might now point after the end of the
2390 // allocated array but we will never dereference it anyway.
2391 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2392 "Assumed at least one output dimension");
2393 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2394 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2395 OneAff = isl_aff_zero_on_domain(
2396 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2397 OneAff = isl_aff_add_constant_si(OneAff, 1);
2398 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2399 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2400
2401 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2402
2403 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002404 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002405}
2406
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002407static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2408 isl_set *Domain = MA->getStatement()->getDomain();
2409 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2410 return isl_set_reset_tuple_id(Domain);
2411}
2412
Tobias Grosserc80d6972016-09-02 06:33:33 +00002413/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002414static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002415 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002416
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002417 struct MinMaxData Data = {MinMaxAccesses, S};
2418 Data.MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002419
2420 isl_union_set *Domains = S.getDomains();
2421 isl_union_map *Accesses = isl_union_map_empty(S.getParamSpace());
2422
2423 for (MemoryAccess *MA : AliasGroup)
2424 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2425
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002426 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2427 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002428 Locations = isl_union_set_coalesce(Locations);
2429 Locations = isl_union_set_detect_equalities(Locations);
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002430 bool Valid =
2431 (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess, &Data));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002432 isl_union_set_free(Locations);
2433 return Valid;
2434}
2435
Tobias Grosserc80d6972016-09-02 06:33:33 +00002436/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002437///
2438///{
2439
Tobias Grosserc80d6972016-09-02 06:33:33 +00002440/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002441static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2442 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2443 : RN->getNodeAs<BasicBlock>();
2444}
2445
Tobias Grosserc80d6972016-09-02 06:33:33 +00002446/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002447static inline BasicBlock *
2448getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002449 if (RN->isSubRegion()) {
2450 assert(idx == 0);
2451 return RN->getNodeAs<Region>()->getExit();
2452 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002453 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002454}
2455
Tobias Grosserc80d6972016-09-02 06:33:33 +00002456/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002457static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002458 if (!RN->isSubRegion()) {
2459 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2460 Loop *L = LI.getLoopFor(BB);
2461
2462 // Unreachable statements are not considered to belong to a LLVM loop, as
2463 // they are not part of an actual loop in the control flow graph.
2464 // Nevertheless, we handle certain unreachable statements that are common
2465 // when modeling run-time bounds checks as being part of the loop to be
2466 // able to model them and to later eliminate the run-time bounds checks.
2467 //
2468 // Specifically, for basic blocks that terminate in an unreachable and
2469 // where the immeditate predecessor is part of a loop, we assume these
2470 // basic blocks belong to the loop the predecessor belongs to. This
2471 // allows us to model the following code.
2472 //
2473 // for (i = 0; i < N; i++) {
2474 // if (i > 1024)
2475 // abort(); <- this abort might be translated to an
2476 // unreachable
2477 //
2478 // A[i] = ...
2479 // }
2480 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2481 L = LI.getLoopFor(BB->getPrevNode());
2482 return L;
2483 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002484
2485 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2486 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2487 while (L && NonAffineSubRegion->contains(L))
2488 L = L->getParentLoop();
2489 return L;
2490}
2491
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002492/// Get the number of blocks in @p L.
2493///
2494/// The number of blocks in a loop are the number of basic blocks actually
2495/// belonging to the loop, as well as all single basic blocks that the loop
2496/// exits to and which terminate in an unreachable instruction. We do not
2497/// allow such basic blocks in the exit of a scop, hence they belong to the
2498/// scop and represent run-time conditions which we want to model and
2499/// subsequently speculate away.
2500///
2501/// @see getRegionNodeLoop for additional details.
2502long getNumBlocksInLoop(Loop *L) {
2503 long NumBlocks = L->getNumBlocks();
2504 SmallVector<llvm::BasicBlock *, 4> ExitBlocks;
2505 L->getExitBlocks(ExitBlocks);
2506
2507 for (auto ExitBlock : ExitBlocks) {
2508 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2509 NumBlocks++;
2510 }
2511 return NumBlocks;
2512}
2513
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002514static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2515 if (!RN->isSubRegion())
2516 return 1;
2517
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002518 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002519 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002520}
2521
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002522static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2523 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002524 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002525 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002526 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002527 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002528 return true;
2529 return false;
2530}
2531
Johannes Doerfert96425c22015-08-30 21:13:53 +00002532///}
2533
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002534static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2535 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002536 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002537 isl_id *DimId =
2538 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2539 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2540}
2541
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002542__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002543 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002544}
2545
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002546__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002547 auto DIt = DomainMap.find(BB);
2548 if (DIt != DomainMap.end())
2549 return isl_set_copy(DIt->getSecond());
2550
2551 auto &RI = *R.getRegionInfo();
2552 auto *BBR = RI.getRegionFor(BB);
2553 while (BBR->getEntry() == BB)
2554 BBR = BBR->getParent();
2555 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002556}
2557
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002558bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002559
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002560 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002561 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002562 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2563 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002564 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002565
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002566 while (LD-- >= 0) {
2567 S = addDomainDimId(S, LD + 1, L);
2568 L = L->getParentLoop();
2569 }
2570
Johannes Doerferta3519512016-04-23 13:02:23 +00002571 // Initialize the invalid domain.
2572 auto *EntryStmt = getStmtFor(EntryBB);
2573 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2574
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002575 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002576
Johannes Doerfert432658d2016-01-26 11:01:41 +00002577 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002578 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002579
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002580 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002581 return false;
2582
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002583 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002584 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002585
2586 // Error blocks and blocks dominated by them have been assumed to never be
2587 // executed. Representing them in the Scop does not add any value. In fact,
2588 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002589 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002590 // will cause problems when building up a ScopStmt for them.
2591 // Furthermore, basic blocks dominated by error blocks may reference
2592 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002593 // can themselves not be constructed properly. To this end we will replace
2594 // the domains of error blocks and those only reachable via error blocks
2595 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002596 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002597 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002598 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002599 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002600
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002601 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002602}
2603
Tobias Grosserc80d6972016-09-02 06:33:33 +00002604/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002605/// to be compatible to domains constructed for loop @p NewL.
2606///
2607/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2608/// edge from @p OldL to @p NewL.
2609static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2610 __isl_take isl_set *Dom,
2611 Loop *OldL, Loop *NewL) {
2612
2613 // If the loops are the same there is nothing to do.
2614 if (NewL == OldL)
2615 return Dom;
2616
2617 int OldDepth = S.getRelativeLoopDepth(OldL);
2618 int NewDepth = S.getRelativeLoopDepth(NewL);
2619 // If both loops are non-affine loops there is nothing to do.
2620 if (OldDepth == -1 && NewDepth == -1)
2621 return Dom;
2622
2623 // Distinguish three cases:
2624 // 1) The depth is the same but the loops are not.
2625 // => One loop was left one was entered.
2626 // 2) The depth increased from OldL to NewL.
2627 // => One loop was entered, none was left.
2628 // 3) The depth decreased from OldL to NewL.
2629 // => Loops were left were difference of the depths defines how many.
2630 if (OldDepth == NewDepth) {
2631 assert(OldL->getParentLoop() == NewL->getParentLoop());
2632 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2633 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2634 Dom = addDomainDimId(Dom, NewDepth, NewL);
2635 } else if (OldDepth < NewDepth) {
2636 assert(OldDepth + 1 == NewDepth);
2637 auto &R = S.getRegion();
2638 (void)R;
2639 assert(NewL->getParentLoop() == OldL ||
2640 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2641 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2642 Dom = addDomainDimId(Dom, NewDepth, NewL);
2643 } else {
2644 assert(OldDepth > NewDepth);
2645 int Diff = OldDepth - NewDepth;
2646 int NumDim = isl_set_n_dim(Dom);
2647 assert(NumDim >= Diff);
2648 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2649 }
2650
2651 return Dom;
2652}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002653
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002654bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2655 LoopInfo &LI) {
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002656 ReversePostOrderTraversal<Region *> RTraversal(R);
2657 for (auto *RN : RTraversal) {
2658
2659 // Recurse for affine subregions but go on for basic blocks and non-affine
2660 // subregions.
2661 if (RN->isSubRegion()) {
2662 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002663 if (!isNonAffineSubRegion(SubRegion)) {
2664 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002665 continue;
2666 }
2667 }
2668
2669 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2670 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002671 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002672 isl_set *&Domain = DomainMap[BB];
2673 assert(Domain && "Cannot propagate a nullptr");
2674
Johannes Doerferta3519512016-04-23 13:02:23 +00002675 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002676 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002677 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002678
Johannes Doerferta3519512016-04-23 13:02:23 +00002679 if (!IsInvalidBlock) {
2680 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002681 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002682 isl_set_free(InvalidDomain);
2683 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002684 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2685 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2686 AS_RESTRICTION);
2687 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002688 }
2689
Johannes Doerferta3519512016-04-23 13:02:23 +00002690 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002691 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002692 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002693 }
2694
Johannes Doerferta3519512016-04-23 13:02:23 +00002695 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002696 auto *TI = BB->getTerminator();
2697 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2698 for (unsigned u = 0; u < NumSuccs; u++) {
2699 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002700 auto *SuccStmt = getStmtFor(SuccBB);
2701
2702 // Skip successors outside the SCoP.
2703 if (!SuccStmt)
2704 continue;
2705
Johannes Doerferte4459a22016-04-25 13:34:50 +00002706 // Skip backedges.
2707 if (DT.dominates(SuccBB, BB))
2708 continue;
2709
Michael Kruse55454072017-03-15 22:16:43 +00002710 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta3519512016-04-23 13:02:23 +00002711 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2712 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2713 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2714 SuccInvalidDomain =
2715 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2716 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2717 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2718 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002719
Michael Krusebc150122016-05-02 12:25:18 +00002720 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002721 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002722 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002723 continue;
2724
Johannes Doerferta3519512016-04-23 13:02:23 +00002725 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002726 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002727 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002728 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002729
2730 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002731 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002732
2733 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002734}
2735
Johannes Doerfert642594a2016-04-04 07:57:39 +00002736void Scop::propagateDomainConstraintsToRegionExit(
2737 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002738 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002739
2740 // Check if the block @p BB is the entry of a region. If so we propagate it's
2741 // domain to the exit block of the region. Otherwise we are done.
2742 auto *RI = R.getRegionInfo();
2743 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2744 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002745 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002746 return;
2747
Johannes Doerfert642594a2016-04-04 07:57:39 +00002748 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002749 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002750 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002751 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002752 SmallVector<BasicBlock *, 4> LatchBBs;
2753 BBLoop->getLoopLatches(LatchBBs);
2754 for (auto *LatchBB : LatchBBs)
2755 if (BB != LatchBB && BBReg->contains(LatchBB))
2756 return;
2757 L = L->getParentLoop();
2758 }
2759
2760 auto *Domain = DomainMap[BB];
2761 assert(Domain && "Cannot propagate a nullptr");
2762
Michael Kruse55454072017-03-15 22:16:43 +00002763 auto *ExitStmt = getStmtFor(ExitBB);
2764 auto *ExitBBLoop = ExitStmt->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002765
2766 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2767 // adjust the domain before we can propagate it.
2768 auto *AdjustedDomain =
2769 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2770 auto *&ExitDomain = DomainMap[ExitBB];
2771
2772 // If the exit domain is not yet created we set it otherwise we "add" the
2773 // current domain.
2774 ExitDomain =
2775 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2776
Johannes Doerferta3519512016-04-23 13:02:23 +00002777 // Initialize the invalid domain.
Johannes Doerferta3519512016-04-23 13:02:23 +00002778 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2779
Johannes Doerfert642594a2016-04-04 07:57:39 +00002780 FinishedExitBlocks.insert(ExitBB);
2781}
2782
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002783bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2784 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002785 // To create the domain for each block in R we iterate over all blocks and
2786 // subregions in R and propagate the conditions under which the current region
2787 // element is executed. To this end we iterate in reverse post order over R as
2788 // it ensures that we first visit all predecessors of a region node (either a
2789 // basic block or a subregion) before we visit the region node itself.
2790 // Initially, only the domain for the SCoP region entry block is set and from
2791 // there we propagate the current domain to all successors, however we add the
2792 // condition that the successor is actually executed next.
2793 // As we are only interested in non-loop carried constraints here we can
2794 // simply skip loop back edges.
2795
Johannes Doerfert642594a2016-04-04 07:57:39 +00002796 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002797 ReversePostOrderTraversal<Region *> RTraversal(R);
2798 for (auto *RN : RTraversal) {
2799
2800 // Recurse for affine subregions but go on for basic blocks and non-affine
2801 // subregions.
2802 if (RN->isSubRegion()) {
2803 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002804 if (!isNonAffineSubRegion(SubRegion)) {
2805 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002806 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002807 continue;
2808 }
2809 }
2810
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002811 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002812 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002813
Johannes Doerfert96425c22015-08-30 21:13:53 +00002814 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002815 TerminatorInst *TI = BB->getTerminator();
2816
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002817 if (isa<UnreachableInst>(TI))
2818 continue;
2819
Johannes Doerfertf5673802015-10-01 23:48:18 +00002820 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002821 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002822 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002823 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002824
Johannes Doerfert642594a2016-04-04 07:57:39 +00002825 auto *BBLoop = getRegionNodeLoop(RN, LI);
2826 // Propagate the domain from BB directly to blocks that have a superset
2827 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002828 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002829
2830 // If all successors of BB have been set a domain through the propagation
2831 // above we do not need to build condition sets but can just skip this
2832 // block. However, it is important to note that this is a local property
2833 // with regards to the region @p R. To this end FinishedExitBlocks is a
2834 // local variable.
2835 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2836 return FinishedExitBlocks.count(SuccBB);
2837 };
2838 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2839 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002840
2841 // Build the condition sets for the successor nodes of the current region
2842 // node. If it is a non-affine subregion we will always execute the single
2843 // exit node, hence the single entry node domain is the condition set. For
2844 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002845 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002846 if (RN->isSubRegion())
2847 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002848 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2849 ConditionSets))
2850 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002851
2852 // Now iterate over the successors and set their initial domain based on
2853 // their condition set. We skip back edges here and have to be careful when
2854 // we leave a loop not to keep constraints over a dimension that doesn't
2855 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002856 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002857 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002858 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002859 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002860
Johannes Doerfert535de032016-04-19 14:49:05 +00002861 auto *SuccStmt = getStmtFor(SuccBB);
2862 // Skip blocks outside the region.
2863 if (!SuccStmt) {
2864 isl_set_free(CondSet);
2865 continue;
2866 }
2867
Johannes Doerfert642594a2016-04-04 07:57:39 +00002868 // If we propagate the domain of some block to "SuccBB" we do not have to
2869 // adjust the domain.
2870 if (FinishedExitBlocks.count(SuccBB)) {
2871 isl_set_free(CondSet);
2872 continue;
2873 }
2874
Johannes Doerfert96425c22015-08-30 21:13:53 +00002875 // Skip back edges.
2876 if (DT.dominates(SuccBB, BB)) {
2877 isl_set_free(CondSet);
2878 continue;
2879 }
2880
Michael Kruse55454072017-03-15 22:16:43 +00002881 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002882 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002883
2884 // Set the domain for the successor or merge it with an existing domain in
2885 // case there are multiple paths (without loop back edges) to the
2886 // successor block.
2887 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002888
Johannes Doerferta3519512016-04-23 13:02:23 +00002889 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002890 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002891 } else {
2892 // Initialize the invalid domain.
2893 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2894 SuccDomain = CondSet;
2895 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002896
Tobias Grosser6d459c52017-05-23 04:26:28 +00002897 SuccDomain = isl_set_detect_equalities(SuccDomain);
2898
Michael Krusebc150122016-05-02 12:25:18 +00002899 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002900 // In case this happens we will clean up and bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002901 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002902 continue;
2903
2904 invalidate(COMPLEXITY, DebugLoc());
2905 while (++u < ConditionSets.size())
2906 isl_set_free(ConditionSets[u]);
2907 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002908 }
2909 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002910
2911 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002912}
2913
Michael Krused56b90a2016-09-01 09:03:27 +00002914__isl_give isl_set *
2915Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2916 __isl_keep isl_set *Domain,
2917 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002918 // If @p BB is the ScopEntry we are done
2919 if (R.getEntry() == BB)
2920 return isl_set_universe(isl_set_get_space(Domain));
2921
Johannes Doerfert642594a2016-04-04 07:57:39 +00002922 // The region info of this function.
2923 auto &RI = *R.getRegionInfo();
2924
Michael Kruse55454072017-03-15 22:16:43 +00002925 auto *BBLoop = getStmtFor(BB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002926
2927 // A domain to collect all predecessor domains, thus all conditions under
2928 // which the block is executed. To this end we start with the empty domain.
2929 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2930
2931 // Set of regions of which the entry block domain has been propagated to BB.
2932 // all predecessors inside any of the regions can be skipped.
2933 SmallSet<Region *, 8> PropagatedRegions;
2934
2935 for (auto *PredBB : predecessors(BB)) {
2936 // Skip backedges.
2937 if (DT.dominates(BB, PredBB))
2938 continue;
2939
2940 // If the predecessor is in a region we used for propagation we can skip it.
2941 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2942 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2943 PredBBInRegion)) {
2944 continue;
2945 }
2946
2947 // Check if there is a valid region we can use for propagation, thus look
2948 // for a region that contains the predecessor and has @p BB as exit block.
2949 auto *PredR = RI.getRegionFor(PredBB);
2950 while (PredR->getExit() != BB && !PredR->contains(BB))
2951 PredR->getParent();
2952
2953 // If a valid region for propagation was found use the entry of that region
2954 // for propagation, otherwise the PredBB directly.
2955 if (PredR->getExit() == BB) {
2956 PredBB = PredR->getEntry();
2957 PropagatedRegions.insert(PredR);
2958 }
2959
Johannes Doerfert41cda152016-04-08 10:32:26 +00002960 auto *PredBBDom = getDomainConditions(PredBB);
Michael Kruse55454072017-03-15 22:16:43 +00002961 auto *PredBBLoop = getStmtFor(PredBB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002962 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2963
2964 PredDom = isl_set_union(PredDom, PredBBDom);
2965 }
2966
2967 return PredDom;
2968}
2969
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002970bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2971 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002972 // Iterate over the region R and propagate the domain constrains from the
2973 // predecessors to the current node. In contrast to the
2974 // buildDomainsWithBranchConstraints function, this one will pull the domain
2975 // information from the predecessors instead of pushing it to the successors.
2976 // Additionally, we assume the domains to be already present in the domain
2977 // map here. However, we iterate again in reverse post order so we know all
2978 // predecessors have been visited before a block or non-affine subregion is
2979 // visited.
2980
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002981 ReversePostOrderTraversal<Region *> RTraversal(R);
2982 for (auto *RN : RTraversal) {
2983
2984 // Recurse for affine subregions but go on for basic blocks and non-affine
2985 // subregions.
2986 if (RN->isSubRegion()) {
2987 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002988 if (!isNonAffineSubRegion(SubRegion)) {
2989 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002990 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002991 continue;
2992 }
2993 }
2994
2995 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002996 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002997 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002998
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002999 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003000 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003001 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00003002 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003003
Johannes Doerfert642594a2016-04-04 07:57:39 +00003004 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00003005 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003006 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
3007 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003008 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00003009
3010 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003011}
3012
Tobias Grosserc80d6972016-09-02 06:33:33 +00003013/// Create a map to map from a given iteration to a subsequent iteration.
3014///
3015/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
3016/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003017/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00003018///
3019/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003020static __isl_give isl_map *
3021createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
3022 auto *MapSpace = isl_space_map_from_set(SetSpace);
3023 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00003024 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003025 if (u != Dim)
3026 NextIterationMap =
3027 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
3028 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
3029 C = isl_constraint_set_constant_si(C, 1);
3030 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
3031 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
3032 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
3033 return NextIterationMap;
3034}
3035
Johannes Doerfert297c7202016-05-10 13:06:42 +00003036bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003037 int LoopDepth = getRelativeLoopDepth(L);
3038 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003039
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003040 BasicBlock *HeaderBB = L->getHeader();
3041 assert(DomainMap.count(HeaderBB));
3042 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003043
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003044 isl_map *NextIterationMap =
3045 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003046
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003047 isl_set *UnionBackedgeCondition =
3048 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003049
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003050 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
3051 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003052
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003053 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003054
3055 // If the latch is only reachable via error statements we skip it.
3056 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
3057 if (!LatchBBDom)
3058 continue;
3059
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003060 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003061
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003062 TerminatorInst *TI = LatchBB->getTerminator();
3063 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00003064 assert(BI && "Only branch instructions allowed in loop latches");
3065
3066 if (BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003067 BackedgeCondition = isl_set_copy(LatchBBDom);
3068 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003069 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003070 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00003071 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
Michael Krusee1dc3872016-11-03 15:19:41 +00003072 ConditionSets)) {
3073 isl_map_free(NextIterationMap);
3074 isl_set_free(UnionBackedgeCondition);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003075 return false;
Michael Krusee1dc3872016-11-03 15:19:41 +00003076 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003077
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003078 // Free the non back edge condition set as we do not need it.
3079 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003080
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003081 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003082 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003083
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003084 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3085 assert(LatchLoopDepth >= LoopDepth);
3086 BackedgeCondition =
3087 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
3088 LatchLoopDepth - LoopDepth);
3089 UnionBackedgeCondition =
3090 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003091 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003092
3093 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
3094 for (int i = 0; i < LoopDepth; i++)
3095 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
3096
3097 isl_set *UnionBackedgeConditionComplement =
3098 isl_set_complement(UnionBackedgeCondition);
3099 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
3100 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
3101 UnionBackedgeConditionComplement =
3102 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
3103 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
3104 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
3105
3106 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
3107 HeaderBBDom = Parts.second;
3108
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003109 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3110 // the bounded assumptions to the context as they are already implied by the
3111 // <nsw> tag.
3112 if (Affinator.hasNSWAddRecForLoop(L)) {
3113 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003114 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003115 }
3116
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003117 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003118 recordAssumption(INFINITELOOP, UnboundedCtx,
3119 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003120 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003121}
3122
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003123MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003124 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003125
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003126 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003127 if (!PointerBaseInst)
3128 return nullptr;
3129
3130 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3131 if (!BasePtrStmt)
3132 return nullptr;
3133
3134 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3135}
3136
3137bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
3138 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003139 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
3140 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
3141 bool Hoistable = NHCtx != nullptr;
3142 isl_set_free(NHCtx);
3143 return !Hoistable;
3144 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003145
Tobias Grosserbe372d52017-02-09 10:11:58 +00003146 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003147 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003148 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003149 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003150
3151 return false;
3152}
3153
Johannes Doerfert5210da52016-06-02 11:06:54 +00003154bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003155 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003156 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003157
Johannes Doerfertcd195322016-11-17 21:41:08 +00003158 if (buildAliasGroups(AA)) {
3159 // Aliasing assumptions do not go through addAssumption but we still want to
3160 // collect statistics so we do it here explicitly.
3161 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003162 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003163 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003164 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003165
3166 // If a problem occurs while building the alias groups we need to delete
3167 // this SCoP and pretend it wasn't valid in the first place. To this end
3168 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003169 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003170
3171 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3172 << " could not be created as the number of parameters involved "
3173 "is too high. The SCoP will be "
3174 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3175 "the maximal number of parameters but be advised that the "
3176 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003177 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003178}
3179
Tobias Grosser889830b2017-02-09 23:12:22 +00003180std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003181Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003182 AliasSetTracker AST(AA);
3183
3184 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003185 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003186 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003187
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003188 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003189 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3190 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003191
3192 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003193 if (StmtDomainEmpty)
3194 continue;
3195
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003196 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003197 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003198 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003199 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003200 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003201 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003202 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003203 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003204 else
3205 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003206 AST.add(Acc);
3207 }
3208 }
3209
Tobias Grosser9edcf072017-01-16 14:07:57 +00003210 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003211 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003212 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003213 continue;
3214 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003215 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003216 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003217 if (AG.size() < 2)
3218 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003219 AliasGroups.push_back(std::move(AG));
3220 }
3221
Tobias Grosser9edcf072017-01-16 14:07:57 +00003222 return std::make_tuple(AliasGroups, HasWriteAccess);
3223}
3224
Tobias Grossere39f9122017-01-16 14:08:00 +00003225void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003226 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3227 AliasGroupTy NewAG;
3228 AliasGroupTy &AG = AliasGroups[u];
3229 AliasGroupTy::iterator AGI = AG.begin();
3230 isl_set *AGDomain = getAccessDomain(*AGI);
3231 while (AGI != AG.end()) {
3232 MemoryAccess *MA = *AGI;
3233 isl_set *MADomain = getAccessDomain(MA);
3234 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3235 NewAG.push_back(MA);
3236 AGI = AG.erase(AGI);
3237 isl_set_free(MADomain);
3238 } else {
3239 AGDomain = isl_set_union(AGDomain, MADomain);
3240 AGI++;
3241 }
3242 }
3243 if (NewAG.size() > 1)
3244 AliasGroups.push_back(std::move(NewAG));
3245 isl_set_free(AGDomain);
3246 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003247}
3248
3249bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3250 // To create sound alias checks we perform the following steps:
3251 // o) We partition each group into read only and non read only accesses.
3252 // o) For each group with more than one base pointer we then compute minimal
3253 // and maximal accesses to each array of a group in read only and non
3254 // read only partitions separately.
3255 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003256 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003257
3258 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3259
3260 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003261
Johannes Doerfert13771732014-10-01 12:40:46 +00003262 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003263 bool Valid = buildAliasGroup(AG, HasWriteAccess);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003264 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003265 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003266 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003267
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003268 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003269}
3270
Tobias Grosser77f32572017-01-16 15:49:07 +00003271bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003272 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003273 AliasGroupTy ReadOnlyAccesses;
3274 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003275 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003276 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003277
3278 auto &F = getFunction();
3279
3280 if (AliasGroup.size() < 2)
3281 return true;
3282
3283 for (MemoryAccess *Access : AliasGroup) {
3284 emitOptimizationRemarkAnalysis(
3285 F.getContext(), DEBUG_TYPE, F,
3286 Access->getAccessInstruction()->getDebugLoc(),
3287 "Possibly aliasing pointer, use restrict keyword.");
3288
Tobias Grosser889830b2017-02-09 23:12:22 +00003289 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3290 if (HasWriteAccess.count(Array)) {
3291 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003292 ReadWriteAccesses.push_back(Access);
3293 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003294 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003295 ReadOnlyAccesses.push_back(Access);
3296 }
3297 }
3298
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003299 // If there are no read-only pointers, and less than two read-write pointers,
3300 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003301 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003302 return true;
3303
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003304 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003305 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003306 return true;
3307
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003308 // For non-affine accesses, no alias check can be generated as we cannot
3309 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003310 for (MemoryAccess *MA : AliasGroup) {
3311 if (!MA->isAffine()) {
3312 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3313 return false;
3314 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003315 }
3316
3317 // Ensure that for all memory accesses for which we generate alias checks,
3318 // their base pointers are available.
3319 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003320 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3321 addRequiredInvariantLoad(
3322 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3323 }
3324
3325 MinMaxAliasGroups.emplace_back();
3326 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3327 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3328 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3329
3330 bool Valid;
3331
3332 Valid =
3333 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3334
3335 if (!Valid)
3336 return false;
3337
3338 // Bail out if the number of values we need to compare is too large.
3339 // This is important as the number of comparisons grows quadratically with
3340 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003341 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003342 RunTimeChecksMaxArraysPerGroup)
3343 return false;
3344
3345 Valid =
3346 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3347
3348 if (!Valid)
3349 return false;
3350
3351 return true;
3352}
3353
Tobias Grosserc80d6972016-09-02 06:33:33 +00003354/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003355static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003356 // Start with the smallest loop containing the entry and expand that
3357 // loop until it contains all blocks in the region. If there is a loop
3358 // containing all blocks in the region check if it is itself contained
3359 // and if so take the parent loop as it will be the smallest containing
3360 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003361 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003362 while (L) {
3363 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003364 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003365 AllContained &= L->contains(BB);
3366 if (AllContained)
3367 break;
3368 L = L->getParentLoop();
3369 }
3370
Johannes Doerfertef744432016-05-23 12:42:38 +00003371 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003372}
3373
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003374Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003375 ScopDetection::DetectionContext &DC)
Philip Pfaffe35bdcaf2017-05-15 13:43:01 +00003376 : SE(&ScalarEvolution), R(R), name(R.getNameStr()), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003377 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003378 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3379 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3380 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3381 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003382 if (IslOnErrorAbort)
3383 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003384 buildContext();
3385}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003386
Tobias Grosserbedef002016-12-02 08:10:56 +00003387void Scop::foldSizeConstantsToRight() {
3388 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3389
3390 for (auto Array : arrays()) {
3391 if (Array->getNumberOfDimensions() <= 1)
3392 continue;
3393
3394 isl_space *Space = Array->getSpace();
3395
3396 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3397
3398 if (!isl_union_set_contains(Accessed, Space)) {
3399 isl_space_free(Space);
3400 continue;
3401 }
3402
3403 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3404
3405 isl_map *Transform =
3406 isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3407
3408 std::vector<int> Int;
3409
3410 int Dims = isl_set_dim(Elements, isl_dim_set);
3411 for (int i = 0; i < Dims; i++) {
3412 isl_set *DimOnly =
3413 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3414 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3415 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3416
3417 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3418
3419 if (i == Dims - 1) {
3420 Int.push_back(1);
3421 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3422 isl_basic_set_free(DimHull);
3423 continue;
3424 }
3425
3426 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3427 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3428 isl_val *Val = isl_aff_get_denominator_val(Diff);
3429 isl_aff_free(Diff);
3430
3431 int ValInt = 1;
3432
3433 if (isl_val_is_int(Val))
3434 ValInt = isl_val_get_num_si(Val);
3435 isl_val_free(Val);
3436
3437 Int.push_back(ValInt);
3438
3439 isl_constraint *C = isl_constraint_alloc_equality(
3440 isl_local_space_from_space(isl_map_get_space(Transform)));
3441 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3442 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3443 Transform = isl_map_add_constraint(Transform, C);
3444 isl_basic_set_free(DimHull);
3445 continue;
3446 }
3447
3448 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3449 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3450
3451 int ValInt = 1;
3452 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3453 ValInt = 0;
3454 }
3455
3456 Int.push_back(ValInt);
3457 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3458 isl_basic_set_free(DimHull);
3459 isl_basic_set_free(ZeroSet);
3460 }
3461
3462 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3463
3464 if (!isl_set_is_subset(Elements, MappedElements)) {
3465 isl_set_free(Elements);
3466 isl_set_free(MappedElements);
3467 isl_map_free(Transform);
3468 continue;
3469 }
3470
3471 isl_set_free(MappedElements);
3472
3473 bool CanFold = true;
3474
3475 if (Int[0] <= 1)
3476 CanFold = false;
3477
3478 unsigned NumDims = Array->getNumberOfDimensions();
3479 for (unsigned i = 1; i < NumDims - 1; i++)
3480 if (Int[0] != Int[i] && Int[i])
3481 CanFold = false;
3482
3483 if (!CanFold) {
3484 isl_set_free(Elements);
3485 isl_map_free(Transform);
3486 continue;
3487 }
3488
Tobias Grosserbedef002016-12-02 08:10:56 +00003489 for (auto &Access : AccessFunctions)
3490 if (Access->getScopArrayInfo() == Array)
3491 Access->setAccessRelation(isl_map_apply_range(
3492 Access->getAccessRelation(), isl_map_copy(Transform)));
3493
3494 isl_map_free(Transform);
3495
3496 std::vector<const SCEV *> Sizes;
3497 for (unsigned i = 0; i < NumDims; i++) {
3498 auto Size = Array->getDimensionSize(i);
3499
3500 if (i == NumDims - 1)
3501 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3502 Sizes.push_back(Size);
3503 }
3504
3505 Array->updateSizes(Sizes, false /* CheckConsistency */);
3506
3507 isl_set_free(Elements);
3508 }
3509 isl_union_set_free(Accessed);
3510 return;
3511}
3512
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003513void Scop::markFortranArrays() {
3514 for (ScopStmt &Stmt : Stmts) {
3515 for (MemoryAccess *MemAcc : Stmt) {
3516 Value *FAD = MemAcc->getFortranArrayDescriptor();
3517 if (!FAD)
3518 continue;
3519
3520 // TODO: const_cast-ing to edit
3521 ScopArrayInfo *SAI =
3522 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3523 assert(SAI && "memory access into a Fortran array does not "
3524 "have an associated ScopArrayInfo");
3525 SAI->applyAndSetFAD(FAD);
3526 }
3527 }
3528}
3529
Tobias Grosser491b7992016-12-02 05:21:22 +00003530void Scop::finalizeAccesses() {
3531 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003532 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003533 foldAccessRelations();
3534 assumeNoOutOfBounds();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003535 markFortranArrays();
Tobias Grosser491b7992016-12-02 05:21:22 +00003536}
3537
Tobias Grosser75805372011-04-29 06:27:02 +00003538Scop::~Scop() {
3539 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003540 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003541 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003542 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003543
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003544 for (auto &It : ParameterIds)
3545 isl_id_free(It.second);
3546
Johannes Doerfert96425c22015-08-30 21:13:53 +00003547 for (auto It : DomainMap)
3548 isl_set_free(It.second);
3549
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003550 for (auto &AS : RecordedAssumptions)
3551 isl_set_free(AS.Set);
3552
Johannes Doerfertb164c792014-09-18 11:17:17 +00003553 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003554 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003555 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003556 isl_pw_multi_aff_free(MMA.first);
3557 isl_pw_multi_aff_free(MMA.second);
3558 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003559 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003560 isl_pw_multi_aff_free(MMA.first);
3561 isl_pw_multi_aff_free(MMA.second);
3562 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003563 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003564
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003565 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003566 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003567
3568 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003569 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003570 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003571 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003572 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003573 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003574 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003575}
3576
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003577void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003578 // Check all array accesses for each base pointer and find a (virtual) element
3579 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003580 for (ScopStmt &Stmt : *this)
3581 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003582 if (!Access->isArrayKind())
3583 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003584 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003585 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3586
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003587 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003588 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003589 unsigned DivisibleSize = Array->getElemSizeInBytes();
3590 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003591 while (!isDivisible(Subscript, DivisibleSize, *SE))
3592 DivisibleSize /= 2;
3593 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003594 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003595 }
3596
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003597 for (auto &Stmt : *this)
3598 for (auto &Access : Stmt)
3599 Access->updateDimensionality();
3600}
3601
Tobias Grosser491b7992016-12-02 05:21:22 +00003602void Scop::foldAccessRelations() {
3603 for (auto &Stmt : *this)
3604 for (auto &Access : Stmt)
3605 Access->foldAccessRelation();
3606}
3607
3608void Scop::assumeNoOutOfBounds() {
3609 for (auto &Stmt : *this)
3610 for (auto &Access : Stmt)
3611 Access->assumeNoOutOfBound();
3612}
3613
Michael Kruse977d38b2016-07-22 17:31:17 +00003614void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003615 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3616 ScopStmt &Stmt = *StmtIt;
3617
Johannes Doerfert26404542016-05-10 12:19:47 +00003618 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003619 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003620 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003621
Johannes Doerferteca9e892015-11-03 16:54:49 +00003622 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003623 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003624 bool OnlyRead = true;
3625 for (MemoryAccess *MA : Stmt) {
3626 if (MA->isRead())
3627 continue;
3628
3629 OnlyRead = false;
3630 break;
3631 }
3632
3633 RemoveStmt = OnlyRead;
3634 }
3635
Johannes Doerfert26404542016-05-10 12:19:47 +00003636 if (!RemoveStmt) {
3637 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003638 continue;
3639 }
3640
Johannes Doerfert26404542016-05-10 12:19:47 +00003641 // Remove the statement because it is unnecessary.
3642 if (Stmt.isRegionStmt())
3643 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3644 StmtMap.erase(BB);
3645 else
3646 StmtMap.erase(Stmt.getBasicBlock());
3647
3648 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003649 }
3650}
3651
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003652InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003653 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3654 if (!LInst)
3655 return nullptr;
3656
3657 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3658 LInst = cast<LoadInst>(Rep);
3659
Johannes Doerfert96e54712016-02-07 17:30:13 +00003660 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003661 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003662 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003663 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003664 continue;
3665
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003666 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003667 for (auto *MA : MAs)
3668 if (MA->getAccessInstruction() == Val)
3669 return &IAClass;
3670 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003671
3672 return nullptr;
3673}
3674
Tobias Grosserc80d6972016-09-02 06:33:33 +00003675/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003676static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003677 bool MAInvalidCtxIsEmpty,
3678 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003679 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3680 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3681 // TODO: We can provide more information for better but more expensive
3682 // results.
3683 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3684 LInst->getAlignment(), DL))
3685 return false;
3686
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003687 // If the location might be overwritten we do not hoist it unconditionally.
3688 //
3689 // TODO: This is probably to conservative.
3690 if (!NonHoistableCtxIsEmpty)
3691 return false;
3692
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003693 // If a dereferencable load is in a statement that is modeled precisely we can
3694 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003695 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003696 return true;
3697
3698 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003699 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003700 // statement domain.
3701 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3702 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3703 return false;
3704 return true;
3705}
3706
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003707void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003708
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003709 if (InvMAs.empty())
3710 return;
3711
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003712 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003713 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003714
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003715 // Get the context under which the statement is executed but remove the error
3716 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003717 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003718 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003719
Tobias Grosser90411a92017-02-16 19:11:33 +00003720 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003721 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003722 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3723 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003724 for (auto &InvMA : InvMAs)
3725 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003726 return;
3727 }
3728
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003729 // Project out all parameters that relate to loads in the statement. Otherwise
3730 // we could have cyclic dependences on the constraints under which the
3731 // hoisted loads are executed and we could not determine an order in which to
3732 // pre-load them. This happens because not only lower bounds are part of the
3733 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003734 for (auto &InvMA : InvMAs) {
3735 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003736 Instruction *AccInst = MA->getAccessInstruction();
3737 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003738 SetVector<Value *> Values;
3739 for (const SCEV *Parameter : Parameters) {
3740 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003741 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003742 if (!Values.count(AccInst))
3743 continue;
3744
3745 if (isl_id *ParamId = getIdForParam(Parameter)) {
3746 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003747 if (Dim >= 0)
3748 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003749 isl_id_free(ParamId);
3750 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003751 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003752 }
3753 }
3754
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003755 for (auto &InvMA : InvMAs) {
3756 auto *MA = InvMA.MA;
3757 auto *NHCtx = InvMA.NonHoistableCtx;
3758
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003759 // Check for another invariant access that accesses the same location as
3760 // MA and if found consolidate them. Otherwise create a new equivalence
3761 // class at the end of InvariantEquivClasses.
3762 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003763 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003764 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3765
Johannes Doerfert85676e32016-04-23 14:32:34 +00003766 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003767 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003768 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3769
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003770 isl_set *MACtx;
3771 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003772 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3773 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003774 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003775 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003776 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003777 } else {
3778 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003779 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003780 MACtx = isl_set_gist_params(MACtx, getContext());
3781 }
3782
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003783 bool Consolidated = false;
3784 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003785 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003786 continue;
3787
Johannes Doerfertdf880232016-03-03 12:26:58 +00003788 // If the pointer and the type is equal check if the access function wrt.
3789 // to the domain is equal too. It can happen that the domain fixes
3790 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003791 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003792 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003793 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003794 if (!MAs.empty()) {
3795 auto *LastMA = MAs.front();
3796
3797 auto *AR = isl_map_range(MA->getAccessRelation());
3798 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3799 bool SameAR = isl_set_is_equal(AR, LastAR);
3800 isl_set_free(AR);
3801 isl_set_free(LastAR);
3802
3803 if (!SameAR)
3804 continue;
3805 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003806
3807 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003808 MAs.push_front(MA);
3809
Johannes Doerfertdf880232016-03-03 12:26:58 +00003810 Consolidated = true;
3811
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003812 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003813 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003814 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003815 IAClassDomainCtx =
3816 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003817 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003818 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003819 break;
3820 }
3821
3822 if (Consolidated)
3823 continue;
3824
3825 // If we did not consolidate MA, thus did not find an equivalence class
3826 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003827 InvariantEquivClasses.emplace_back(
3828 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003829 }
3830
3831 isl_set_free(DomainCtx);
3832}
3833
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003834__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3835 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003836 // TODO: Loads that are not loop carried, hence are in a statement with
3837 // zero iterators, are by construction invariant, though we
3838 // currently "hoist" them anyway. This is necessary because we allow
3839 // them to be treated as parameters (e.g., in conditions) and our code
3840 // generation would otherwise use the old value.
3841
3842 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003843 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003844
Johannes Doerfertc9765462016-11-17 22:11:56 +00003845 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3846 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003847 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003848
3849 // Skip accesses that have an invariant base pointer which is defined but
3850 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3851 // returns a pointer that is used as a base address. However, as we want
3852 // to hoist indirect pointers, we allow the base pointer to be defined in
3853 // the region if it is also a memory access. Each ScopArrayInfo object
3854 // that has a base pointer origin has a base pointer that is loaded and
3855 // that it is invariant, thus it will be hoisted too. However, if there is
3856 // no base pointer origin we check that the base pointer is defined
3857 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003858 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003859 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003860 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003861
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003862 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003863 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003864
3865 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3866 Stmt.getNumIterators())) {
3867 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003868 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003869 }
3870
3871 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003872 isl_set *SafeToLoad;
3873
3874 auto &DL = getFunction().getParent()->getDataLayout();
3875 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
3876 DL)) {
3877 SafeToLoad =
3878 isl_set_universe(isl_space_range(isl_map_get_space(AccessRelation)));
3879 isl_map_free(AccessRelation);
3880 } else if (BB != LI->getParent()) {
3881 // Skip accesses in non-affine subregions as they might not be executed
3882 // under the same condition as the entry of the non-affine subregion.
3883 isl_map_free(AccessRelation);
3884 return nullptr;
3885 } else {
3886 SafeToLoad = isl_map_range(AccessRelation);
3887 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003888
3889 isl_union_map *Written = isl_union_map_intersect_range(
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003890 isl_union_map_copy(Writes), isl_union_set_from_set(SafeToLoad));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003891 auto *WrittenCtx = isl_union_map_params(Written);
3892 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003893
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003894 if (!IsWritten)
3895 return WrittenCtx;
3896
3897 WrittenCtx = isl_set_remove_divs(WrittenCtx);
Tobias Grosser90411a92017-02-16 19:11:33 +00003898 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctsInDomain;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003899 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3900 isl_set_free(WrittenCtx);
3901 return nullptr;
3902 }
3903
3904 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3905 AS_RESTRICTION);
3906 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003907}
3908
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003909void Scop::verifyInvariantLoads() {
3910 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003911 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003912 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003913 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003914 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003915 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3916 return;
3917 }
3918 }
3919}
3920
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003921void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003922 if (!PollyInvariantLoadHoisting)
3923 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003924
Tobias Grosser0865e7752016-02-29 07:29:42 +00003925 isl_union_map *Writes = getWrites();
3926 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003927 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003928
Tobias Grosser0865e7752016-02-29 07:29:42 +00003929 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003930 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3931 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003932
3933 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003934 for (auto InvMA : InvariantAccesses)
3935 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003936 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003937 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003938 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003939}
3940
Tobias Grosserf3adab42017-05-10 10:59:58 +00003941/// Find the canonical scop array info object for a set of invariant load
3942/// hoisted loads. The canonical array is the one that corresponds to the
3943/// first load in the list of accesses which is used as base pointer of a
3944/// scop array.
3945static const ScopArrayInfo *findCanonicalArray(Scop *S,
3946 MemoryAccessList &Accesses) {
3947 for (MemoryAccess *Access : Accesses) {
3948 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
3949 Access->getAccessInstruction(), MemoryKind::Array);
3950 if (CanonicalArray)
3951 return CanonicalArray;
3952 }
3953 return nullptr;
3954}
3955
3956/// Check if @p Array severs as base array in an invariant load.
3957static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
3958 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
3959 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
3960 if (Access2->getScopArrayInfo() == Array)
3961 return true;
3962 return false;
3963}
3964
3965/// Replace the base pointer arrays in all memory accesses referencing @p Old,
3966/// with a reference to @p New.
3967static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
3968 const ScopArrayInfo *New) {
3969 for (ScopStmt &Stmt : *S)
3970 for (MemoryAccess *Access : Stmt) {
3971 if (Access->getLatestScopArrayInfo() != Old)
3972 continue;
3973
3974 isl_id *Id = New->getBasePtrId();
3975 isl_map *Map = Access->getAccessRelation();
3976 Map = isl_map_set_tuple_id(Map, isl_dim_out, Id);
3977 Access->setAccessRelation(Map);
3978 }
3979}
3980
3981void Scop::canonicalizeDynamicBasePtrs() {
3982 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
3983 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
3984
3985 const ScopArrayInfo *CanonicalBasePtrSAI =
3986 findCanonicalArray(this, BasePtrAccesses);
3987
3988 if (!CanonicalBasePtrSAI)
3989 continue;
3990
3991 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
3992 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
3993 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
3994 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
3995 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
3996 continue;
3997
3998 // we currently do not canonicalize arrays where some accesses are
3999 // hoisted as invariant loads. If we would, we need to update the access
4000 // function of the invariant loads as well. However, as this is not a
4001 // very common situation, we leave this for now to avoid further
4002 // complexity increases.
4003 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
4004 continue;
4005
4006 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
4007 }
4008 }
4009}
4010
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004011const ScopArrayInfo *
4012Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
4013 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
4014 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004015 assert((BasePtr || BaseName) &&
4016 "BasePtr and BaseName can not be nullptr at the same time.");
4017 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
4018 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
4019 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004020 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004021 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00004022 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00004023 DL, this, BaseName));
4024 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004025 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004026 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00004027 // In case of mismatching array sizes, we bail out by setting the run-time
4028 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004029 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004030 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004031 }
Tobias Grosserab671442015-05-23 05:58:27 +00004032 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004033}
4034
Roman Gareevd7754a12016-07-30 09:25:51 +00004035const ScopArrayInfo *
4036Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
4037 const std::vector<unsigned> &Sizes) {
4038 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
4039 std::vector<const SCEV *> SCEVSizes;
4040
4041 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00004042 if (size)
4043 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
4044 else
4045 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00004046
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004047 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
4048 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00004049 return SAI;
4050}
4051
Tobias Grosserf3adab42017-05-10 10:59:58 +00004052const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
4053 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00004054 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004055 return SAI;
4056}
4057
4058const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
4059 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004060 assert(SAI && "No ScopArrayInfo available for this base pointer");
4061 return SAI;
4062}
4063
Tobias Grosser74394f02013-01-14 22:40:23 +00004064std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004065
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004066std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004067 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004068 return stringFromIslObj(AssumedContext);
4069}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004070
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004071std::string Scop::getInvalidContextStr() const {
4072 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004073}
Tobias Grosser75805372011-04-29 06:27:02 +00004074
4075std::string Scop::getNameStr() const {
4076 std::string ExitName, EntryName;
4077 raw_string_ostream ExitStr(ExitName);
4078 raw_string_ostream EntryStr(EntryName);
4079
Tobias Grosserf240b482014-01-09 10:42:15 +00004080 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004081 EntryStr.str();
4082
4083 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00004084 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004085 ExitStr.str();
4086 } else
4087 ExitName = "FunctionExit";
4088
4089 return EntryName + "---" + ExitName;
4090}
4091
Tobias Grosser74394f02013-01-14 22:40:23 +00004092__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00004093__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00004094 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00004095}
4096
Tobias Grossere86109f2013-10-29 21:05:49 +00004097__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004098 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00004099 return isl_set_copy(AssumedContext);
4100}
4101
Michael Krusef3091bf2017-03-17 13:09:52 +00004102bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004103 if (PollyProcessUnprofitable)
4104 return true;
4105
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004106 if (isEmpty())
4107 return false;
4108
4109 unsigned OptimizableStmtsOrLoops = 0;
4110 for (auto &Stmt : *this) {
4111 if (Stmt.getNumIterators() == 0)
4112 continue;
4113
4114 bool ContainsArrayAccs = false;
4115 bool ContainsScalarAccs = false;
4116 for (auto *MA : Stmt) {
4117 if (MA->isRead())
4118 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004119 ContainsArrayAccs |= MA->isLatestArrayKind();
4120 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004121 }
4122
Michael Krusef3091bf2017-03-17 13:09:52 +00004123 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004124 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4125 }
4126
4127 return OptimizableStmtsOrLoops > 1;
4128}
4129
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004130bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004131 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004132 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00004133 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4134 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4135 isl_set_is_subset(PositiveContext, NegativeContext));
4136 isl_set_free(PositiveContext);
4137 if (!IsFeasible) {
4138 isl_set_free(NegativeContext);
4139 return false;
4140 }
4141
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004142 auto *DomainContext = isl_union_set_params(getDomains());
4143 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00004144 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004145 isl_set_free(NegativeContext);
4146 isl_set_free(DomainContext);
4147
Johannes Doerfert43788c52015-08-20 05:58:56 +00004148 return IsFeasible;
4149}
4150
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004151static std::string toString(AssumptionKind Kind) {
4152 switch (Kind) {
4153 case ALIASING:
4154 return "No-aliasing";
4155 case INBOUNDS:
4156 return "Inbounds";
4157 case WRAPPING:
4158 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004159 case UNSIGNED:
4160 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004161 case COMPLEXITY:
4162 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004163 case PROFITABLE:
4164 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004165 case ERRORBLOCK:
4166 return "No-error";
4167 case INFINITELOOP:
4168 return "Finite loop";
4169 case INVARIANTLOAD:
4170 return "Invariant load";
4171 case DELINEARIZATION:
4172 return "Delinearization";
4173 }
4174 llvm_unreachable("Unknown AssumptionKind!");
4175}
4176
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004177bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4178 if (Sign == AS_ASSUMPTION) {
4179 if (isl_set_is_subset(Context, Set))
4180 return false;
4181
4182 if (isl_set_is_subset(AssumedContext, Set))
4183 return false;
4184 } else {
4185 if (isl_set_is_disjoint(Set, Context))
4186 return false;
4187
4188 if (isl_set_is_subset(Set, InvalidContext))
4189 return false;
4190 }
4191 return true;
4192}
4193
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004194bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
4195 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004196 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4197 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004198
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004199 // Do never emit trivial assumptions as they only clutter the output.
4200 if (!PollyRemarksMinimal) {
4201 isl_set *Univ = nullptr;
4202 if (Sign == AS_ASSUMPTION)
4203 Univ = isl_set_universe(isl_set_get_space(Set));
4204
4205 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4206 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4207 isl_set_free(Univ);
4208
4209 if (IsTrivial)
4210 return false;
4211 }
4212
Johannes Doerfertcd195322016-11-17 21:41:08 +00004213 switch (Kind) {
4214 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004215 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004216 break;
4217 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004218 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004219 break;
4220 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004221 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004222 break;
4223 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004224 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004225 break;
4226 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004227 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004228 break;
4229 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004230 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004231 break;
4232 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004233 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004234 break;
4235 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004236 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004237 break;
4238 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004239 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004240 break;
4241 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004242 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004243 break;
4244 }
4245
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004246 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004247 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4248 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004249 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004250 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004251}
4252
4253void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004254 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004255 // Simplify the assumptions/restrictions first.
4256 Set = isl_set_gist_params(Set, getContext());
4257
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004258 if (!trackAssumption(Kind, Set, Loc, Sign)) {
4259 isl_set_free(Set);
4260 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004261 }
4262
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004263 if (Sign == AS_ASSUMPTION) {
4264 AssumedContext = isl_set_intersect(AssumedContext, Set);
4265 AssumedContext = isl_set_coalesce(AssumedContext);
4266 } else {
4267 InvalidContext = isl_set_union(InvalidContext, Set);
4268 InvalidContext = isl_set_coalesce(InvalidContext);
4269 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004270}
4271
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004272void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004273 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004274 assert((isl_set_is_params(Set) || BB) &&
4275 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004276 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004277}
4278
4279void Scop::addRecordedAssumptions() {
4280 while (!RecordedAssumptions.empty()) {
4281 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004282
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004283 if (!AS.BB) {
4284 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
4285 continue;
4286 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004287
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004288 // If the domain was deleted the assumptions are void.
4289 isl_set *Dom = getDomainConditions(AS.BB);
4290 if (!Dom) {
4291 isl_set_free(AS.Set);
4292 continue;
4293 }
4294
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004295 // If a basic block was given use its domain to simplify the assumption.
4296 // In case of restrictions we know they only have to hold on the domain,
4297 // thus we can intersect them with the domain of the block. However, for
4298 // assumptions the domain has to imply them, thus:
4299 // _ _____
4300 // Dom => S <==> A v B <==> A - B
4301 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004302 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004303 // assumption.
4304 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004305 if (AS.Sign == AS_RESTRICTION)
4306 S = isl_set_params(isl_set_intersect(S, Dom));
4307 else /* (AS.Sign == AS_ASSUMPTION) */
4308 S = isl_set_params(isl_set_subtract(Dom, S));
4309
4310 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004311 }
4312}
4313
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004314void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004315 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004316}
4317
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004318__isl_give isl_set *Scop::getInvalidContext() const {
4319 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004320}
4321
Tobias Grosser75805372011-04-29 06:27:02 +00004322void Scop::printContext(raw_ostream &OS) const {
4323 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004324 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004325
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004326 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004327 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004328
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004329 OS.indent(4) << "Invalid Context:\n";
4330 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004331
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004332 unsigned Dim = 0;
4333 for (const SCEV *Parameter : Parameters)
4334 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004335}
4336
Johannes Doerfertb164c792014-09-18 11:17:17 +00004337void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004338 int noOfGroups = 0;
4339 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004340 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004341 noOfGroups += 1;
4342 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004343 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004344 }
4345
Tobias Grosserbb853c22015-07-25 12:31:03 +00004346 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004347 if (MinMaxAliasGroups.empty()) {
4348 OS.indent(8) << "n/a\n";
4349 return;
4350 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004351
Tobias Grosserbb853c22015-07-25 12:31:03 +00004352 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004353
4354 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004355 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004356 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004357 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004358 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4359 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004360 }
4361 OS << " ]]\n";
4362 }
4363
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004364 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004365 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004366 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004367 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004368 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4369 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004370 }
4371 OS << " ]]\n";
4372 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004373 }
4374}
4375
Tobias Grosser75805372011-04-29 06:27:02 +00004376void Scop::printStatements(raw_ostream &OS) const {
4377 OS << "Statements {\n";
4378
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004379 for (const ScopStmt &Stmt : *this)
4380 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00004381
4382 OS.indent(4) << "}\n";
4383}
4384
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004385void Scop::printArrayInfo(raw_ostream &OS) const {
4386 OS << "Arrays {\n";
4387
Tobias Grosserab671442015-05-23 05:58:27 +00004388 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004389 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004390
4391 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004392
4393 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4394
4395 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004396 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004397
4398 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004399}
4400
Tobias Grosser75805372011-04-29 06:27:02 +00004401void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004402 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004403 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004404 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004405 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004406 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004407 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004408 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004409 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004410 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004411 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004412 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4413 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004414 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004415 }
4416 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004417 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004418 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004419 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00004420 printStatements(OS.indent(4));
4421}
4422
4423void Scop::dump() const { print(dbgs()); }
4424
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004425isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004426
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004427__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4428 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004429 // First try to use the SCEVAffinator to generate a piecewise defined
4430 // affine function from @p E in the context of @p BB. If that tasks becomes to
4431 // complex the affinator might return a nullptr. In such a case we invalidate
4432 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004433 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004434 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004435 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004436 // TODO: We could use a heuristic and either use:
4437 // SCEVAffinator::takeNonNegativeAssumption
4438 // or
4439 // SCEVAffinator::interpretAsUnsigned
4440 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004441 if (NonNegative)
4442 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004443 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004444 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004445
4446 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
4447 invalidate(COMPLEXITY, DL);
4448 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004449}
4450
Tobias Grosser808cd692015-07-14 09:33:13 +00004451__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004452 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4453 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004454
Tobias Grosser808cd692015-07-14 09:33:13 +00004455 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004456 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004457
4458 return Domain;
4459}
4460
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004461__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4462 PWACtx PWAC = getPwAff(E, BB);
4463 isl_set_free(PWAC.second);
4464 return PWAC.first;
4465}
4466
Tobias Grossere5a35142015-11-12 14:07:09 +00004467__isl_give isl_union_map *
4468Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4469 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004470
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004471 for (ScopStmt &Stmt : *this) {
4472 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004473 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004474 continue;
4475
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004476 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004477 isl_map *AccessDomain = MA->getAccessRelation();
4478 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004479 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004480 }
4481 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004482 return isl_union_map_coalesce(Accesses);
4483}
4484
4485__isl_give isl_union_map *Scop::getMustWrites() {
4486 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004487}
4488
4489__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004490 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004491}
4492
Tobias Grosser37eb4222014-02-20 21:43:54 +00004493__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004494 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004495}
4496
4497__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004498 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004499}
4500
Tobias Grosser2ac23382015-11-12 14:07:13 +00004501__isl_give isl_union_map *Scop::getAccesses() {
4502 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4503}
4504
Roman Gareevb3224ad2016-09-14 06:26:09 +00004505// Check whether @p Node is an extension node.
4506//
4507// @return true if @p Node is an extension node.
4508isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4509 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4510 return isl_bool_error;
4511 else
4512 return isl_bool_true;
4513}
4514
4515bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4516 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4517 nullptr) == isl_stat_error;
4518}
4519
Tobias Grosser808cd692015-07-14 09:33:13 +00004520__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004521 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004522 if (containsExtensionNode(Tree)) {
4523 isl_schedule_free(Tree);
4524 return nullptr;
4525 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004526 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004527 isl_schedule_free(Tree);
4528 return S;
4529}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004530
Tobias Grosser808cd692015-07-14 09:33:13 +00004531__isl_give isl_schedule *Scop::getScheduleTree() const {
4532 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4533 getDomains());
4534}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004535
Tobias Grosser808cd692015-07-14 09:33:13 +00004536void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4537 auto *S = isl_schedule_from_domain(getDomains());
4538 S = isl_schedule_insert_partial_schedule(
4539 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4540 isl_schedule_free(Schedule);
4541 Schedule = S;
4542}
4543
4544void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4545 isl_schedule_free(Schedule);
4546 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004547}
4548
4549bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4550 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004551 for (ScopStmt &Stmt : *this) {
4552 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004553 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4554 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4555
4556 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4557 isl_union_set_free(StmtDomain);
4558 isl_union_set_free(NewStmtDomain);
4559 continue;
4560 }
4561
4562 Changed = true;
4563
4564 isl_union_set_free(StmtDomain);
4565 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4566
4567 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004568 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004569 isl_union_set_free(NewStmtDomain);
4570 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004571 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004572 }
4573 isl_union_set_free(Domain);
4574 return Changed;
4575}
4576
Tobias Grosser75805372011-04-29 06:27:02 +00004577ScalarEvolution *Scop::getSE() const { return SE; }
4578
Tobias Grosserc80d6972016-09-02 06:33:33 +00004579// Create an isl_multi_union_aff that defines an identity mapping from the
4580// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004581//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004582// # Example:
4583//
4584// Domain: { A[i,j]; B[i,j,k] }
4585// N: 1
4586//
4587// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4588//
4589// @param USet A union set describing the elements for which to generate a
4590// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004591// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004592// @returns A mapping from USet to its N-th dimension.
Tobias Grosser99320862017-05-26 17:22:03 +00004593static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) {
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004594 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004595 assert(USet);
Tobias Grosser99320862017-05-26 17:22:03 +00004596 assert(!USet.is_empty());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004597
Tobias Grosser99320862017-05-26 17:22:03 +00004598 auto Result = isl::union_pw_multi_aff::empty(USet.get_space());
Tobias Grosser808cd692015-07-14 09:33:13 +00004599
Tobias Grosser99320862017-05-26 17:22:03 +00004600 auto Lambda = [&Result, N](isl::set S) -> isl::stat {
4601 int Dim = S.dim(isl::dim::set);
4602 auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set,
4603 N, Dim - N);
4604 if (N > 1)
4605 PMA = PMA.drop_dims(isl::dim::out, 0, N - 1);
Tobias Grosser808cd692015-07-14 09:33:13 +00004606
Tobias Grosser99320862017-05-26 17:22:03 +00004607 Result = Result.add_pw_multi_aff(PMA);
4608 return isl::stat::ok;
4609 };
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004610
Tobias Grosser99320862017-05-26 17:22:03 +00004611 isl::stat Res = USet.foreach_set(Lambda);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004612 (void)Res;
4613
Tobias Grosser99320862017-05-26 17:22:03 +00004614 assert(Res == isl::stat::ok);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004615
Tobias Grosser99320862017-05-26 17:22:03 +00004616 return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result));
Tobias Grosser808cd692015-07-14 09:33:13 +00004617}
4618
Michael Kruse55454072017-03-15 22:16:43 +00004619void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004620 assert(BB && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004621 Stmts.emplace_back(*this, *BB, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004622 auto *Stmt = &Stmts.back();
4623 StmtMap[BB] = Stmt;
4624}
4625
Michael Kruse55454072017-03-15 22:16:43 +00004626void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004627 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004628 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004629 auto *Stmt = &Stmts.back();
4630 for (BasicBlock *BB : R->blocks())
Tobias Grosser808cd692015-07-14 09:33:13 +00004631 StmtMap[BB] = Stmt;
Tobias Grosser808cd692015-07-14 09:33:13 +00004632}
4633
Roman Gareevb3224ad2016-09-14 06:26:09 +00004634ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4635 __isl_take isl_map *TargetRel,
4636 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004637#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004638 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4639 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4640 assert(isl_set_is_subset(Domain, TargetDomain) &&
4641 "Target access not defined for complete statement domain");
4642 assert(isl_set_is_subset(Domain, SourceDomain) &&
4643 "Source access not defined for complete statement domain");
4644 isl_set_free(SourceDomain);
4645 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004646#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004647 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4648 CopyStmtsNum++;
4649 return &(Stmts.back());
4650}
4651
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004652void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004653 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004654 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004655 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004656 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4657 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004658}
4659
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004660/// To generate a schedule for the elements in a Region we traverse the Region
4661/// in reverse-post-order and add the contained RegionNodes in traversal order
4662/// to the schedule of the loop that is currently at the top of the LoopStack.
4663/// For loop-free codes, this results in a correct sequential ordering.
4664///
4665/// Example:
4666/// bb1(0)
4667/// / \.
4668/// bb2(1) bb3(2)
4669/// \ / \.
4670/// bb4(3) bb5(4)
4671/// \ /
4672/// bb6(5)
4673///
4674/// Including loops requires additional processing. Whenever a loop header is
4675/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4676/// from an empty schedule, we first process all RegionNodes that are within
4677/// this loop and complete the sequential schedule at this loop-level before
4678/// processing about any other nodes. To implement this
4679/// loop-nodes-first-processing, the reverse post-order traversal is
4680/// insufficient. Hence, we additionally check if the traversal yields
4681/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4682/// These region-nodes are then queue and only traverse after the all nodes
4683/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004684void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004685 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004686
4687 ReversePostOrderTraversal<Region *> RTraversal(R);
4688 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4689 std::deque<RegionNode *> DelayList;
4690 bool LastRNWaiting = false;
4691
4692 // Iterate over the region @p R in reverse post-order but queue
4693 // sub-regions/blocks iff they are not part of the last encountered but not
4694 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4695 // that we queued the last sub-region/block from the reverse post-order
4696 // iterator. If it is set we have to explore the next sub-region/block from
4697 // the iterator (if any) to guarantee progress. If it is not set we first try
4698 // the next queued sub-region/blocks.
4699 while (!WorkList.empty() || !DelayList.empty()) {
4700 RegionNode *RN;
4701
4702 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4703 RN = WorkList.front();
4704 WorkList.pop_front();
4705 LastRNWaiting = false;
4706 } else {
4707 RN = DelayList.front();
4708 DelayList.pop_front();
4709 }
4710
4711 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004712 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004713 L = OuterScopLoop;
4714
Tobias Grosser151ae322016-04-03 19:36:52 +00004715 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004716 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004717 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004718 LastRNWaiting = true;
4719 DelayList.push_back(RN);
4720 continue;
4721 }
4722 LoopStack.push_back({L, nullptr, 0});
4723 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004724 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004725 }
4726
4727 return;
4728}
4729
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004730void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004731
Tobias Grosser8362c262016-01-06 15:30:06 +00004732 if (RN->isSubRegion()) {
4733 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004734 if (!isNonAffineSubRegion(LocalRegion)) {
4735 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004736 return;
4737 }
4738 }
Michael Kruse046dde42015-08-10 13:01:57 +00004739
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004740 auto &LoopData = LoopStack.back();
4741 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004742
Michael Kruse6f7721f2016-02-24 22:08:19 +00004743 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004744 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4745 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004746 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004747 }
4748
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004749 // Check if we just processed the last node in this loop. If we did, finalize
4750 // the loop by:
4751 //
4752 // - adding new schedule dimensions
4753 // - folding the resulting schedule into the parent loop schedule
4754 // - dropping the loop schedule from the LoopStack.
4755 //
4756 // Then continue to check surrounding loops, which might also have been
4757 // completed by this node.
4758 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00004759 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004760 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004761 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004762
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004763 LoopStack.pop_back();
4764 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004765
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004766 if (Schedule) {
Tobias Grosser99320862017-05-26 17:22:03 +00004767 isl::union_set Domain = give(isl_schedule_get_domain(Schedule));
4768 isl::multi_union_pw_aff MUPA = mapToDimension(Domain, LoopStack.size());
4769 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA.release());
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004770 NextLoopData.Schedule =
4771 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004772 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004773
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004774 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4775 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004776 }
Tobias Grosser75805372011-04-29 06:27:02 +00004777}
4778
Michael Kruse6f7721f2016-02-24 22:08:19 +00004779ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004780 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004781 if (StmtMapIt == StmtMap.end())
4782 return nullptr;
4783 return StmtMapIt->second;
4784}
4785
Michael Kruse6f7721f2016-02-24 22:08:19 +00004786ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4787 if (RN->isSubRegion())
4788 return getStmtFor(RN->getNodeAs<Region>());
4789 return getStmtFor(RN->getNodeAs<BasicBlock>());
4790}
4791
4792ScopStmt *Scop::getStmtFor(Region *R) const {
4793 ScopStmt *Stmt = getStmtFor(R->getEntry());
4794 assert(!Stmt || Stmt->getRegion() == R);
4795 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004796}
4797
Johannes Doerfert96425c22015-08-30 21:13:53 +00004798int Scop::getRelativeLoopDepth(const Loop *L) const {
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00004799 if (!L || !R.contains(L))
Johannes Doerfert96425c22015-08-30 21:13:53 +00004800 return -1;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00004801 // outermostLoopInRegion always returns nullptr for top level regions
4802 if (R.isTopLevelRegion()) {
4803 // LoopInfo's depths start at 1, we start at 0
4804 return L->getLoopDepth() - 1;
4805 } else {
4806 Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
4807 assert(OuterLoop);
4808 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4809 }
Johannes Doerfertd020b772015-08-27 06:53:52 +00004810}
4811
Roman Gareevd7754a12016-07-30 09:25:51 +00004812ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4813 for (auto &SAI : arrays()) {
4814 if (SAI->getName() == BaseName)
4815 return SAI;
4816 }
4817 return nullptr;
4818}
4819
Johannes Doerfert99191c72016-05-31 09:41:04 +00004820//===----------------------------------------------------------------------===//
4821void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4822 AU.addRequired<LoopInfoWrapperPass>();
4823 AU.addRequired<RegionInfoPass>();
4824 AU.addRequired<DominatorTreeWrapperPass>();
4825 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004826 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004827 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004828 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004829 AU.setPreservesAll();
4830}
4831
Tobias Grossercd01a362017-02-17 08:12:36 +00004832void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
4833 NumLoopsInScop += Stats.NumLoops;
4834 MaxNumLoopsInScop =
4835 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
4836
Tobias Grossercd01a362017-02-17 08:12:36 +00004837 if (Stats.MaxDepth == 1)
4838 NumScopsDepthOne++;
4839 else if (Stats.MaxDepth == 2)
4840 NumScopsDepthTwo++;
4841 else if (Stats.MaxDepth == 3)
4842 NumScopsDepthThree++;
4843 else if (Stats.MaxDepth == 4)
4844 NumScopsDepthFour++;
4845 else if (Stats.MaxDepth == 5)
4846 NumScopsDepthFive++;
4847 else
4848 NumScopsDepthLarger++;
4849}
4850
Johannes Doerfert99191c72016-05-31 09:41:04 +00004851bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004852 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004853
4854 if (!SD.isMaxRegionInScop(*R))
4855 return false;
4856
4857 Function *F = R->getEntry()->getParent();
4858 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4859 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4860 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4861 auto const &DL = F->getParent()->getDataLayout();
4862 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004863 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004864
Michael Kruse89b1f942017-03-17 13:56:53 +00004865 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004866 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00004867
4868 if (S) {
4869 ScopDetection::LoopStats Stats =
4870 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
4871 updateLoopCountStatistic(Stats);
4872 }
4873
Tobias Grosser75805372011-04-29 06:27:02 +00004874 return false;
4875}
4876
Johannes Doerfert99191c72016-05-31 09:41:04 +00004877void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004878 if (S)
4879 S->print(OS);
4880 else
4881 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004882}
Tobias Grosser75805372011-04-29 06:27:02 +00004883
Johannes Doerfert99191c72016-05-31 09:41:04 +00004884char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004885
Johannes Doerfert99191c72016-05-31 09:41:04 +00004886Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4887
4888INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004889 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004890 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004891INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00004892INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004893INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004894INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004895INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004896INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004897INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004898INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004899 "Polly - Create polyhedral description of Scops", false,
4900 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004901
4902//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00004903ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
4904 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
4905 AssumptionCache &AC) {
4906 /// Create polyhedral descripton of scops for all the valid regions of a
4907 /// function.
4908 for (auto &It : SD) {
4909 Region *R = const_cast<Region *>(It);
4910 if (!SD.isMaxRegionInScop(*R))
4911 continue;
4912
4913 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4914 std::unique_ptr<Scop> S = SB.getScop();
4915 if (!S)
4916 continue;
4917 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
4918 assert(Inserted && "Building Scop for the same region twice!");
4919 (void)Inserted;
4920 }
4921}
4922
4923AnalysisKey ScopInfoAnalysis::Key;
4924
4925ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
4926 FunctionAnalysisManager &FAM) {
4927 auto &SD = FAM.getResult<ScopAnalysis>(F);
4928 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
4929 auto &LI = FAM.getResult<LoopAnalysis>(F);
4930 auto &AA = FAM.getResult<AAManager>(F);
4931 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
4932 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
4933 auto &DL = F.getParent()->getDataLayout();
4934 return {DL, SD, SE, LI, AA, DT, AC};
4935}
4936
4937PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
4938 FunctionAnalysisManager &FAM) {
4939 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
4940 for (auto &It : SI) {
4941 if (It.second)
4942 It.second->print(Stream);
4943 else
4944 Stream << "Invalid Scop!\n";
4945 }
4946 return PreservedAnalyses::all();
4947}
4948
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004949void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4950 AU.addRequired<LoopInfoWrapperPass>();
4951 AU.addRequired<RegionInfoPass>();
4952 AU.addRequired<DominatorTreeWrapperPass>();
4953 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004954 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004955 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004956 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004957 AU.setPreservesAll();
4958}
4959
4960bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004961 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004962 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4963 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4964 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4965 auto const &DL = F.getParent()->getDataLayout();
4966 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004967 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004968
Philip Pfaffe838e0882017-05-15 12:55:14 +00004969 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004970 return false;
4971}
4972
4973void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00004974 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004975 if (It.second)
4976 It.second->print(OS);
4977 else
4978 OS << "Invalid Scop!\n";
4979 }
4980}
4981
4982char ScopInfoWrapperPass::ID = 0;
4983
4984Pass *polly::createScopInfoWrapperPassPass() {
4985 return new ScopInfoWrapperPass();
4986}
4987
4988INITIALIZE_PASS_BEGIN(
4989 ScopInfoWrapperPass, "polly-function-scops",
4990 "Polly - Create polyhedral description of all Scops of a function", false,
4991 false);
4992INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00004993INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004994INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4995INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4996INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004997INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004998INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4999INITIALIZE_PASS_END(
5000 ScopInfoWrapperPass, "polly-function-scops",
5001 "Polly - Create polyhedral description of all Scops of a function", false,
5002 false)