blob: 88206f04252fe32232b42acb42617a8a5a4e7b5d [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 Grosser1eeedf42017-07-20 19:55:19 +000097// The maximal number of dimensions we allow during invariant load construction.
98// More complex access ranges will result in very high compile time and are also
99// unlikely to result in good code. This value is very high and should only
100// trigger for corner cases (e.g., the "dct_luma" function in h264, SPEC2006).
101static int const MaxDimensionsInAccessRange = 9;
102
Tobias Grosser97715842017-05-19 04:01:52 +0000103static cl::opt<int>
104 OptComputeOut("polly-analysis-computeout",
105 cl::desc("Bound the scop analysis by a maximal amount of "
106 "computational steps (0 means no bound)"),
Tobias Grosser57a1d362017-06-23 08:05:27 +0000107 cl::Hidden, cl::init(800000), cl::ZeroOrMore,
Tobias Grosser97715842017-05-19 04:01:52 +0000108 cl::cat(PollyCategory));
Tobias Grosser45e9fd12017-05-19 03:45:00 +0000109
Johannes Doerfert2f705842016-04-12 16:09:44 +0000110static cl::opt<bool> PollyRemarksMinimal(
111 "polly-remarks-minimal",
112 cl::desc("Do not emit remarks about assumptions that are known"),
113 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
114
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +0000115// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000116// operations can overflow easily. Additive reductions and bit operations
117// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +0000118static cl::opt<bool> DisableMultiplicativeReductions(
119 "polly-disable-multiplicative-reductions",
120 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
121 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000122
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +0000123static cl::opt<int> RunTimeChecksMaxAccessDisjuncts(
124 "polly-rtc-max-array-disjuncts",
125 cl::desc("The maximal number of disjunts allowed in memory accesses to "
126 "to build RTCs."),
127 cl::Hidden, cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
128
Johannes Doerfert9143d672014-09-27 11:02:39 +0000129static cl::opt<unsigned> RunTimeChecksMaxParameters(
130 "polly-rtc-max-parameters",
131 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
132 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
133
Tobias Grosser71500722015-03-28 15:11:14 +0000134static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
135 "polly-rtc-max-arrays-per-group",
136 cl::desc("The maximal number of arrays to compare in each alias group."),
137 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000138
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000139static cl::opt<std::string> UserContextStr(
140 "polly-context", cl::value_desc("isl parameter set"),
141 cl::desc("Provide additional constraints on the context parameters"),
142 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000143
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000144static cl::opt<bool> DetectReductions("polly-detect-reductions",
145 cl::desc("Detect and exploit reductions"),
146 cl::Hidden, cl::ZeroOrMore,
147 cl::init(true), cl::cat(PollyCategory));
148
Tobias Grosser2937b592016-04-29 11:43:20 +0000149static cl::opt<bool>
150 IslOnErrorAbort("polly-on-isl-error-abort",
151 cl::desc("Abort if an isl error is encountered"),
152 cl::init(true), cl::cat(PollyCategory));
153
Tobias Grosserd7c49752017-02-28 09:45:54 +0000154static cl::opt<bool> PollyPreciseInbounds(
155 "polly-precise-inbounds",
156 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
157 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
158
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000159static cl::opt<bool>
160 PollyIgnoreInbounds("polly-ignore-inbounds",
161 cl::desc("Do not take inbounds assumptions at all"),
162 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
163
Tobias Grosser5842dee2017-03-17 13:00:53 +0000164static cl::opt<bool> PollyIgnoreParamBounds(
165 "polly-ignore-parameter-bounds",
166 cl::desc(
167 "Do not add parameter bounds and do no gist simplify sets accordingly"),
168 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
169
Tobias Grosserc2f15102017-03-01 21:11:27 +0000170static cl::opt<bool> PollyPreciseFoldAccesses(
171 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000172 cl::desc("Fold memory accesses to model more possible delinearizations "
173 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000174 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000175
Michael Kruse5ae08c02017-05-06 14:03:58 +0000176bool polly::UseInstructionNames;
177static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000178 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000179 cl::desc("Use LLVM-IR names when deriving statement names"),
180 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
181 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000182
Tobias Grosserd5fcbef2017-05-27 04:40:18 +0000183static cl::opt<bool> PollyPrintInstructions(
184 "polly-print-instructions", cl::desc("Output instructions per ScopStmt"),
185 cl::Hidden, cl::Optional, cl::init(false), cl::cat(PollyCategory));
186
Michael Kruse7bf39442015-09-10 12:46:52 +0000187//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000188
Michael Kruse046dde42015-08-10 13:01:57 +0000189// Create a sequence of two schedules. Either argument may be null and is
190// interpreted as the empty schedule. Can also return null if both schedules are
191// empty.
192static __isl_give isl_schedule *
193combineInSequence(__isl_take isl_schedule *Prev,
194 __isl_take isl_schedule *Succ) {
195 if (!Prev)
196 return Succ;
197 if (!Succ)
198 return Prev;
199
200 return isl_schedule_sequence(Prev, Succ);
201}
202
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000203static isl::set addRangeBoundsToSet(isl::set S, const ConstantRange &Range,
204 int dim, isl::dim type) {
205 isl::val V;
206 isl::ctx Ctx = S.get_ctx();
Johannes Doerferte7044942015-02-24 11:58:30 +0000207
Tobias Grosser3281f602017-02-16 18:39:14 +0000208 // The upper and lower bound for a parameter value is derived either from
209 // the data type of the parameter or from the - possibly more restrictive -
210 // range metadata.
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000211 V = valFromAPInt(Ctx.get(), Range.getSignedMin(), true);
212 S = S.lower_bound_val(type, dim, V);
213 V = valFromAPInt(Ctx.get(), Range.getSignedMax(), true);
214 S = S.upper_bound_val(type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000215
Tobias Grosser3281f602017-02-16 18:39:14 +0000216 if (Range.isFullSet())
217 return S;
218
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000219 if (isl_set_n_basic_set(S.get()) > MaxDisjunctsInContext)
Tobias Grosserc8a82762017-02-16 19:11:25 +0000220 return S;
221
Tobias Grosser3281f602017-02-16 18:39:14 +0000222 // In case of signed wrapping, we can refine the set of valid values by
223 // excluding the part not covered by the wrapping range.
224 if (Range.isSignWrappedSet()) {
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000225 V = valFromAPInt(Ctx.get(), Range.getLower(), true);
226 isl::set SLB = S.lower_bound_val(type, dim, V);
Tobias Grosser3281f602017-02-16 18:39:14 +0000227
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000228 V = valFromAPInt(Ctx.get(), Range.getUpper(), true);
229 V = V.sub_ui(1);
230 isl::set SUB = S.upper_bound_val(type, dim, V);
231 S = SLB.unite(SUB);
Tobias Grosser3281f602017-02-16 18:39:14 +0000232 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000233
Tobias Grosser3281f602017-02-16 18:39:14 +0000234 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000235}
236
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000237static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
238 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
239 if (!BasePtrLI)
240 return nullptr;
241
Johannes Doerfert952b5302016-05-23 12:40:48 +0000242 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000243 return nullptr;
244
245 ScalarEvolution &SE = *S->getSE();
246
247 auto *OriginBaseSCEV =
248 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
249 if (!OriginBaseSCEV)
250 return nullptr;
251
252 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
253 if (!OriginBaseSCEVUnknown)
254 return nullptr;
255
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000256 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000257 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000258}
259
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000260ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000261 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000262 const DataLayout &DL, Scop *S,
263 const char *BaseName)
Michael Kruseb738ffa2017-06-28 13:02:43 +0000264 : BasePtr(BasePtr), ElementType(ElementType), IsOnHeap(false), Kind(Kind),
265 DL(DL), S(*S), FAD(nullptr) {
Tobias Grosser92245222015-07-28 14:53:44 +0000266 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000267 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000268 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
269 Kind == MemoryKind::PHI ? "__phi" : "",
270 UseInstructionNames);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000271 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000272
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000273 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000274
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000275 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000276 BasePtrOriginSAI = nullptr;
277 return;
278 }
279
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000280 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
281 if (BasePtrOriginSAI)
282 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000283}
284
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000285__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000286 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000287 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
288 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
289 return Space;
290}
291
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000292bool ScopArrayInfo::isReadOnly() {
Tobias Grosser2ade9862017-05-23 06:41:04 +0000293 isl::union_set WriteSet = give(S.getWrites()).range();
294 isl::space Space = give(getSpace());
295 WriteSet = WriteSet.extract_set(Space);
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000296
Tobias Grosser2ade9862017-05-23 06:41:04 +0000297 return bool(WriteSet.is_empty());
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000298}
299
Tobias Grosserf3adab42017-05-10 10:59:58 +0000300bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
301 if (Array->getElementType() != getElementType())
302 return false;
303
304 if (Array->getNumberOfDimensions() != getNumberOfDimensions())
305 return false;
306
307 for (unsigned i = 0; i < getNumberOfDimensions(); i++)
308 if (Array->getDimensionSize(i) != getDimensionSize(i))
309 return false;
310
311 return true;
312}
313
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000314void ScopArrayInfo::updateElementType(Type *NewElementType) {
315 if (NewElementType == ElementType)
316 return;
317
Tobias Grosserd840fc72016-02-04 13:18:42 +0000318 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
319 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
320
Johannes Doerferta7920982016-02-25 14:08:48 +0000321 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000322 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000323
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000324 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
325 ElementType = NewElementType;
326 } else {
327 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
328 ElementType = IntegerType::get(ElementType->getContext(), GCD);
329 }
330}
331
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000332/// Make the ScopArrayInfo model a Fortran Array
333void ScopArrayInfo::applyAndSetFAD(Value *FAD) {
334 assert(FAD && "got invalid Fortran array descriptor");
335 if (this->FAD) {
336 assert(this->FAD == FAD &&
337 "receiving different array descriptors for same array");
338 return;
339 }
340
341 assert(DimensionSizesPw.size() > 0 && !DimensionSizesPw[0]);
342 assert(!this->FAD);
343 this->FAD = FAD;
344
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000345 isl::space Space(S.getIslCtx(), 1, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000346
347 std::string param_name = getName();
348 param_name += "_fortranarr_size";
349 // TODO: see if we need to add `this` as the id user pointer
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000350 isl::id IdPwAff = isl::id::alloc(S.getIslCtx(), param_name.c_str(), nullptr);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000351
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000352 Space = Space.set_dim_id(isl::dim::param, 0, IdPwAff);
353 isl::pw_aff PwAff =
354 isl::aff::var_on_domain(isl::local_space(Space), isl::dim::param, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000355
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000356 DimensionSizesPw[0] = PwAff.release();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000357}
358
Tobias Grosserbedef002016-12-02 08:10:56 +0000359bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
360 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000361 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
362 int ExtraDimsNew = NewSizes.size() - SharedDims;
363 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000364
Tobias Grosserbedef002016-12-02 08:10:56 +0000365 if (CheckConsistency) {
366 for (int i = 0; i < SharedDims; i++) {
367 auto *NewSize = NewSizes[i + ExtraDimsNew];
368 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
369 if (NewSize && KnownSize && NewSize != KnownSize)
370 return false;
371 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000372
Tobias Grosserbedef002016-12-02 08:10:56 +0000373 if (DimensionSizes.size() >= NewSizes.size())
374 return true;
375 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000376
377 DimensionSizes.clear();
378 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
379 NewSizes.end());
380 for (isl_pw_aff *Size : DimensionSizesPw)
381 isl_pw_aff_free(Size);
382 DimensionSizesPw.clear();
383 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000384 if (!Expr) {
385 DimensionSizesPw.push_back(nullptr);
386 continue;
387 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000388 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000389 DimensionSizesPw.push_back(Size);
390 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000391 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000392}
393
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000394ScopArrayInfo::~ScopArrayInfo() {
395 isl_id_free(Id);
396 for (isl_pw_aff *Size : DimensionSizesPw)
397 isl_pw_aff_free(Size);
398}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000399
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000400std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
401
402int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000403 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000404}
405
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000406__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
407 return isl_id_copy(Id);
408}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000409
410void ScopArrayInfo::dump() const { print(errs()); }
411
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000412void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000413 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000414 unsigned u = 0;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000415 // If this is a Fortran array, then we can print the outermost dimension
416 // as a isl_pw_aff even though there is no SCEV information.
417 bool IsOutermostSizeKnown = SizeAsPwAff && FAD;
418
419 if (!IsOutermostSizeKnown && getNumberOfDimensions() > 0 &&
420 !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000421 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000422 u++;
423 }
424 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000425 OS << "[";
426
Tobias Grosser26253842015-11-10 14:24:21 +0000427 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000428 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000429 OS << " " << Size << " ";
430 isl_pw_aff_free(Size);
431 } else {
432 OS << *getDimensionSize(u);
433 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000434
435 OS << "]";
436 }
437
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000438 OS << ";";
439
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000440 if (BasePtrOriginSAI)
441 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
442
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000443 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000444}
445
446const ScopArrayInfo *
447ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
448 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
449 assert(Id && "Output dimension didn't have an ID");
450 return getFromId(Id);
451}
452
Michael Krused56b90a2016-09-01 09:03:27 +0000453const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000454 void *User = isl_id_get_user(Id);
455 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
456 isl_id_free(Id);
457 return SAI;
458}
459
Michael Kruse3b425ff2016-04-11 14:34:08 +0000460void MemoryAccess::wrapConstantDimensions() {
461 auto *SAI = getScopArrayInfo();
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000462 isl::space ArraySpace = give(SAI->getSpace());
463 isl::ctx Ctx = ArraySpace.get_ctx();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000464 unsigned DimsArray = SAI->getNumberOfDimensions();
465
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000466 isl::multi_aff DivModAff = isl::multi_aff::identity(
467 ArraySpace.map_from_domain_and_range(ArraySpace));
468 isl::local_space LArraySpace = isl::local_space(ArraySpace);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000469
470 // Begin with last dimension, to iteratively carry into higher dimensions.
471 for (int i = DimsArray - 1; i > 0; i--) {
472 auto *DimSize = SAI->getDimensionSize(i);
473 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
474
475 // This transformation is not applicable to dimensions with dynamic size.
476 if (!DimSizeCst)
477 continue;
478
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000479 // This transformation is not applicable to dimensions of size zero.
480 if (DimSize->isZero())
481 continue;
482
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000483 isl::val DimSizeVal =
484 valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
485 isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
486 isl::aff PrevVar =
487 isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000488
489 // Compute: index % size
490 // Modulo must apply in the divide of the previous iteration, if any.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000491 isl::aff Modulo = Var.mod_val(DimSizeVal);
492 Modulo = Modulo.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000493
494 // Compute: floor(index / size)
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000495 isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
496 Divide = Divide.floor();
497 Divide = Divide.add(PrevVar);
498 Divide = Divide.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000499
500 // Apply Modulo and Divide.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000501 DivModAff = DivModAff.set_aff(i, Modulo);
502 DivModAff = DivModAff.set_aff(i - 1, Divide);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000503 }
504
505 // Apply all modulo/divides on the accesses.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000506 isl::map Relation = give(AccessRelation);
507 Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
508 Relation = Relation.detect_equalities();
509 AccessRelation = Relation.release();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000510}
511
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000512void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000513 auto *SAI = getScopArrayInfo();
Tobias Grosser7be82452017-05-21 20:38:33 +0000514 isl::space ArraySpace = give(SAI->getSpace());
515 isl::space AccessSpace = give(isl_map_get_space(AccessRelation)).range();
516 isl::ctx Ctx = ArraySpace.get_ctx();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000517
Tobias Grosser7be82452017-05-21 20:38:33 +0000518 auto DimsArray = ArraySpace.dim(isl::dim::set);
519 auto DimsAccess = AccessSpace.dim(isl::dim::set);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000520 auto DimsMissing = DimsArray - DimsAccess;
521
Michael Kruse375cb5f2016-02-24 22:08:24 +0000522 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000523 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000524 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000525 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000526
Tobias Grosser7be82452017-05-21 20:38:33 +0000527 isl::map Map = isl::map::from_domain_and_range(
528 isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000529
530 for (unsigned i = 0; i < DimsMissing; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000531 Map = Map.fix_si(isl::dim::out, i, 0);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000532
533 for (unsigned i = DimsMissing; i < DimsArray; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000534 Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000535
Tobias Grosser7be82452017-05-21 20:38:33 +0000536 AccessRelation = isl_map_apply_range(AccessRelation, Map.release());
Roman Gareev10595a12016-01-08 14:01:59 +0000537
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000538 // For the non delinearized arrays, divide the access function of the last
539 // subscript by the size of the elements in the array.
540 //
541 // A stride one array access in C expressed as A[i] is expressed in
542 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
543 // two subsequent values of 'i' index two values that are stored next to
544 // each other in memory. By this division we make this characteristic
545 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000546 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000547 // that divides the offsets of all accesses to this base pointer.
548 if (DimsAccess == 1) {
Tobias Grosser7be82452017-05-21 20:38:33 +0000549 isl::val V = isl::val(Ctx, ArrayElemSize);
550 AccessRelation = isl_map_floordiv_val(AccessRelation, V.release());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000551 }
552
Michael Kruse3b425ff2016-04-11 14:34:08 +0000553 // We currently do this only if we added at least one dimension, which means
554 // some dimension's indices have not been specified, an indicator that some
555 // index values have been added together.
556 // TODO: Investigate general usefulness; Effect on unit tests is to make index
557 // expressions more complicated.
558 if (DimsMissing)
559 wrapConstantDimensions();
560
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000561 if (!isAffine())
562 computeBoundsOnAccessRelation(ArrayElemSize);
563
Tobias Grosserd840fc72016-02-04 13:18:42 +0000564 // Introduce multi-element accesses in case the type loaded by this memory
565 // access is larger than the canonical element type of the array.
566 //
567 // An access ((float *)A)[i] to an array char *A is modeled as
568 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000569 if (ElemBytes > ArrayElemSize) {
570 assert(ElemBytes % ArrayElemSize == 0 &&
571 "Loaded element size should be multiple of canonical element size");
Tobias Grosser7be82452017-05-21 20:38:33 +0000572 isl::map Map = isl::map::from_domain_and_range(
573 isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000574 for (unsigned i = 0; i < DimsArray - 1; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000575 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000576
Tobias Grosser7be82452017-05-21 20:38:33 +0000577 isl::constraint C;
578 isl::local_space LS;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000579
Tobias Grosser7be82452017-05-21 20:38:33 +0000580 LS = isl::local_space(Map.get_space());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000581 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
582
Tobias Grosser7be82452017-05-21 20:38:33 +0000583 C = isl::constraint::alloc_inequality(LS);
584 C = C.set_constant_val(isl::val(Ctx, Num - 1));
585 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
586 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
587 Map = Map.add_constraint(C);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000588
Tobias Grosser7be82452017-05-21 20:38:33 +0000589 C = isl::constraint::alloc_inequality(LS);
590 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, -1);
591 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, 1);
592 C = C.set_constant_val(isl::val(Ctx, 0));
593 Map = Map.add_constraint(C);
594 AccessRelation = isl_map_apply_range(AccessRelation, Map.release());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000595 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000596}
597
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000598const std::string
599MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
600 switch (RT) {
601 case MemoryAccess::RT_NONE:
602 llvm_unreachable("Requested a reduction operator string for a memory "
603 "access which isn't a reduction");
604 case MemoryAccess::RT_ADD:
605 return "+";
606 case MemoryAccess::RT_MUL:
607 return "*";
608 case MemoryAccess::RT_BOR:
609 return "|";
610 case MemoryAccess::RT_BXOR:
611 return "^";
612 case MemoryAccess::RT_BAND:
613 return "&";
614 }
615 llvm_unreachable("Unknown reduction type");
616 return "";
617}
618
Tobias Grosserc80d6972016-09-02 06:33:33 +0000619/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000620static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
621 const Instruction *Load) {
622 if (!BinOp)
623 return MemoryAccess::RT_NONE;
624 switch (BinOp->getOpcode()) {
625 case Instruction::FAdd:
626 if (!BinOp->hasUnsafeAlgebra())
627 return MemoryAccess::RT_NONE;
628 // Fall through
629 case Instruction::Add:
630 return MemoryAccess::RT_ADD;
631 case Instruction::Or:
632 return MemoryAccess::RT_BOR;
633 case Instruction::Xor:
634 return MemoryAccess::RT_BXOR;
635 case Instruction::And:
636 return MemoryAccess::RT_BAND;
637 case Instruction::FMul:
638 if (!BinOp->hasUnsafeAlgebra())
639 return MemoryAccess::RT_NONE;
640 // Fall through
641 case Instruction::Mul:
642 if (DisableMultiplicativeReductions)
643 return MemoryAccess::RT_NONE;
644 return MemoryAccess::RT_MUL;
645 default:
646 return MemoryAccess::RT_NONE;
647 }
648}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000649
Tobias Grosser75805372011-04-29 06:27:02 +0000650MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000651 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000652 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000653 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000654 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000655}
656
Michael Kruse2fa35192016-09-01 19:53:31 +0000657const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000658 isl_id *ArrayId = getArrayId();
659 void *User = isl_id_get_user(ArrayId);
660 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
661 isl_id_free(ArrayId);
662 return SAI;
663}
664
Michael Kruse2fa35192016-09-01 19:53:31 +0000665const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
666 isl_id *ArrayId = getLatestArrayId();
667 void *User = isl_id_get_user(ArrayId);
668 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
669 isl_id_free(ArrayId);
670 return SAI;
671}
672
673__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000674 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
675}
676
Michael Kruse2fa35192016-09-01 19:53:31 +0000677__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
678 if (!hasNewAccessRelation())
679 return getOriginalArrayId();
680 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
681}
682
Tobias Grosserd840fc72016-02-04 13:18:42 +0000683__isl_give isl_map *MemoryAccess::getAddressFunction() const {
684 return isl_map_lexmin(getAccessRelation());
685}
686
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000687__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
688 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000689 isl_map *Schedule, *ScheduledAccRel;
690 isl_union_set *UDomain;
691
692 UDomain = isl_union_set_from_set(getStatement()->getDomain());
693 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
694 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000695 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000696 return isl_pw_multi_aff_from_map(ScheduledAccRel);
697}
698
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000699__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000700 return isl_map_copy(AccessRelation);
701}
702
Johannes Doerferta99130f2014-10-13 12:58:03 +0000703std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000704 return stringFromIslObj(AccessRelation);
705}
706
Johannes Doerferta99130f2014-10-13 12:58:03 +0000707__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000708 return isl_map_get_space(AccessRelation);
709}
710
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000711__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000712 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000713}
714
Tobias Grosser6f730082015-09-05 07:46:47 +0000715std::string MemoryAccess::getNewAccessRelationStr() const {
716 return stringFromIslObj(NewAccessRelation);
717}
718
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000719std::string MemoryAccess::getAccessRelationStr() const {
720 return isl::manage(getAccessRelation()).to_str();
721}
722
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000723__isl_give isl_basic_map *
724MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000725 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000726 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000727
Tobias Grosser084d8f72012-05-29 09:29:44 +0000728 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000729 isl_basic_set_universe(Statement->getDomainSpace()),
730 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000731}
732
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000733// Formalize no out-of-bound access assumption
734//
735// When delinearizing array accesses we optimistically assume that the
736// delinearized accesses do not access out of bound locations (the subscript
737// expression of each array evaluates for each statement instance that is
738// executed to a value that is larger than zero and strictly smaller than the
739// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000740// dimension for which we do not need to assume any upper bound. At this point
741// we formalize this assumption to ensure that at code generation time the
742// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000743//
744// To find the set of constraints necessary to avoid out of bound accesses, we
745// first build the set of data locations that are not within array bounds. We
746// then apply the reverse access relation to obtain the set of iterations that
747// may contain invalid accesses and reduce this set of iterations to the ones
748// that are actually executed by intersecting them with the domain of the
749// statement. If we now project out all loop dimensions, we obtain a set of
750// parameters that may cause statement instances to be executed that may
751// possibly yield out of bound memory accesses. The complement of these
752// constraints is the set of constraints that needs to be assumed to ensure such
753// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000754void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000755 if (PollyIgnoreInbounds)
756 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000757 auto *SAI = getScopArrayInfo();
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000758 isl::space Space = give(getOriginalAccessRelationSpace()).range();
759 isl::set Outside = isl::set::empty(Space);
760 for (int i = 1, Size = Space.dim(isl::dim::set); i < Size; ++i) {
761 isl::local_space LS(Space);
762 isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
763 isl::pw_aff Zero = isl::pw_aff(LS);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000764
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000765 isl::set DimOutside = Var.lt_set(Zero);
766 isl::pw_aff SizeE = give(SAI->getDimensionSizePw(i));
767 SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set));
768 SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
769 DimOutside = DimOutside.unite(SizeE.le_set(Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000770
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000771 Outside = Outside.unite(DimOutside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000772 }
773
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000774 Outside = Outside.apply(give(getAccessRelation()).reverse());
775 Outside = Outside.intersect(give(Statement->getDomain()));
776 Outside = Outside.params();
Tobias Grosserf54bb772015-06-26 12:09:28 +0000777
778 // Remove divs to avoid the construction of overly complicated assumptions.
779 // Doing so increases the set of parameter combinations that are assumed to
780 // not appear. This is always save, but may make the resulting run-time check
781 // bail out more often than strictly necessary.
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000782 Outside = Outside.remove_divs();
783 Outside = Outside.complement();
Michael Kruse7071e8b2016-04-11 13:24:29 +0000784 const auto &Loc = getAccessInstruction()
785 ? getAccessInstruction()->getDebugLoc()
786 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000787 if (!PollyPreciseInbounds)
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000788 Outside = Outside.gist_params(give(Statement->getDomain()).params());
789 Statement->getParent()->recordAssumption(INBOUNDS, Outside.release(), Loc,
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000790 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000791}
792
Johannes Doerfertcea61932016-02-21 19:13:19 +0000793void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000794 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000795 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000796
Tobias Grosser53fc3552017-05-23 07:07:09 +0000797 isl::pw_aff SubscriptPWA = give(getPwAff(Subscripts[0]));
798 isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000799
Tobias Grosser53fc3552017-05-23 07:07:09 +0000800 isl::map LengthMap;
Johannes Doerferta7920982016-02-25 14:08:48 +0000801 if (Subscripts[1] == nullptr) {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000802 LengthMap = isl::map::universe(SubscriptMap.get_space());
Johannes Doerferta7920982016-02-25 14:08:48 +0000803 } else {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000804 isl::pw_aff LengthPWA = give(getPwAff(Subscripts[1]));
805 LengthMap = isl::map::from_pw_aff(LengthPWA);
806 isl::space RangeSpace = LengthMap.get_space().range();
807 LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
Johannes Doerferta7920982016-02-25 14:08:48 +0000808 }
Tobias Grosser53fc3552017-05-23 07:07:09 +0000809 LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
810 LengthMap = LengthMap.align_params(SubscriptMap.get_space());
811 SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
812 LengthMap = LengthMap.sum(SubscriptMap);
813 AccessRelation =
814 LengthMap.set_tuple_id(isl::dim::in, give(getStatement()->getDomainId()))
815 .release();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000816}
817
Johannes Doerferte7044942015-02-24 11:58:30 +0000818void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
819 ScalarEvolution *SE = Statement->getParent()->getSE();
820
Johannes Doerfertcea61932016-02-21 19:13:19 +0000821 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000822 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000823 return;
824
825 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000826 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
827 return;
828
829 auto *PtrSCEV = SE->getSCEV(Ptr);
830 if (isa<SCEVCouldNotCompute>(PtrSCEV))
831 return;
832
833 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
834 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
835 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
836
837 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
838 if (Range.isFullSet())
839 return;
840
Michael Kruse960c0d02017-05-18 21:55:36 +0000841 if (Range.isWrappedSet() || Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000842 return;
843
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000844 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000845
Johannes Doerferte7044942015-02-24 11:58:30 +0000846 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000847 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000848 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000849 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000850
851 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000852 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000853
Tobias Grosserb3a85882017-02-12 08:11:12 +0000854 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
855
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000856 isl::map Relation = give(AccessRelation);
857 isl::set AccessRange = Relation.range();
858 AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
859 isl::dim::set);
860 AccessRelation = Relation.intersect_range(AccessRange).release();
Johannes Doerferte7044942015-02-24 11:58:30 +0000861}
862
Tobias Grosser491b7992016-12-02 05:21:22 +0000863void MemoryAccess::foldAccessRelation() {
864 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
865 return;
866
Michael Krusee2bccbb2015-09-18 19:59:43 +0000867 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000868
Tobias Grossera32de132017-05-23 07:22:56 +0000869 isl::map NewAccessRelation = give(isl_map_copy(AccessRelation));
Tobias Grosserc2f15102017-03-01 21:11:27 +0000870
Tobias Grosser619190d2015-03-30 17:22:28 +0000871 for (int i = Size - 2; i >= 0; --i) {
Tobias Grossera32de132017-05-23 07:22:56 +0000872 isl::space Space;
873 isl::map MapOne, MapTwo;
874 isl::pw_aff DimSize = give(getPwAff(Sizes[i + 1]));
Tobias Grosser619190d2015-03-30 17:22:28 +0000875
Tobias Grossera32de132017-05-23 07:22:56 +0000876 isl::space SpaceSize = DimSize.get_space();
877 isl::id ParamId =
878 give(isl_space_get_dim_id(SpaceSize.get(), isl_dim_param, 0));
Tobias Grosser619190d2015-03-30 17:22:28 +0000879
Tobias Grossera32de132017-05-23 07:22:56 +0000880 Space = give(isl_map_copy(AccessRelation)).get_space();
881 Space = Space.range().map_from_set();
882 Space = Space.align_params(SpaceSize);
Tobias Grosser619190d2015-03-30 17:22:28 +0000883
Tobias Grossera32de132017-05-23 07:22:56 +0000884 int ParamLocation = Space.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosser619190d2015-03-30 17:22:28 +0000885
Tobias Grossera32de132017-05-23 07:22:56 +0000886 MapOne = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000887 for (int j = 0; j < Size; ++j)
Tobias Grossera32de132017-05-23 07:22:56 +0000888 MapOne = MapOne.equate(isl::dim::in, j, isl::dim::out, j);
889 MapOne = MapOne.lower_bound_si(isl::dim::in, i + 1, 0);
Tobias Grosser619190d2015-03-30 17:22:28 +0000890
Tobias Grossera32de132017-05-23 07:22:56 +0000891 MapTwo = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000892 for (int j = 0; j < Size; ++j)
893 if (j < i || j > i + 1)
Tobias Grossera32de132017-05-23 07:22:56 +0000894 MapTwo = MapTwo.equate(isl::dim::in, j, isl::dim::out, j);
Tobias Grosser619190d2015-03-30 17:22:28 +0000895
Tobias Grossera32de132017-05-23 07:22:56 +0000896 isl::local_space LS(Space);
897 isl::constraint C;
898 C = isl::constraint::alloc_equality(LS);
899 C = C.set_constant_si(-1);
900 C = C.set_coefficient_si(isl::dim::in, i, 1);
901 C = C.set_coefficient_si(isl::dim::out, i, -1);
902 MapTwo = MapTwo.add_constraint(C);
903 C = isl::constraint::alloc_equality(LS);
904 C = C.set_coefficient_si(isl::dim::in, i + 1, 1);
905 C = C.set_coefficient_si(isl::dim::out, i + 1, -1);
906 C = C.set_coefficient_si(isl::dim::param, ParamLocation, 1);
907 MapTwo = MapTwo.add_constraint(C);
908 MapTwo = MapTwo.upper_bound_si(isl::dim::in, i + 1, -1);
Tobias Grosser619190d2015-03-30 17:22:28 +0000909
Tobias Grossera32de132017-05-23 07:22:56 +0000910 MapOne = MapOne.unite(MapTwo);
911 NewAccessRelation = NewAccessRelation.apply_range(MapOne);
Tobias Grosser619190d2015-03-30 17:22:28 +0000912 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000913
Tobias Grossera32de132017-05-23 07:22:56 +0000914 isl::id BaseAddrId = give(getScopArrayInfo()->getBasePtrId());
915 isl::space Space = give(Statement->getDomainSpace());
916 NewAccessRelation = NewAccessRelation.set_tuple_id(
917 isl::dim::in, Space.get_tuple_id(isl::dim::set));
918 NewAccessRelation = NewAccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
919 NewAccessRelation =
920 NewAccessRelation.gist_domain(give(Statement->getDomain()));
Tobias Grosserc2f15102017-03-01 21:11:27 +0000921
922 // Access dimension folding might in certain cases increase the number of
923 // disjuncts in the memory access, which can possibly complicate the generated
924 // run-time checks and can lead to costly compilation.
Tobias Grossera32de132017-05-23 07:22:56 +0000925 if (!PollyPreciseFoldAccesses &&
926 isl_map_n_basic_map(NewAccessRelation.get()) >
927 isl_map_n_basic_map(AccessRelation)) {
Tobias Grosserc2f15102017-03-01 21:11:27 +0000928 } else {
Tobias Grossera32de132017-05-23 07:22:56 +0000929 isl_map_free(AccessRelation);
930 AccessRelation = NewAccessRelation.release();
Tobias Grosserc2f15102017-03-01 21:11:27 +0000931 }
Tobias Grosser619190d2015-03-30 17:22:28 +0000932}
933
Tobias Grosserc80d6972016-09-02 06:33:33 +0000934/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000935static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000936 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000937 if (Size == 1)
938 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000939
940 // Only one factor needs to be divisible.
941 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
942 for (auto *FactorExpr : MulExpr->operands())
943 if (isDivisible(FactorExpr, Size, SE))
944 return true;
945 return false;
946 }
947
948 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
Michael Krusea6d48f52017-06-08 12:06:15 +0000949 // to be divisible.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000950 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
951 for (auto *OpExpr : NAryExpr->operands())
952 if (!isDivisible(OpExpr, Size, SE))
953 return false;
954 return true;
955 }
956
957 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
958 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
959 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
960 return MulSCEV == Expr;
961}
962
Michael Krusee2bccbb2015-09-18 19:59:43 +0000963void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
Tobias Grosser37c8ee72017-06-30 06:30:51 +0000964 assert(!AccessRelation && "AccessRelation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000965
Johannes Doerfert85676e32016-04-23 14:32:34 +0000966 // Initialize the invalid domain which describes all iterations for which the
967 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000968 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
969 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
970 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000971
Michael Krusee2bccbb2015-09-18 19:59:43 +0000972 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000973 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000974
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000975 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
976 buildMemIntrinsicAccessRelation();
977 AccessRelation =
978 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
979 return;
980 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000981
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000982 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000983 // We overapproximate non-affine accesses with a possible access to the
984 // whole array. For read accesses it does not make a difference, if an
985 // access must or may happen. However, for write accesses it is important to
986 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000987 if (!AccessRelation)
988 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
989
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000990 AccessRelation =
991 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000992 return;
993 }
994
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000995 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000996 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000997
Michael Krusee2bccbb2015-09-18 19:59:43 +0000998 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000999 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +00001000 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +00001001 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +00001002 }
1003
Tobias Grosser79baa212014-04-10 08:38:02 +00001004 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +00001005 AccessRelation = isl_map_set_tuple_id(
1006 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +00001007 AccessRelation =
1008 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
1009
Tobias Grosseraa660a92015-03-30 00:07:50 +00001010 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +00001011 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001012}
Tobias Grosser30b8a092011-08-18 07:51:37 +00001013
Michael Krusecac948e2015-10-02 13:53:07 +00001014MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00001015 AccessType AccType, Value *BaseAddress,
1016 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +00001017 ArrayRef<const SCEV *> Subscripts,
1018 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +00001019 MemoryKind Kind)
Johannes Doerfertcea61932016-02-21 19:13:19 +00001020 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Tobias Grosser81331282017-05-03 07:57:35 +00001021 InvalidDomain(nullptr), BaseAddr(BaseAddress), ElementType(ElementType),
1022 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
1023 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +00001024 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001025 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +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());
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001028
Tobias Grosser81331282017-05-03 07:57:35 +00001029 std::string IdName = Stmt->getBaseName() + Access;
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001030 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1031}
Michael Krusee2bccbb2015-09-18 19:59:43 +00001032
Roman Gareevb3224ad2016-09-14 06:26:09 +00001033MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
1034 __isl_take isl_map *AccRel)
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001035 : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
1036 Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001037 IsAffine(true), AccessRelation(nullptr), NewAccessRelation(AccRel),
1038 FAD(nullptr) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001039 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
1040 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1041 Sizes.push_back(nullptr);
1042 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1043 Sizes.push_back(SAI->getDimensionSize(i));
1044 ElementType = SAI->getElementType();
1045 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001046 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001047 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001048
Tobias Grosser81331282017-05-03 07:57:35 +00001049 std::string IdName = Stmt->getBaseName() + Access;
Roman Gareevb3224ad2016-09-14 06:26:09 +00001050 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1051}
1052
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001053void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +00001054 auto *Ctx = Statement->getParent()->getContext();
1055 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1056 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001057}
1058
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001059const std::string MemoryAccess::getReductionOperatorStr() const {
1060 return MemoryAccess::getReductionOperatorStr(getReductionType());
1061}
1062
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001063__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
1064
Johannes Doerfertf6183392014-07-01 20:52:51 +00001065raw_ostream &polly::operator<<(raw_ostream &OS,
1066 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001067 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001068 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001069 else
1070 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001071 return OS;
1072}
1073
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001074void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001075
Tobias Grosser75805372011-04-29 06:27:02 +00001076void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001077 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001078 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001079 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001080 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001081 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001082 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001083 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001084 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001085 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001086 break;
1087 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001088
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001089 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001090
1091 if (FAD) {
1092 OS << "[Fortran array descriptor: " << FAD->getName();
1093 OS << "] ";
1094 };
1095
Tobias Grossera535dff2015-12-13 19:59:01 +00001096 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001097 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001098 if (hasNewAccessRelation())
1099 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001100}
1101
Tobias Grosser74394f02013-01-14 22:40:23 +00001102void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +00001103
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001104__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
1105 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001106 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +00001107 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
1108 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
1109 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +00001110 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001111}
1112
Tobias Grosser75805372011-04-29 06:27:02 +00001113// Create a map in the size of the provided set domain, that maps from the
1114// one element of the provided set domain to another element of the provided
1115// set domain.
1116// The mapping is limited to all points that are equal in all but the last
1117// dimension and for which the last dimension of the input is strict smaller
1118// than the last dimension of the output.
1119//
1120// getEqualAndLarger(set[i0, i1, ..., iX]):
1121//
1122// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1123// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1124//
Tobias Grosser2a526fe2016-09-08 11:18:56 +00001125static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +00001126 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001127 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +00001128 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001129
1130 // Set all but the last dimension to be equal for the input and output
1131 //
1132 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1133 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001134 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +00001135 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001136
1137 // Set the last dimension of the input to be strict smaller than the
1138 // last dimension of the output.
1139 //
1140 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001141 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1142 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001143 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001144}
1145
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001146__isl_give isl_set *
1147MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001148 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +00001149 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +00001150 isl_space *Space = isl_space_range(isl_map_get_space(S));
1151 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001152
Sebastian Popa00a0292012-12-18 07:46:06 +00001153 S = isl_map_reverse(S);
1154 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001155
Sebastian Popa00a0292012-12-18 07:46:06 +00001156 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1157 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1158 NextScatt = isl_map_apply_domain(NextScatt, S);
1159 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001160
Sebastian Popa00a0292012-12-18 07:46:06 +00001161 isl_set *Deltas = isl_map_deltas(NextScatt);
1162 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001163}
1164
Sebastian Popa00a0292012-12-18 07:46:06 +00001165bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001166 int StrideWidth) const {
1167 isl_set *Stride, *StrideX;
1168 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001169
Sebastian Popa00a0292012-12-18 07:46:06 +00001170 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001171 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001172 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1173 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1174 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1175 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001176 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001177
Tobias Grosser28dd4862012-01-24 16:42:16 +00001178 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001179 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001180
Tobias Grosser28dd4862012-01-24 16:42:16 +00001181 return IsStrideX;
1182}
1183
Michael Krused56b90a2016-09-01 09:03:27 +00001184bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001185 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001186}
1187
Michael Krused56b90a2016-09-01 09:03:27 +00001188bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001189 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001190}
1191
Tobias Grosserbedef002016-12-02 08:10:56 +00001192void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
1193 isl_map_free(AccessRelation);
1194 AccessRelation = NewAccess;
1195}
1196
Michael Krused56b90a2016-09-01 09:03:27 +00001197void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001198 assert(NewAccess);
1199
1200#ifndef NDEBUG
1201 // Check domain space compatibility.
1202 auto *NewSpace = isl_map_get_space(NewAccess);
1203 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1204 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1205 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1206 isl_space_free(NewDomainSpace);
1207 isl_space_free(OriginalDomainSpace);
1208
Michael Kruse706f79a2017-05-21 22:46:57 +00001209 // Reads must be executed unconditionally. Writes might be executed in a
1210 // subdomain only.
1211 if (isRead()) {
1212 // Check whether there is an access for every statement instance.
1213 auto *StmtDomain = getStatement()->getDomain();
1214 StmtDomain = isl_set_intersect_params(
1215 StmtDomain, getStatement()->getParent()->getContext());
1216 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1217 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1218 "Partial READ accesses not supported");
1219 isl_set_free(NewDomain);
1220 isl_set_free(StmtDomain);
1221 }
Michael Kruse772ce722016-09-01 19:16:58 +00001222
Michael Kruse772ce722016-09-01 19:16:58 +00001223 auto *NewAccessSpace = isl_space_range(NewSpace);
1224 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1225 "Must specify the array that is accessed");
1226 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1227 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1228 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001229
1230 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1231 InvariantEquivClassTy *EqClass =
1232 getStatement()->getParent()->lookupInvariantEquivClass(
1233 SAI->getBasePtr());
1234 assert(EqClass &&
1235 "Access functions to indirect arrays must have an invariant and "
1236 "hoisted base pointer");
1237 }
1238
1239 // Check whether access dimensions correspond to number of dimensions of the
1240 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001241 auto Dims = SAI->getNumberOfDimensions();
1242 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1243 "Access dims must match array dims");
1244 isl_space_free(NewAccessSpace);
1245 isl_id_free(NewArrayId);
1246#endif
1247
Tobias Grosser166c4222015-09-05 07:46:40 +00001248 isl_map_free(NewAccessRelation);
Tobias Grosser4556c9b2017-07-17 20:47:10 +00001249 NewAccess = isl_map_gist_domain(NewAccess, getStatement()->getDomain());
Tobias Grosser166c4222015-09-05 07:46:40 +00001250 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001251}
Tobias Grosser75805372011-04-29 06:27:02 +00001252
Michael Kruse706f79a2017-05-21 22:46:57 +00001253bool MemoryAccess::isLatestPartialAccess() const {
1254 isl::set StmtDom = give(getStatement()->getDomain());
1255 isl::set AccDom = give(isl_map_domain(getLatestAccessRelation()));
1256
1257 return isl_set_is_subset(StmtDom.keep(), AccDom.keep()) == isl_bool_false;
1258}
1259
Tobias Grosser75805372011-04-29 06:27:02 +00001260//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001261
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001262__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001263 isl_set *Domain = getDomain();
1264 if (isl_set_is_empty(Domain)) {
1265 isl_set_free(Domain);
1266 return isl_map_from_aff(
1267 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1268 }
1269 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001270 if (!Schedule) {
1271 isl_set_free(Domain);
1272 return nullptr;
1273 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001274 Schedule = isl_union_map_intersect_domain(
1275 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1276 if (isl_union_map_is_empty(Schedule)) {
1277 isl_set_free(Domain);
1278 isl_union_map_free(Schedule);
1279 return isl_map_from_aff(
1280 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1281 }
1282 auto *M = isl_map_from_union_map(Schedule);
1283 M = isl_map_coalesce(M);
1284 M = isl_map_gist_domain(M, Domain);
1285 M = isl_map_coalesce(M);
1286 return M;
1287}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001288
Tobias Grosser37eb4222014-02-20 21:43:54 +00001289void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1290 assert(isl_set_is_subset(NewDomain, Domain) &&
1291 "New domain is not a subset of old domain!");
1292 isl_set_free(Domain);
1293 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001294}
1295
Michael Krusecac948e2015-10-02 13:53:07 +00001296void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001297 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001298 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001299 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001300
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001301 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001302 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001303 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001304 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001305 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001306 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001307 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001308 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001309 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001310
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001311 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1312 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001313 Access->buildAccessRelation(SAI);
Michael Kruse8b805802017-07-19 17:11:25 +00001314 S.addAccessData(Access);
Tobias Grosser75805372011-04-29 06:27:02 +00001315 }
1316}
1317
Michael Krusecac948e2015-10-02 13:53:07 +00001318void ScopStmt::addAccess(MemoryAccess *Access) {
1319 Instruction *AccessInst = Access->getAccessInstruction();
1320
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001321 if (Access->isArrayKind()) {
1322 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1323 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001324 } else if (Access->isValueKind() && Access->isWrite()) {
1325 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001326 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001327 assert(!ValueWrites.lookup(AccessVal));
1328
1329 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001330 } else if (Access->isValueKind() && Access->isRead()) {
1331 Value *AccessVal = Access->getAccessValue();
1332 assert(!ValueReads.lookup(AccessVal));
1333
1334 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001335 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001336 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001337 assert(!PHIWrites.lookup(PHI));
1338
1339 PHIWrites[PHI] = Access;
Michael Kruse3562f272017-07-20 16:47:57 +00001340 } else if (Access->isAnyPHIKind() && Access->isRead()) {
1341 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1342 assert(!PHIReads.lookup(PHI));
1343
1344 PHIReads[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001345 }
1346
1347 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001348}
1349
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001350void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001351 for (MemoryAccess *MA : *this)
1352 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001353
Johannes Doerferta60ad842016-05-10 12:18:22 +00001354 auto *Ctx = Parent.getContext();
1355 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1356 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001357}
1358
Tobias Grosserc80d6972016-09-02 06:33:33 +00001359/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001360static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1361 void *User) {
1362 isl_set **BoundedParts = static_cast<isl_set **>(User);
1363 if (isl_basic_set_is_bounded(BSet))
1364 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1365 else
1366 isl_basic_set_free(BSet);
1367 return isl_stat_ok;
1368}
1369
Tobias Grosserc80d6972016-09-02 06:33:33 +00001370/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001371static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1372 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1373 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1374 isl_set_free(S);
1375 return BoundedParts;
1376}
1377
Tobias Grosserc80d6972016-09-02 06:33:33 +00001378/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001379///
1380/// @returns A separation of @p S into first an unbounded then a bounded subset,
1381/// both with regards to the dimension @p Dim.
1382static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1383partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1384
1385 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001386 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001387
1388 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001389 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001390
1391 // Remove dimensions that are greater than Dim as they are not interesting.
1392 assert(NumDimsS >= Dim + 1);
1393 OnlyDimS =
1394 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1395
1396 // Create artificial parametric upper bounds for dimensions smaller than Dim
1397 // as we are not interested in them.
1398 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1399 for (unsigned u = 0; u < Dim; u++) {
1400 isl_constraint *C = isl_inequality_alloc(
1401 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1402 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1403 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1404 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1405 }
1406
1407 // Collect all bounded parts of OnlyDimS.
1408 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1409
1410 // Create the dimensions greater than Dim again.
1411 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1412 NumDimsS - Dim - 1);
1413
1414 // Remove the artificial upper bound parameters again.
1415 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1416
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001417 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001418 return std::make_pair(UnboundedParts, BoundedParts);
1419}
1420
Tobias Grosserc80d6972016-09-02 06:33:33 +00001421/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001422static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1423 __isl_take isl_set *To) {
1424 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1425 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1426 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1427 }
1428 return To;
1429}
1430
Tobias Grosserc80d6972016-09-02 06:33:33 +00001431/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001432static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001433 __isl_take isl_pw_aff *L,
1434 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001435 switch (Pred) {
1436 case ICmpInst::ICMP_EQ:
1437 return isl_pw_aff_eq_set(L, R);
1438 case ICmpInst::ICMP_NE:
1439 return isl_pw_aff_ne_set(L, R);
1440 case ICmpInst::ICMP_SLT:
1441 return isl_pw_aff_lt_set(L, R);
1442 case ICmpInst::ICMP_SLE:
1443 return isl_pw_aff_le_set(L, R);
1444 case ICmpInst::ICMP_SGT:
1445 return isl_pw_aff_gt_set(L, R);
1446 case ICmpInst::ICMP_SGE:
1447 return isl_pw_aff_ge_set(L, R);
1448 case ICmpInst::ICMP_ULT:
1449 return isl_pw_aff_lt_set(L, R);
1450 case ICmpInst::ICMP_UGT:
1451 return isl_pw_aff_gt_set(L, R);
1452 case ICmpInst::ICMP_ULE:
1453 return isl_pw_aff_le_set(L, R);
1454 case ICmpInst::ICMP_UGE:
1455 return isl_pw_aff_ge_set(L, R);
1456 default:
1457 llvm_unreachable("Non integer predicate not supported");
1458 }
1459}
1460
Tobias Grosserc80d6972016-09-02 06:33:33 +00001461/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001462///
1463/// Helper function that will make sure the dimensions of the result have the
1464/// same isl_id's as the @p Domain.
1465static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1466 __isl_take isl_pw_aff *L,
1467 __isl_take isl_pw_aff *R,
1468 __isl_keep isl_set *Domain) {
1469 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1470 return setDimensionIds(Domain, ConsequenceCondSet);
1471}
1472
Michael Kruse476f8552017-06-29 12:47:41 +00001473/// Compute the isl representation for the SCEV @p E in this BB.
1474///
1475/// @param S The Scop in which @p BB resides in.
1476/// @param BB The BB for which isl representation is to be
1477/// computed.
1478/// @param InvalidDomainMap A map of BB to their invalid domains.
1479/// @param E The SCEV that should be translated.
1480/// @param NonNegative Flag to indicate the @p E has to be non-negative.
1481///
1482/// Note that this function will also adjust the invalid context accordingly.
1483
1484__isl_give isl_pw_aff *
1485getPwAff(Scop &S, BasicBlock *BB,
Tobias Grosser13acbb92017-07-15 09:01:31 +00001486 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, const SCEV *E,
1487 bool NonNegative = false) {
Michael Kruse476f8552017-06-29 12:47:41 +00001488 PWACtx PWAC = S.getPwAff(E, BB, NonNegative);
Tobias Grosser13acbb92017-07-15 09:01:31 +00001489 InvalidDomainMap[BB] = InvalidDomainMap[BB].unite(isl::manage(PWAC.second));
Michael Kruse476f8552017-06-29 12:47:41 +00001490 return PWAC.first;
1491}
1492
Tobias Grosserc80d6972016-09-02 06:33:33 +00001493/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001494///
1495/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001496/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1497/// have as many elements as @p SI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001498static bool
1499buildConditionSets(Scop &S, BasicBlock *BB, SwitchInst *SI, Loop *L,
1500 __isl_keep isl_set *Domain,
1501 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1502 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001503
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001504 Value *Condition = getConditionFromTerminator(SI);
1505 assert(Condition && "No condition for switch");
1506
1507 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001508 isl_pw_aff *LHS, *RHS;
Michael Kruse476f8552017-06-29 12:47:41 +00001509 LHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001510
1511 unsigned NumSuccessors = SI->getNumSuccessors();
1512 ConditionSets.resize(NumSuccessors);
1513 for (auto &Case : SI->cases()) {
1514 unsigned Idx = Case.getSuccessorIndex();
1515 ConstantInt *CaseValue = Case.getCaseValue();
1516
Michael Kruse476f8552017-06-29 12:47:41 +00001517 RHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001518 isl_set *CaseConditionSet =
1519 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1520 ConditionSets[Idx] = isl_set_coalesce(
1521 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1522 }
1523
1524 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1525 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1526 for (unsigned u = 2; u < NumSuccessors; u++)
1527 ConditionSetUnion =
1528 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1529 ConditionSets[0] = setDimensionIds(
1530 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1531
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001532 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001533
1534 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001535}
1536
Michael Kruse08655852017-07-20 12:37:02 +00001537/// Build condition sets for unsigned ICmpInst(s).
1538/// Special handling is required for unsigned operands to ensure that if
1539/// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst
1540/// it should wrap around.
1541///
1542/// @param IsStrictUpperBound holds information on the predicate relation
1543/// between TestVal and UpperBound, i.e,
1544/// TestVal < UpperBound OR TestVal <= UpperBound
1545static __isl_give isl_set *
1546buildUnsignedConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1547 __isl_keep isl_set *Domain, const SCEV *SCEV_TestVal,
1548 const SCEV *SCEV_UpperBound,
1549 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1550 bool IsStrictUpperBound) {
1551
1552 // Do not take NonNeg assumption on TestVal
1553 // as it might have MSB (Sign bit) set.
1554 isl_pw_aff *TestVal = getPwAff(S, BB, InvalidDomainMap, SCEV_TestVal, false);
1555 // Take NonNeg assumption on UpperBound.
1556 isl_pw_aff *UpperBound =
1557 getPwAff(S, BB, InvalidDomainMap, SCEV_UpperBound, true);
1558
1559 // 0 <= TestVal
1560 isl_set *First =
1561 isl_pw_aff_le_set(isl_pw_aff_zero_on_domain(isl_local_space_from_space(
1562 isl_pw_aff_get_domain_space(TestVal))),
1563 isl_pw_aff_copy(TestVal));
1564
1565 isl_set *Second;
1566 if (IsStrictUpperBound)
1567 // TestVal < UpperBound
1568 Second = isl_pw_aff_lt_set(TestVal, UpperBound);
1569 else
1570 // TestVal <= UpperBound
1571 Second = isl_pw_aff_le_set(TestVal, UpperBound);
1572
1573 isl_set *ConsequenceCondSet = isl_set_intersect(First, Second);
1574 ConsequenceCondSet = setDimensionIds(Domain, ConsequenceCondSet);
1575 return ConsequenceCondSet;
1576}
1577
Tobias Grosserc80d6972016-09-02 06:33:33 +00001578/// Build the conditions sets for the branch condition @p Condition in
1579/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001580///
1581/// This will fill @p ConditionSets with the conditions under which control
1582/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001583/// have as many elements as @p TI has successors. If @p TI is nullptr the
1584/// context under which @p Condition is true/false will be returned as the
1585/// new elements of @p ConditionSets.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001586static bool
1587buildConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1588 TerminatorInst *TI, Loop *L, __isl_keep isl_set *Domain,
1589 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1590 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001591
1592 isl_set *ConsequenceCondSet = nullptr;
1593 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1594 if (CCond->isZero())
1595 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1596 else
1597 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1598 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1599 auto Opcode = BinOp->getOpcode();
1600 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1601
Michael Kruse476f8552017-06-29 12:47:41 +00001602 bool Valid = buildConditionSets(S, BB, BinOp->getOperand(0), TI, L, Domain,
1603 InvalidDomainMap, ConditionSets) &&
1604 buildConditionSets(S, BB, BinOp->getOperand(1), TI, L, Domain,
1605 InvalidDomainMap, ConditionSets);
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001606 if (!Valid) {
1607 while (!ConditionSets.empty())
1608 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001609 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001610 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001611
1612 isl_set_free(ConditionSets.pop_back_val());
1613 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1614 isl_set_free(ConditionSets.pop_back_val());
1615 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1616
1617 if (Opcode == Instruction::And)
1618 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1619 else
1620 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1621 } else {
1622 auto *ICond = dyn_cast<ICmpInst>(Condition);
1623 assert(ICond &&
1624 "Condition of exiting branch was neither constant nor ICmp!");
1625
1626 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001627 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001628 // For unsigned comparisons we assumed the signed bit of neither operand
1629 // to be set. The comparison is equal to a signed comparison under this
1630 // assumption.
1631 bool NonNeg = ICond->isUnsigned();
Michael Kruse08655852017-07-20 12:37:02 +00001632 const SCEV *LeftOperand = SE.getSCEVAtScope(ICond->getOperand(0), L),
1633 *RightOperand = SE.getSCEVAtScope(ICond->getOperand(1), L);
1634
1635 switch (ICond->getPredicate()) {
1636 case ICmpInst::ICMP_ULT:
1637 ConsequenceCondSet =
1638 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1639 RightOperand, InvalidDomainMap, true);
1640 break;
1641 case ICmpInst::ICMP_ULE:
1642 ConsequenceCondSet =
1643 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1644 RightOperand, InvalidDomainMap, false);
1645 break;
1646 case ICmpInst::ICMP_UGT:
1647 ConsequenceCondSet =
1648 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1649 LeftOperand, InvalidDomainMap, true);
1650 break;
1651 case ICmpInst::ICMP_UGE:
1652 ConsequenceCondSet =
1653 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1654 LeftOperand, InvalidDomainMap, false);
1655 break;
1656 default:
1657 LHS = getPwAff(S, BB, InvalidDomainMap, LeftOperand, NonNeg);
1658 RHS = getPwAff(S, BB, InvalidDomainMap, RightOperand, NonNeg);
1659 ConsequenceCondSet =
1660 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1661 break;
1662 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001663 }
1664
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001665 // If no terminator was given we are only looking for parameter constraints
1666 // under which @p Condition is true/false.
1667 if (!TI)
1668 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001669 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001670 ConsequenceCondSet = isl_set_coalesce(
1671 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001672
Johannes Doerfertb2885792016-04-26 09:20:41 +00001673 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001674 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001675 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001676
Michael Krusef7a4a942016-05-02 12:25:36 +00001677 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001678 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1679 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001680 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001681 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001682 }
1683
Michael Krusef7a4a942016-05-02 12:25:36 +00001684 if (TooComplex) {
Eli Friedmane737fc12017-07-17 23:58:33 +00001685 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc(),
1686 TI ? TI->getParent() : nullptr /* BasicBlock */);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001687 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001688 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001689 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001690 }
1691
1692 ConditionSets.push_back(ConsequenceCondSet);
1693 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001694
1695 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001696}
1697
Tobias Grosserc80d6972016-09-02 06:33:33 +00001698/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001699///
1700/// This will fill @p ConditionSets with the conditions under which control
1701/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1702/// have as many elements as @p TI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001703static bool
1704buildConditionSets(Scop &S, BasicBlock *BB, TerminatorInst *TI, Loop *L,
1705 __isl_keep isl_set *Domain,
1706 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1707 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001708
1709 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Michael Kruse476f8552017-06-29 12:47:41 +00001710 return buildConditionSets(S, BB, SI, L, Domain, InvalidDomainMap,
1711 ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001712
1713 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1714
1715 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001716 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001717 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001718 }
1719
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001720 Value *Condition = getConditionFromTerminator(TI);
1721 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001722
Michael Kruse476f8552017-06-29 12:47:41 +00001723 return buildConditionSets(S, BB, Condition, TI, L, Domain, InvalidDomainMap,
1724 ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001725}
1726
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001727void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001728 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001729
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001730 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001731 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001732}
1733
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001734void ScopStmt::collectSurroundingLoops() {
1735 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1736 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1737 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1738 isl_id_free(DimId);
1739 }
1740}
1741
Michael Kruse55454072017-03-15 22:16:43 +00001742ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001743 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
Michael Kruse55454072017-03-15 22:16:43 +00001744 R(&R), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001745
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001746 BaseName = getIslCompatibleName(
1747 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001748}
1749
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001750ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop,
1751 std::vector<Instruction *> Instructions)
Johannes Doerferta3519512016-04-23 13:02:23 +00001752 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001753 R(nullptr), Build(nullptr), SurroundingLoop(SurroundingLoop),
1754 Instructions(Instructions) {
Tobias Grosser75805372011-04-29 06:27:02 +00001755
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001756 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), "",
1757 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001758}
1759
Roman Gareevb3224ad2016-09-14 06:26:09 +00001760ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1761 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1762 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1763 R(nullptr), Build(nullptr) {
1764 BaseName = getIslCompatibleName("CopyStmt_", "",
1765 std::to_string(parent.getCopyStmtsNum()));
1766 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1767 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1768 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1769 auto *Access =
1770 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1771 parent.addAccessFunction(Access);
1772 addAccess(Access);
1773 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1774 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1775 parent.addAccessFunction(Access);
1776 addAccess(Access);
1777}
1778
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001779void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001780 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001781
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001782 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001783 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001784 buildAccessRelations();
1785
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001786 if (DetectReductions)
1787 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001788}
1789
Tobias Grosserc80d6972016-09-02 06:33:33 +00001790/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001791///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001792/// Check if the stored value for @p StoreMA is a binary operator with one or
1793/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001794/// used only once (by @p StoreMA) and its load operands are also used only
1795/// once, we have found a possible reduction chain. It starts at an operand
1796/// load and includes the binary operator and @p StoreMA.
1797///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001798/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001799/// escape this block or into any other store except @p StoreMA.
1800void ScopStmt::collectCandiateReductionLoads(
1801 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1802 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1803 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001804 return;
1805
1806 // Skip if there is not one binary operator between the load and the store
1807 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001808 if (!BinOp)
1809 return;
1810
1811 // Skip if the binary operators has multiple uses
1812 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001813 return;
1814
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001815 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001816 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1817 return;
1818
Johannes Doerfert9890a052014-07-01 00:32:29 +00001819 // Skip if the binary operator is outside the current SCoP
1820 if (BinOp->getParent() != Store->getParent())
1821 return;
1822
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001823 // Skip if it is a multiplicative reduction and we disabled them
1824 if (DisableMultiplicativeReductions &&
1825 (BinOp->getOpcode() == Instruction::Mul ||
1826 BinOp->getOpcode() == Instruction::FMul))
1827 return;
1828
Johannes Doerferte58a0122014-06-27 20:31:28 +00001829 // Check the binary operator operands for a candidate load
1830 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1831 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1832 if (!PossibleLoad0 && !PossibleLoad1)
1833 return;
1834
1835 // A load is only a candidate if it cannot escape (thus has only this use)
1836 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001837 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001838 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001839 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001840 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001841 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001842}
1843
Tobias Grosserc80d6972016-09-02 06:33:33 +00001844/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001845///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001846/// Iterate over all store memory accesses and check for valid binary reduction
1847/// like chains. For all candidates we check if they have the same base address
1848/// and there are no other accesses which overlap with them. The base address
1849/// check rules out impossible reductions candidates early. The overlap check,
1850/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001851/// guarantees that none of the intermediate results will escape during
1852/// execution of the loop nest. We basically check here that no other memory
1853/// access can access the same memory as the potential reduction.
1854void ScopStmt::checkForReductions() {
1855 SmallVector<MemoryAccess *, 2> Loads;
1856 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1857
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001858 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001859 // stores and collecting possible reduction loads.
1860 for (MemoryAccess *StoreMA : MemAccs) {
1861 if (StoreMA->isRead())
1862 continue;
1863
1864 Loads.clear();
1865 collectCandiateReductionLoads(StoreMA, Loads);
1866 for (MemoryAccess *LoadMA : Loads)
1867 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1868 }
1869
1870 // Then check each possible candidate pair.
1871 for (const auto &CandidatePair : Candidates) {
1872 bool Valid = true;
1873 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1874 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1875
1876 // Skip those with obviously unequal base addresses.
1877 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1878 isl_map_free(LoadAccs);
1879 isl_map_free(StoreAccs);
1880 continue;
1881 }
1882
1883 // And check if the remaining for overlap with other memory accesses.
1884 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1885 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1886 isl_set *AllAccs = isl_map_range(AllAccsRel);
1887
1888 for (MemoryAccess *MA : MemAccs) {
1889 if (MA == CandidatePair.first || MA == CandidatePair.second)
1890 continue;
1891
1892 isl_map *AccRel =
1893 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1894 isl_set *Accs = isl_map_range(AccRel);
1895
Tobias Grosser55a7af72016-09-08 14:08:07 +00001896 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001897 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1898 Valid = Valid && isl_set_is_empty(OverlapAccs);
1899 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001900 } else {
1901 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001902 }
1903 }
1904
1905 isl_set_free(AllAccs);
1906 if (!Valid)
1907 continue;
1908
Johannes Doerfertf6183392014-07-01 20:52:51 +00001909 const LoadInst *Load =
1910 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1911 MemoryAccess::ReductionType RT =
1912 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1913
Johannes Doerferte58a0122014-06-27 20:31:28 +00001914 // If no overlapping access was found we mark the load and store as
1915 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001916 CandidatePair.first->markAsReductionLike(RT);
1917 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001918 }
Tobias Grosser75805372011-04-29 06:27:02 +00001919}
1920
Tobias Grosser74394f02013-01-14 22:40:23 +00001921std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001922
Tobias Grosser54839312015-04-21 11:37:25 +00001923std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001924 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001925 if (!S)
1926 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001927 auto Str = stringFromIslObj(S);
1928 isl_map_free(S);
1929 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001930}
1931
Johannes Doerferta3519512016-04-23 13:02:23 +00001932void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1933 isl_set_free(InvalidDomain);
1934 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001935}
1936
Michael Kruse375cb5f2016-02-24 22:08:24 +00001937BasicBlock *ScopStmt::getEntryBlock() const {
1938 if (isBlockStmt())
1939 return getBasicBlock();
1940 return getRegion()->getEntry();
1941}
1942
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001943unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001944
Tobias Grosser75805372011-04-29 06:27:02 +00001945const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1946
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001947Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001948 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001949}
1950
Tobias Grosser74394f02013-01-14 22:40:23 +00001951isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001952
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001953__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001954
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001955__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001956 return isl_set_get_space(Domain);
1957}
1958
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001959__isl_give isl_id *ScopStmt::getDomainId() const {
1960 return isl_set_get_tuple_id(Domain);
1961}
Tobias Grossercd95b772012-08-30 11:49:38 +00001962
Johannes Doerfert7c013572016-04-12 09:57:34 +00001963ScopStmt::~ScopStmt() {
1964 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001965 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001966}
Tobias Grosser75805372011-04-29 06:27:02 +00001967
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001968void ScopStmt::printInstructions(raw_ostream &OS) const {
1969 OS << "Instructions {\n";
1970
1971 for (Instruction *Inst : Instructions)
1972 OS.indent(16) << *Inst << "\n";
1973
1974 OS.indent(16) << "}\n";
1975}
1976
Tobias Grosser75805372011-04-29 06:27:02 +00001977void ScopStmt::print(raw_ostream &OS) const {
1978 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001979 OS.indent(12) << "Domain :=\n";
1980
1981 if (Domain) {
1982 OS.indent(16) << getDomainStr() << ";\n";
1983 } else
1984 OS.indent(16) << "n/a\n";
1985
Tobias Grosser54839312015-04-21 11:37:25 +00001986 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001987
1988 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001989 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001990 } else
1991 OS.indent(16) << "n/a\n";
1992
Tobias Grosser083d3d32014-06-28 08:59:45 +00001993 for (MemoryAccess *Access : MemAccs)
1994 Access->print(OS);
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001995
1996 if (PollyPrintInstructions)
1997 printInstructions(OS.indent(12));
Tobias Grosser75805372011-04-29 06:27:02 +00001998}
1999
2000void ScopStmt::dump() const { print(dbgs()); }
2001
Michael Krusee60eca72017-05-11 22:56:12 +00002002void ScopStmt::removeAccessData(MemoryAccess *MA) {
2003 if (MA->isRead() && MA->isOriginalValueKind()) {
2004 bool Found = ValueReads.erase(MA->getAccessValue());
2005 (void)Found;
2006 assert(Found && "Expected access data not found");
2007 }
2008 if (MA->isWrite() && MA->isOriginalValueKind()) {
2009 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
2010 (void)Found;
2011 assert(Found && "Expected access data not found");
2012 }
2013 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
2014 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
2015 (void)Found;
2016 assert(Found && "Expected access data not found");
2017 }
Michael Kruse3562f272017-07-20 16:47:57 +00002018 if (MA->isRead() && MA->isOriginalAnyPHIKind()) {
2019 bool Found = PHIReads.erase(cast<PHINode>(MA->getAccessInstruction()));
2020 (void)Found;
2021 assert(Found && "Expected access data not found");
2022 }
Michael Krusee60eca72017-05-11 22:56:12 +00002023}
2024
Michael Kruse10071822016-05-23 14:45:58 +00002025void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00002026 // Remove the memory accesses from this statement together with all scalar
2027 // accesses that were caused by it. MemoryKind::Value READs have no access
2028 // instruction, hence would not be removed by this function. However, it is
2029 // only used for invariant LoadInst accesses, its arguments are always affine,
2030 // hence synthesizable, and therefore there are no MemoryKind::Value READ
2031 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00002032 auto Predicate = [&](MemoryAccess *Acc) {
2033 return Acc->getAccessInstruction() == MA->getAccessInstruction();
2034 };
Michael Krusee60eca72017-05-11 22:56:12 +00002035 for (auto *MA : MemAccs) {
Michael Kruse8b805802017-07-19 17:11:25 +00002036 if (Predicate(MA)) {
Michael Krusee60eca72017-05-11 22:56:12 +00002037 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00002038 Parent.removeAccessData(MA);
2039 }
Michael Krusee60eca72017-05-11 22:56:12 +00002040 }
Michael Kruse10071822016-05-23 14:45:58 +00002041 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
2042 MemAccs.end());
2043 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002044}
2045
Michael Kruse0446d812017-03-10 16:05:24 +00002046void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
2047 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
2048 assert(MAIt != MemAccs.end());
2049 MemAccs.erase(MAIt);
2050
Michael Krusee60eca72017-05-11 22:56:12 +00002051 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00002052 Parent.removeAccessData(MA);
Michael Krusee60eca72017-05-11 22:56:12 +00002053
Michael Kruse0446d812017-03-10 16:05:24 +00002054 auto It = InstructionToAccess.find(MA->getAccessInstruction());
2055 if (It != InstructionToAccess.end()) {
2056 It->second.remove(MA);
2057 if (It->second.empty())
2058 InstructionToAccess.erase(MA->getAccessInstruction());
2059 }
2060}
2061
Tobias Grosser75805372011-04-29 06:27:02 +00002062//===----------------------------------------------------------------------===//
2063/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00002064
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00002065void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00002066 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
2067 isl_set_free(Context);
2068 Context = NewContext;
2069}
2070
Eli Friedman5e589ea2017-06-20 22:53:02 +00002071namespace {
Tobias Grosserc80d6972016-09-02 06:33:33 +00002072/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002073struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00002074 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002075 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002076
2077public:
2078 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00002079 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002080
2081 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
2082 ValueToValueMap &VMap) {
2083 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
2084 return SSPR.visit(E);
2085 }
2086
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002087 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
2088 auto *Start = visit(E->getStart());
2089 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
2090 visit(E->getStepRecurrence(SE)),
2091 E->getLoop(), SCEV::FlagAnyWrap);
2092 return SE.getAddExpr(Start, AddRec);
2093 }
2094
2095 const SCEV *visitUnknown(const SCEVUnknown *E) {
2096 if (auto *NewValue = VMap.lookup(E->getValue()))
2097 return SE.getUnknown(NewValue);
2098 return E;
2099 }
2100};
2101
Eli Friedman5e589ea2017-06-20 22:53:02 +00002102/// Check whether we should remap a SCEV expression.
2103struct SCEVFindInsideScop : public SCEVTraversal<SCEVFindInsideScop> {
2104 ValueToValueMap &VMap;
2105 bool FoundInside = false;
2106 Scop *S;
2107
2108public:
2109 SCEVFindInsideScop(ValueToValueMap &VMap, ScalarEvolution &SE, Scop *S)
2110 : SCEVTraversal(*this), VMap(VMap), S(S) {}
2111
2112 static bool hasVariant(const SCEV *E, ScalarEvolution &SE,
2113 ValueToValueMap &VMap, Scop *S) {
2114 SCEVFindInsideScop SFIS(VMap, SE, S);
2115 SFIS.visitAll(E);
2116 return SFIS.FoundInside;
2117 }
2118
2119 bool follow(const SCEV *E) {
2120 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(E)) {
2121 FoundInside |= S->getRegion().contains(AddRec->getLoop());
2122 } else if (auto *Unknown = dyn_cast<SCEVUnknown>(E)) {
2123 if (Instruction *I = dyn_cast<Instruction>(Unknown->getValue()))
2124 FoundInside |= S->getRegion().contains(I) && !VMap.count(I);
2125 }
2126 return !FoundInside;
2127 }
2128 bool isDone() { return FoundInside; }
2129};
2130} // namespace
2131
2132const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *E) {
2133 // Check whether it makes sense to rewrite the SCEV. (ScalarEvolution
2134 // doesn't like addition between an AddRec and an expression that
2135 // doesn't have a dominance relationship with it.)
2136 if (SCEVFindInsideScop::hasVariant(E, *SE, InvEquivClassVMap, this))
2137 return E;
2138
2139 // Rewrite SCEV.
2140 return SCEVSensitiveParameterRewriter::rewrite(E, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002141}
2142
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002143// This table of function names is used to translate parameter names in more
2144// human-readable names. This makes it easier to interpret Polly analysis
2145// results.
2146StringMap<std::string> KnownNames = {
2147 {"_Z13get_global_idj", "global_id"},
2148 {"_Z12get_local_idj", "local_id"},
2149 {"_Z15get_global_sizej", "global_size"},
2150 {"_Z14get_local_sizej", "local_size"},
2151 {"_Z12get_work_dimv", "work_dim"},
2152 {"_Z17get_global_offsetj", "global_offset"},
2153 {"_Z12get_group_idj", "group_id"},
2154 {"_Z14get_num_groupsj", "num_groups"},
2155};
2156
2157static std::string getCallParamName(CallInst *Call) {
2158 std::string Result;
2159 raw_string_ostream OS(Result);
2160 std::string Name = Call->getCalledFunction()->getName();
2161
2162 auto Iterator = KnownNames.find(Name);
2163 if (Iterator != KnownNames.end())
Tobias Grosserdff902f2017-06-01 12:46:51 +00002164 Name = "__" + Iterator->getValue();
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002165 OS << Name;
2166 for (auto &Operand : Call->arg_operands()) {
2167 ConstantInt *Op = cast<ConstantInt>(&Operand);
2168 OS << "_" << Op->getValue();
2169 }
2170 OS.flush();
2171 return Result;
2172}
2173
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002174void Scop::createParameterId(const SCEV *Parameter) {
2175 assert(Parameters.count(Parameter));
2176 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002177
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002178 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002179
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002180 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
2181 Value *Val = ValueParameter->getValue();
2182 CallInst *Call = dyn_cast<CallInst>(Val);
Tobias Grosser8f99c162011-11-15 11:38:55 +00002183
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002184 if (Call && isConstCall(Call)) {
2185 ParameterName = getCallParamName(Call);
2186 } else if (UseInstructionNames) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002187 // If this parameter references a specific Value and this value has a name
2188 // we use this name as it is likely to be unique and more useful than just
2189 // a number.
2190 if (Val->hasName())
2191 ParameterName = Val->getName();
2192 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
2193 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
2194 if (LoadOrigin->hasName()) {
2195 ParameterName += "_loaded_from_";
2196 ParameterName +=
2197 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
2198 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002199 }
2200 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00002201
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002202 ParameterName = getIslCompatibleName("", ParameterName, "");
2203 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00002204
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002205 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
2206 const_cast<void *>((const void *)Parameter));
2207 ParameterIds[Parameter] = Id;
2208}
2209
2210void Scop::addParams(const ParameterSetTy &NewParameters) {
2211 for (const SCEV *Parameter : NewParameters) {
2212 // Normalize the SCEV to get the representing element for an invariant load.
2213 Parameter = extractConstantFactor(Parameter, *SE).second;
2214 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2215
2216 if (Parameters.insert(Parameter))
2217 createParameterId(Parameter);
2218 }
2219}
2220
2221__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
2222 // Normalize the SCEV to get the representing element for an invariant load.
2223 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2224 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00002225}
Tobias Grosser75805372011-04-29 06:27:02 +00002226
Michael Krused56b90a2016-09-01 09:03:27 +00002227__isl_give isl_set *
2228Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002229 isl_set *DomainContext = isl_union_set_params(getDomains());
2230 return isl_set_intersect_params(C, DomainContext);
2231}
2232
Johannes Doerferte0b08072016-05-23 12:43:44 +00002233bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2234 return DT.dominates(BB, getEntry());
2235}
2236
Michael Kruse476f8552017-06-29 12:47:41 +00002237void Scop::addUserAssumptions(
2238 AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002239 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse89b1f942017-03-17 13:56:53 +00002240 for (auto &Assumption : AC.assumptions()) {
2241 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2242 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002243 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002244
Michael Kruse89b1f942017-03-17 13:56:53 +00002245 bool InScop = contains(CI);
2246 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2247 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002248
Michael Kruse89b1f942017-03-17 13:56:53 +00002249 auto *L = LI.getLoopFor(CI->getParent());
2250 auto *Val = CI->getArgOperand(0);
2251 ParameterSetTy DetectedParams;
2252 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00002253 ORE.emit(
2254 OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreUserAssumption", CI)
2255 << "Non-affine user assumption ignored.");
Michael Kruse89b1f942017-03-17 13:56:53 +00002256 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002257 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002258
2259 // Collect all newly introduced parameters.
2260 ParameterSetTy NewParams;
2261 for (auto *Param : DetectedParams) {
2262 Param = extractConstantFactor(Param, *SE).second;
2263 Param = getRepresentingInvariantLoadSCEV(Param);
2264 if (Parameters.count(Param))
2265 continue;
2266 NewParams.insert(Param);
2267 }
2268
2269 SmallVector<isl_set *, 2> ConditionSets;
2270 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
2271 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
2272 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
Michael Kruse476f8552017-06-29 12:47:41 +00002273 bool Valid = buildConditionSets(*this, Stmt.getEntryBlock(), Val, TI, L,
2274 Dom, InvalidDomainMap, ConditionSets);
Michael Kruse89b1f942017-03-17 13:56:53 +00002275 isl_set_free(Dom);
2276
2277 if (!Valid)
2278 continue;
2279
2280 isl_set *AssumptionCtx = nullptr;
2281 if (InScop) {
2282 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2283 isl_set_free(ConditionSets[0]);
2284 } else {
2285 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2286 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2287 }
2288
2289 // Project out newly introduced parameters as they are not otherwise useful.
2290 if (!NewParams.empty()) {
2291 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2292 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2293 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2294 isl_id_free(Id);
2295
2296 if (!NewParams.count(Param))
2297 continue;
2298
2299 AssumptionCtx =
2300 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2301 }
2302 }
Eli Friedmane737fc12017-07-17 23:58:33 +00002303 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "UserAssumption", CI)
2304 << "Use user assumption: " << stringFromIslObj(AssumptionCtx));
Michael Kruse89b1f942017-03-17 13:56:53 +00002305 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002306 }
2307}
2308
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002309void Scop::addUserContext() {
2310 if (UserContextStr.empty())
2311 return;
2312
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002313 isl_set *UserContext =
2314 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002315 isl_space *Space = getParamSpace();
2316 if (isl_space_dim(Space, isl_dim_param) !=
2317 isl_set_dim(UserContext, isl_dim_param)) {
2318 auto SpaceStr = isl_space_to_str(Space);
2319 errs() << "Error: the context provided in -polly-context has not the same "
2320 << "number of dimensions than the computed context. Due to this "
2321 << "mismatch, the -polly-context option is ignored. Please provide "
2322 << "the context in the parameter space: " << SpaceStr << ".\n";
2323 free(SpaceStr);
2324 isl_set_free(UserContext);
2325 isl_space_free(Space);
2326 return;
2327 }
2328
2329 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002330 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2331 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002332
2333 if (strcmp(NameContext, NameUserContext) != 0) {
2334 auto SpaceStr = isl_space_to_str(Space);
2335 errs() << "Error: the name of dimension " << i
2336 << " provided in -polly-context "
2337 << "is '" << NameUserContext << "', but the name in the computed "
2338 << "context is '" << NameContext
2339 << "'. Due to this name mismatch, "
2340 << "the -polly-context option is ignored. Please provide "
2341 << "the context in the parameter space: " << SpaceStr << ".\n";
2342 free(SpaceStr);
2343 isl_set_free(UserContext);
2344 isl_space_free(Space);
2345 return;
2346 }
2347
2348 UserContext =
2349 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2350 isl_space_get_dim_id(Space, isl_dim_param, i));
2351 }
2352
2353 Context = isl_set_intersect(Context, UserContext);
2354 isl_space_free(Space);
2355}
2356
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002357void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002358 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002359
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002360 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002361 for (LoadInst *LInst : RIL) {
2362 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2363
Johannes Doerfert96e54712016-02-07 17:30:13 +00002364 Type *Ty = LInst->getType();
2365 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002366 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002367 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002368 continue;
2369 }
2370
2371 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002372 InvariantEquivClasses.emplace_back(
2373 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002374 }
2375}
2376
Tobias Grosser6be480c2011-11-08 15:41:13 +00002377void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002378 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002379 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002380 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002381 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002382}
2383
Tobias Grosser18daaca2012-05-22 10:47:27 +00002384void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002385 unsigned PDim = 0;
2386 for (auto *Parameter : Parameters) {
2387 ConstantRange SRange = SE->getSignedRange(Parameter);
Tobias Grosser99ea1d02017-05-21 20:23:20 +00002388 Context =
2389 addRangeBoundsToSet(give(Context), SRange, PDim++, isl::dim::param)
2390 .release();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002391 }
2392}
2393
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002394// We use the outermost dimension to generate GPU transfers for Fortran arrays
2395// even when the array bounds are not known statically. To do so, we need the
2396// outermost dimension information. We add this into the context so that the
2397// outermost dimension is available during codegen.
2398// We currently do not care about dimensions other than the outermost
2399// dimension since it doesn't affect transfers.
2400static isl_set *addFortranArrayOutermostDimParams(__isl_give isl_set *Context,
2401 Scop::array_range Arrays) {
2402
2403 std::vector<isl_id *> OutermostSizeIds;
2404 for (auto Array : Arrays) {
2405 // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2406 // for its outermost dimension. Fortran arrays will have this since the
2407 // outermost dimension size can be picked up from their runtime description.
2408 // TODO: actually need to check if it has a FAD, but for now this works.
2409 if (Array->getNumberOfDimensions() > 0) {
2410 isl_pw_aff *PwAff = Array->getDimensionSizePw(0);
2411 if (!PwAff)
2412 continue;
2413
2414 isl_id *Id = isl_pw_aff_get_dim_id(PwAff, isl_dim_param, 0);
2415 isl_pw_aff_free(PwAff);
2416 assert(Id && "Invalid Id for PwAff expression in Fortran array");
2417 OutermostSizeIds.push_back(Id);
2418 }
2419 }
2420
2421 const int NumTrueParams = isl_set_dim(Context, isl_dim_param);
2422 Context = isl_set_add_dims(Context, isl_dim_param, OutermostSizeIds.size());
2423
2424 for (size_t i = 0; i < OutermostSizeIds.size(); i++) {
2425 Context = isl_set_set_dim_id(Context, isl_dim_param, NumTrueParams + i,
2426 OutermostSizeIds[i]);
2427 Context =
2428 isl_set_lower_bound_si(Context, isl_dim_param, NumTrueParams + i, 0);
2429 }
2430
2431 return Context;
2432}
2433
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002434void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002435 if (PollyIgnoreParamBounds)
2436 return;
2437
Tobias Grosser6be480c2011-11-08 15:41:13 +00002438 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002439 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002440
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002441 unsigned PDim = 0;
2442 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002443 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002444 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002445 }
2446
2447 // Align the parameters of all data structures to the model.
2448 Context = isl_set_align_params(Context, Space);
2449
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002450 // Add the outermost dimension of the Fortran arrays into the Context.
2451 // See the description of the function for more information.
2452 Context = addFortranArrayOutermostDimParams(Context, arrays());
2453
Johannes Doerferta60ad842016-05-10 12:18:22 +00002454 // As all parameters are known add bounds to them.
2455 addParameterBounds();
2456
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002457 for (ScopStmt &Stmt : *this)
2458 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002459 // Simplify the schedule according to the context too.
2460 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002461}
2462
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002463static __isl_give isl_set *
2464simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2465 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002466 // If we have modeled all blocks in the SCoP that have side effects we can
2467 // simplify the context with the constraints that are needed for anything to
2468 // be executed at all. However, if we have error blocks in the SCoP we already
2469 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002470 // domains, thus we cannot use the remaining domain to simplify the
2471 // assumptions.
2472 if (!S.hasErrorBlock()) {
2473 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2474 AssumptionContext =
2475 isl_set_gist_params(AssumptionContext, DomainParameters);
2476 }
2477
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002478 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2479 return AssumptionContext;
2480}
2481
2482void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002483 // The parameter constraints of the iteration domains give us a set of
2484 // constraints that need to hold for all cases where at least a single
2485 // statement iteration is executed in the whole scop. We now simplify the
2486 // assumed context under the assumption that such constraints hold and at
2487 // least a single statement iteration is executed. For cases where no
2488 // statement instances are executed, the assumptions we have taken about
2489 // the executed code do not matter and can be changed.
2490 //
2491 // WARNING: This only holds if the assumptions we have taken do not reduce
2492 // the set of statement instances that are executed. Otherwise we
2493 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002494 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002495 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002496 // performed. In such a case, modifying the run-time conditions and
2497 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002498 // to not be executed.
2499 //
2500 // Example:
2501 //
2502 // When delinearizing the following code:
2503 //
2504 // for (long i = 0; i < 100; i++)
2505 // for (long j = 0; j < m; j++)
2506 // A[i+p][j] = 1.0;
2507 //
2508 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002509 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002510 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002511 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002512 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002513}
2514
Tobias Grosserc80d6972016-09-02 06:33:33 +00002515/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002516static isl::stat
2517buildMinMaxAccess(isl::set Set, Scop::MinMaxVectorTy &MinMaxAccesses, Scop &S) {
2518 isl::pw_multi_aff MinPMA, MaxPMA;
2519 isl::pw_aff LastDimAff;
2520 isl::aff OneAff;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002521 unsigned Pos;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002522 isl::ctx Ctx = Set.get_ctx();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002523
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002524 Set = Set.remove_divs();
Johannes Doerfert6296d952016-04-22 11:38:19 +00002525
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002526 if (isl_set_n_basic_set(Set.get()) >= MaxDisjunctsInDomain)
2527 return isl::stat::error;
Johannes Doerfert6296d952016-04-22 11:38:19 +00002528
Johannes Doerfert9143d672014-09-27 11:02:39 +00002529 // Restrict the number of parameters involved in the access as the lexmin/
2530 // lexmax computation will take too long if this number is high.
2531 //
2532 // Experiments with a simple test case using an i7 4800MQ:
2533 //
2534 // #Parameters involved | Time (in sec)
2535 // 6 | 0.01
2536 // 7 | 0.04
2537 // 8 | 0.12
2538 // 9 | 0.40
2539 // 10 | 1.54
2540 // 11 | 6.78
2541 // 12 | 30.38
2542 //
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002543 if (isl_set_n_param(Set.get()) > RunTimeChecksMaxParameters) {
Johannes Doerfert9143d672014-09-27 11:02:39 +00002544 unsigned InvolvedParams = 0;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002545 for (unsigned u = 0, e = isl_set_n_param(Set.get()); u < e; u++)
2546 if (Set.involves_dims(isl::dim::param, u, 1))
Johannes Doerfert9143d672014-09-27 11:02:39 +00002547 InvolvedParams++;
2548
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002549 if (InvolvedParams > RunTimeChecksMaxParameters)
2550 return isl::stat::error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002551 }
2552
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +00002553 if (isl_set_n_basic_set(Set.get()) > RunTimeChecksMaxAccessDisjuncts)
2554 return isl::stat::error;
2555
Tobias Grosser57a1d362017-06-23 08:05:27 +00002556 MinPMA = Set.lexmin_pw_multi_aff();
2557 MaxPMA = Set.lexmax_pw_multi_aff();
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002558
Tobias Grosser57a1d362017-06-23 08:05:27 +00002559 if (isl_ctx_last_error(Ctx.get()) == isl_error_quota)
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002560 return isl::stat::error;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002561
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002562 MinPMA = MinPMA.coalesce();
2563 MaxPMA = MaxPMA.coalesce();
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002564
Johannes Doerfertb164c792014-09-18 11:17:17 +00002565 // Adjust the last dimension of the maximal access by one as we want to
2566 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2567 // we test during code generation might now point after the end of the
2568 // allocated array but we will never dereference it anyway.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002569 assert(MaxPMA.dim(isl::dim::out) && "Assumed at least one output dimension");
2570 Pos = MaxPMA.dim(isl::dim::out) - 1;
2571 LastDimAff = MaxPMA.get_pw_aff(Pos);
2572 OneAff = isl::aff(isl::local_space(LastDimAff.get_domain_space()));
2573 OneAff = OneAff.add_constant_si(1);
2574 LastDimAff = LastDimAff.add(OneAff);
2575 MaxPMA = MaxPMA.set_pw_aff(Pos, LastDimAff);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002576
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002577 MinMaxAccesses.push_back(std::make_pair(MinPMA.copy(), MaxPMA.copy()));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002578
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002579 return isl::stat::ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002580}
2581
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002582static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2583 isl_set *Domain = MA->getStatement()->getDomain();
2584 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2585 return isl_set_reset_tuple_id(Domain);
2586}
2587
Tobias Grosserc80d6972016-09-02 06:33:33 +00002588/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002589static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002590 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002591
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002592 MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002593
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002594 isl::union_set Domains = give(S.getDomains());
2595 isl::union_map Accesses = isl::union_map::empty(give(S.getParamSpace()));
Tobias Grossere9522232017-01-16 15:49:04 +00002596
2597 for (MemoryAccess *MA : AliasGroup)
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002598 Accesses = Accesses.add_map(give(MA->getAccessRelation()));
Tobias Grossere9522232017-01-16 15:49:04 +00002599
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002600 Accesses = Accesses.intersect_domain(Domains);
2601 isl::union_set Locations = Accesses.range();
2602 Locations = Locations.coalesce();
2603 Locations = Locations.detect_equalities();
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002604
2605 auto Lambda = [&MinMaxAccesses, &S](isl::set Set) -> isl::stat {
2606 return buildMinMaxAccess(Set, MinMaxAccesses, S);
2607 };
2608 return Locations.foreach_set(Lambda) == isl::stat::ok;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002609}
2610
Tobias Grosserc80d6972016-09-02 06:33:33 +00002611/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002612///
2613///{
2614
Tobias Grosserc80d6972016-09-02 06:33:33 +00002615/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002616static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2617 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2618 : RN->getNodeAs<BasicBlock>();
2619}
2620
Tobias Grosserc80d6972016-09-02 06:33:33 +00002621/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002622static inline BasicBlock *
2623getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002624 if (RN->isSubRegion()) {
2625 assert(idx == 0);
2626 return RN->getNodeAs<Region>()->getExit();
2627 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002628 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002629}
2630
Tobias Grosserc80d6972016-09-02 06:33:33 +00002631/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002632static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002633 if (!RN->isSubRegion()) {
2634 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2635 Loop *L = LI.getLoopFor(BB);
2636
2637 // Unreachable statements are not considered to belong to a LLVM loop, as
2638 // they are not part of an actual loop in the control flow graph.
2639 // Nevertheless, we handle certain unreachable statements that are common
2640 // when modeling run-time bounds checks as being part of the loop to be
2641 // able to model them and to later eliminate the run-time bounds checks.
2642 //
2643 // Specifically, for basic blocks that terminate in an unreachable and
Michael Krusea6d48f52017-06-08 12:06:15 +00002644 // where the immediate predecessor is part of a loop, we assume these
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002645 // basic blocks belong to the loop the predecessor belongs to. This
2646 // allows us to model the following code.
2647 //
2648 // for (i = 0; i < N; i++) {
2649 // if (i > 1024)
2650 // abort(); <- this abort might be translated to an
2651 // unreachable
2652 //
2653 // A[i] = ...
2654 // }
2655 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2656 L = LI.getLoopFor(BB->getPrevNode());
2657 return L;
2658 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002659
2660 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2661 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2662 while (L && NonAffineSubRegion->contains(L))
2663 L = L->getParentLoop();
2664 return L;
2665}
2666
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002667/// Get the number of blocks in @p L.
2668///
2669/// The number of blocks in a loop are the number of basic blocks actually
2670/// belonging to the loop, as well as all single basic blocks that the loop
2671/// exits to and which terminate in an unreachable instruction. We do not
2672/// allow such basic blocks in the exit of a scop, hence they belong to the
2673/// scop and represent run-time conditions which we want to model and
2674/// subsequently speculate away.
2675///
2676/// @see getRegionNodeLoop for additional details.
Reid Klecknerdf2b2832017-06-19 17:44:02 +00002677unsigned getNumBlocksInLoop(Loop *L) {
2678 unsigned NumBlocks = L->getNumBlocks();
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002679 SmallVector<llvm::BasicBlock *, 4> ExitBlocks;
2680 L->getExitBlocks(ExitBlocks);
2681
2682 for (auto ExitBlock : ExitBlocks) {
2683 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2684 NumBlocks++;
2685 }
2686 return NumBlocks;
2687}
2688
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002689static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2690 if (!RN->isSubRegion())
2691 return 1;
2692
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002693 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002694 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002695}
2696
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002697static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2698 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002699 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002700 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002701 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002702 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002703 return true;
2704 return false;
2705}
2706
Johannes Doerfert96425c22015-08-30 21:13:53 +00002707///}
2708
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002709static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2710 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002711 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002712 isl_id *DimId =
2713 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2714 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2715}
2716
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002717__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002718 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002719}
2720
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002721__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002722 auto DIt = DomainMap.find(BB);
2723 if (DIt != DomainMap.end())
Tobias Grosser325204a32017-07-15 12:41:32 +00002724 return DIt->getSecond().copy();
Johannes Doerfert41cda152016-04-08 10:32:26 +00002725
2726 auto &RI = *R.getRegionInfo();
2727 auto *BBR = RI.getRegionFor(BB);
2728 while (BBR->getEntry() == BB)
2729 BBR = BBR->getParent();
2730 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002731}
2732
Tobias Grosser13acbb92017-07-15 09:01:31 +00002733bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI,
2734 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002735
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002736 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002737 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002738 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2739 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002740 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002741
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002742 while (LD-- >= 0) {
2743 S = addDomainDimId(S, LD + 1, L);
2744 L = L->getParentLoop();
2745 }
2746
Tobias Grosser13acbb92017-07-15 09:01:31 +00002747 InvalidDomainMap[EntryBB] = isl::manage(isl_set_empty(isl_set_get_space(S)));
Tobias Grosser325204a32017-07-15 12:41:32 +00002748 DomainMap[EntryBB] = isl::manage(S);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002749
Johannes Doerfert432658d2016-01-26 11:01:41 +00002750 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002751 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002752
Michael Kruse476f8552017-06-29 12:47:41 +00002753 if (!buildDomainsWithBranchConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002754 return false;
2755
Michael Kruse476f8552017-06-29 12:47:41 +00002756 if (!propagateDomainConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002757 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002758
2759 // Error blocks and blocks dominated by them have been assumed to never be
2760 // executed. Representing them in the Scop does not add any value. In fact,
2761 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002762 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002763 // will cause problems when building up a ScopStmt for them.
2764 // Furthermore, basic blocks dominated by error blocks may reference
2765 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002766 // can themselves not be constructed properly. To this end we will replace
2767 // the domains of error blocks and those only reachable via error blocks
2768 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002769 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002770 // InvalidDomain. This information is needed during load hoisting.
Michael Kruse476f8552017-06-29 12:47:41 +00002771 if (!propagateInvalidStmtDomains(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002772 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002773
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002774 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002775}
2776
Tobias Grosserc80d6972016-09-02 06:33:33 +00002777/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002778/// to be compatible to domains constructed for loop @p NewL.
2779///
2780/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2781/// edge from @p OldL to @p NewL.
2782static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2783 __isl_take isl_set *Dom,
2784 Loop *OldL, Loop *NewL) {
2785
2786 // If the loops are the same there is nothing to do.
2787 if (NewL == OldL)
2788 return Dom;
2789
2790 int OldDepth = S.getRelativeLoopDepth(OldL);
2791 int NewDepth = S.getRelativeLoopDepth(NewL);
2792 // If both loops are non-affine loops there is nothing to do.
2793 if (OldDepth == -1 && NewDepth == -1)
2794 return Dom;
2795
2796 // Distinguish three cases:
2797 // 1) The depth is the same but the loops are not.
2798 // => One loop was left one was entered.
2799 // 2) The depth increased from OldL to NewL.
2800 // => One loop was entered, none was left.
2801 // 3) The depth decreased from OldL to NewL.
2802 // => Loops were left were difference of the depths defines how many.
2803 if (OldDepth == NewDepth) {
2804 assert(OldL->getParentLoop() == NewL->getParentLoop());
2805 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2806 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2807 Dom = addDomainDimId(Dom, NewDepth, NewL);
2808 } else if (OldDepth < NewDepth) {
2809 assert(OldDepth + 1 == NewDepth);
2810 auto &R = S.getRegion();
2811 (void)R;
2812 assert(NewL->getParentLoop() == OldL ||
2813 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2814 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2815 Dom = addDomainDimId(Dom, NewDepth, NewL);
2816 } else {
2817 assert(OldDepth > NewDepth);
2818 int Diff = OldDepth - NewDepth;
2819 int NumDim = isl_set_n_dim(Dom);
2820 assert(NumDim >= Diff);
2821 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2822 }
2823
2824 return Dom;
2825}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002826
Michael Kruse476f8552017-06-29 12:47:41 +00002827bool Scop::propagateInvalidStmtDomains(
2828 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002829 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse476f8552017-06-29 12:47:41 +00002830
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002831 ReversePostOrderTraversal<Region *> RTraversal(R);
2832 for (auto *RN : RTraversal) {
2833
2834 // Recurse for affine subregions but go on for basic blocks and non-affine
2835 // subregions.
2836 if (RN->isSubRegion()) {
2837 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002838 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002839 propagateInvalidStmtDomains(SubRegion, DT, LI, InvalidDomainMap);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002840 continue;
2841 }
2842 }
2843
2844 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2845 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00002846 isl::set &Domain = DomainMap[BB];
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002847 assert(Domain && "Cannot propagate a nullptr");
2848
Tobias Grosser325204a32017-07-15 12:41:32 +00002849 isl::set InvalidDomain = InvalidDomainMap[BB];
Michael Kruse476f8552017-06-29 12:47:41 +00002850
Tobias Grosser325204a32017-07-15 12:41:32 +00002851 bool IsInvalidBlock = ContainsErrorBlock || Domain.is_subset(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002852
Johannes Doerferta3519512016-04-23 13:02:23 +00002853 if (!IsInvalidBlock) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002854 InvalidDomain = InvalidDomain.intersect(Domain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002855 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002856 InvalidDomain = Domain;
Tobias Grosser325204a32017-07-15 12:41:32 +00002857 isl::set DomPar = Domain.params();
2858 recordAssumption(ERRORBLOCK, DomPar.release(),
2859 BB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002860 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002861 }
2862
Tobias Grosser325204a32017-07-15 12:41:32 +00002863 if (InvalidDomain.is_empty()) {
2864 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002865 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002866 }
2867
Johannes Doerferta3519512016-04-23 13:02:23 +00002868 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002869 auto *TI = BB->getTerminator();
2870 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2871 for (unsigned u = 0; u < NumSuccs; u++) {
2872 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002873
2874 // Skip successors outside the SCoP.
Michael Kruse476f8552017-06-29 12:47:41 +00002875 if (!contains(SuccBB))
Johannes Doerfert7c013572016-04-12 09:57:34 +00002876 continue;
2877
Johannes Doerferte4459a22016-04-25 13:34:50 +00002878 // Skip backedges.
2879 if (DT.dominates(SuccBB, BB))
2880 continue;
2881
Michael Kruse476f8552017-06-29 12:47:41 +00002882 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2883
Johannes Doerferta3519512016-04-23 13:02:23 +00002884 auto *AdjustedInvalidDomain = adjustDomainDimensions(
Tobias Grosser325204a32017-07-15 12:41:32 +00002885 *this, InvalidDomain.copy(), BBLoop, SuccBBLoop);
Michael Kruse476f8552017-06-29 12:47:41 +00002886
Tobias Grosser13acbb92017-07-15 09:01:31 +00002887 auto *SuccInvalidDomain = InvalidDomainMap[SuccBB].copy();
Johannes Doerferta3519512016-04-23 13:02:23 +00002888 SuccInvalidDomain =
2889 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2890 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2891 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
Michael Kruse476f8552017-06-29 12:47:41 +00002892
Tobias Grosser13acbb92017-07-15 09:01:31 +00002893 InvalidDomainMap[SuccBB] = isl::manage(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002894
Michael Krusebc150122016-05-02 12:25:18 +00002895 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002896 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002897 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002898 continue;
2899
Tobias Grosserf44f0052017-07-09 15:47:17 +00002900 InvalidDomainMap.erase(BB);
Eli Friedmane737fc12017-07-17 23:58:33 +00002901 invalidate(COMPLEXITY, TI->getDebugLoc(), TI->getParent());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002902 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002903 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002904
Tobias Grosser325204a32017-07-15 12:41:32 +00002905 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002906 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002907
2908 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002909}
2910
Johannes Doerfert642594a2016-04-04 07:57:39 +00002911void Scop::propagateDomainConstraintsToRegionExit(
2912 BasicBlock *BB, Loop *BBLoop,
Michael Kruse476f8552017-06-29 12:47:41 +00002913 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002914 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002915
2916 // Check if the block @p BB is the entry of a region. If so we propagate it's
2917 // domain to the exit block of the region. Otherwise we are done.
2918 auto *RI = R.getRegionInfo();
2919 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2920 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002921 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002922 return;
2923
Johannes Doerfert642594a2016-04-04 07:57:39 +00002924 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002925 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002926 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002927 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002928 SmallVector<BasicBlock *, 4> LatchBBs;
2929 BBLoop->getLoopLatches(LatchBBs);
2930 for (auto *LatchBB : LatchBBs)
2931 if (BB != LatchBB && BBReg->contains(LatchBB))
2932 return;
2933 L = L->getParentLoop();
2934 }
2935
Tobias Grosser325204a32017-07-15 12:41:32 +00002936 isl::set Domain = DomainMap[BB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002937 assert(Domain && "Cannot propagate a nullptr");
2938
Michael Kruse476f8552017-06-29 12:47:41 +00002939 Loop *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002940
2941 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2942 // adjust the domain before we can propagate it.
Tobias Grosser325204a32017-07-15 12:41:32 +00002943 isl::set AdjustedDomain = isl::manage(
2944 adjustDomainDimensions(*this, Domain.copy(), BBLoop, ExitBBLoop));
2945 isl::set &ExitDomain = DomainMap[ExitBB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002946
2947 // If the exit domain is not yet created we set it otherwise we "add" the
2948 // current domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002949 ExitDomain = ExitDomain ? AdjustedDomain.unite(ExitDomain) : AdjustedDomain;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002950
Johannes Doerferta3519512016-04-23 13:02:23 +00002951 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002952 InvalidDomainMap[ExitBB] = ExitDomain.empty(ExitDomain.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002953
Johannes Doerfert642594a2016-04-04 07:57:39 +00002954 FinishedExitBlocks.insert(ExitBB);
2955}
2956
Michael Kruse476f8552017-06-29 12:47:41 +00002957bool Scop::buildDomainsWithBranchConstraints(
2958 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002959 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse476f8552017-06-29 12:47:41 +00002960
Johannes Doerfert96425c22015-08-30 21:13:53 +00002961 // To create the domain for each block in R we iterate over all blocks and
2962 // subregions in R and propagate the conditions under which the current region
2963 // element is executed. To this end we iterate in reverse post order over R as
2964 // it ensures that we first visit all predecessors of a region node (either a
2965 // basic block or a subregion) before we visit the region node itself.
2966 // Initially, only the domain for the SCoP region entry block is set and from
2967 // there we propagate the current domain to all successors, however we add the
2968 // condition that the successor is actually executed next.
2969 // As we are only interested in non-loop carried constraints here we can
2970 // simply skip loop back edges.
2971
Johannes Doerfert642594a2016-04-04 07:57:39 +00002972 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002973 ReversePostOrderTraversal<Region *> RTraversal(R);
2974 for (auto *RN : RTraversal) {
2975
2976 // Recurse for affine subregions but go on for basic blocks and non-affine
2977 // subregions.
2978 if (RN->isSubRegion()) {
2979 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002980 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002981 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI,
2982 InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002983 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002984 continue;
2985 }
2986 }
2987
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002988 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002989 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002990
Johannes Doerfert96425c22015-08-30 21:13:53 +00002991 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002992 TerminatorInst *TI = BB->getTerminator();
2993
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002994 if (isa<UnreachableInst>(TI))
2995 continue;
2996
Tobias Grosser325204a32017-07-15 12:41:32 +00002997 isl::set Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002998 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002999 continue;
Tobias Grosser325204a32017-07-15 12:41:32 +00003000 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain.get()));
Johannes Doerfert96425c22015-08-30 21:13:53 +00003001
Johannes Doerfert642594a2016-04-04 07:57:39 +00003002 auto *BBLoop = getRegionNodeLoop(RN, LI);
3003 // Propagate the domain from BB directly to blocks that have a superset
3004 // domain, at the moment only region exit nodes of regions that start in BB.
Michael Kruse476f8552017-06-29 12:47:41 +00003005 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI,
3006 InvalidDomainMap);
Johannes Doerfert642594a2016-04-04 07:57:39 +00003007
3008 // If all successors of BB have been set a domain through the propagation
3009 // above we do not need to build condition sets but can just skip this
3010 // block. However, it is important to note that this is a local property
3011 // with regards to the region @p R. To this end FinishedExitBlocks is a
3012 // local variable.
3013 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
3014 return FinishedExitBlocks.count(SuccBB);
3015 };
3016 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
3017 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003018
3019 // Build the condition sets for the successor nodes of the current region
3020 // node. If it is a non-affine subregion we will always execute the single
3021 // exit node, hence the single entry node domain is the condition set. For
3022 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003023 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003024 if (RN->isSubRegion())
Tobias Grosser325204a32017-07-15 12:41:32 +00003025 ConditionSets.push_back(Domain.copy());
3026 else if (!buildConditionSets(*this, BB, TI, BBLoop, Domain.get(),
Michael Kruse476f8552017-06-29 12:47:41 +00003027 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003028 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003029
3030 // Now iterate over the successors and set their initial domain based on
3031 // their condition set. We skip back edges here and have to be careful when
3032 // we leave a loop not to keep constraints over a dimension that doesn't
3033 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003034 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00003035 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Tobias Grosser325204a32017-07-15 12:41:32 +00003036 isl::set CondSet = isl::manage(ConditionSets[u]);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003037 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003038
Johannes Doerfert535de032016-04-19 14:49:05 +00003039 // Skip blocks outside the region.
Tobias Grosser325204a32017-07-15 12:41:32 +00003040 if (!contains(SuccBB))
Johannes Doerfert535de032016-04-19 14:49:05 +00003041 continue;
Johannes Doerfert535de032016-04-19 14:49:05 +00003042
Johannes Doerfert642594a2016-04-04 07:57:39 +00003043 // If we propagate the domain of some block to "SuccBB" we do not have to
3044 // adjust the domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00003045 if (FinishedExitBlocks.count(SuccBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00003046 continue;
Johannes Doerfert642594a2016-04-04 07:57:39 +00003047
Johannes Doerfert96425c22015-08-30 21:13:53 +00003048 // Skip back edges.
Tobias Grosser325204a32017-07-15 12:41:32 +00003049 if (DT.dominates(SuccBB, BB))
Johannes Doerfert96425c22015-08-30 21:13:53 +00003050 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003051
Michael Kruse476f8552017-06-29 12:47:41 +00003052 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
3053
Tobias Grosser325204a32017-07-15 12:41:32 +00003054 CondSet = isl::manage(
3055 adjustDomainDimensions(*this, CondSet.copy(), BBLoop, SuccBBLoop));
Johannes Doerfert96425c22015-08-30 21:13:53 +00003056
3057 // Set the domain for the successor or merge it with an existing domain in
3058 // case there are multiple paths (without loop back edges) to the
3059 // successor block.
Tobias Grosser325204a32017-07-15 12:41:32 +00003060 isl::set &SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00003061
Johannes Doerferta3519512016-04-23 13:02:23 +00003062 if (SuccDomain) {
Tobias Grosser325204a32017-07-15 12:41:32 +00003063 SuccDomain = SuccDomain.unite(CondSet).coalesce();
Johannes Doerferta3519512016-04-23 13:02:23 +00003064 } else {
3065 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00003066 InvalidDomainMap[SuccBB] = CondSet.empty(CondSet.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00003067 SuccDomain = CondSet;
3068 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00003069
Tobias Grosser325204a32017-07-15 12:41:32 +00003070 SuccDomain = SuccDomain.detect_equalities();
Tobias Grosser6d459c52017-05-23 04:26:28 +00003071
Michael Krusebc150122016-05-02 12:25:18 +00003072 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003073 // In case this happens we will clean up and bail.
Tobias Grosser325204a32017-07-15 12:41:32 +00003074 if (isl_set_n_basic_set(SuccDomain.get()) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003075 continue;
3076
3077 invalidate(COMPLEXITY, DebugLoc());
3078 while (++u < ConditionSets.size())
3079 isl_set_free(ConditionSets[u]);
3080 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003081 }
3082 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003083
3084 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003085}
3086
Michael Krused56b90a2016-09-01 09:03:27 +00003087__isl_give isl_set *
3088Scop::getPredecessorDomainConstraints(BasicBlock *BB,
3089 __isl_keep isl_set *Domain,
3090 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00003091 // If @p BB is the ScopEntry we are done
3092 if (R.getEntry() == BB)
3093 return isl_set_universe(isl_set_get_space(Domain));
3094
Johannes Doerfert642594a2016-04-04 07:57:39 +00003095 // The region info of this function.
3096 auto &RI = *R.getRegionInfo();
3097
Michael Kruse476f8552017-06-29 12:47:41 +00003098 Loop *BBLoop = getFirstNonBoxedLoopFor(BB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00003099
3100 // A domain to collect all predecessor domains, thus all conditions under
3101 // which the block is executed. To this end we start with the empty domain.
3102 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
3103
3104 // Set of regions of which the entry block domain has been propagated to BB.
3105 // all predecessors inside any of the regions can be skipped.
3106 SmallSet<Region *, 8> PropagatedRegions;
3107
3108 for (auto *PredBB : predecessors(BB)) {
3109 // Skip backedges.
3110 if (DT.dominates(BB, PredBB))
3111 continue;
3112
3113 // If the predecessor is in a region we used for propagation we can skip it.
3114 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
3115 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
3116 PredBBInRegion)) {
3117 continue;
3118 }
3119
3120 // Check if there is a valid region we can use for propagation, thus look
3121 // for a region that contains the predecessor and has @p BB as exit block.
3122 auto *PredR = RI.getRegionFor(PredBB);
3123 while (PredR->getExit() != BB && !PredR->contains(BB))
3124 PredR->getParent();
3125
3126 // If a valid region for propagation was found use the entry of that region
3127 // for propagation, otherwise the PredBB directly.
3128 if (PredR->getExit() == BB) {
3129 PredBB = PredR->getEntry();
3130 PropagatedRegions.insert(PredR);
3131 }
3132
Johannes Doerfert41cda152016-04-08 10:32:26 +00003133 auto *PredBBDom = getDomainConditions(PredBB);
Michael Kruse476f8552017-06-29 12:47:41 +00003134 Loop *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, getBoxedLoops());
3135
Johannes Doerfert642594a2016-04-04 07:57:39 +00003136 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
3137
3138 PredDom = isl_set_union(PredDom, PredBBDom);
3139 }
3140
3141 return PredDom;
3142}
3143
Michael Kruse476f8552017-06-29 12:47:41 +00003144bool Scop::propagateDomainConstraints(
3145 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00003146 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003147 // Iterate over the region R and propagate the domain constrains from the
3148 // predecessors to the current node. In contrast to the
3149 // buildDomainsWithBranchConstraints function, this one will pull the domain
3150 // information from the predecessors instead of pushing it to the successors.
3151 // Additionally, we assume the domains to be already present in the domain
3152 // map here. However, we iterate again in reverse post order so we know all
3153 // predecessors have been visited before a block or non-affine subregion is
3154 // visited.
3155
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003156 ReversePostOrderTraversal<Region *> RTraversal(R);
3157 for (auto *RN : RTraversal) {
3158
3159 // Recurse for affine subregions but go on for basic blocks and non-affine
3160 // subregions.
3161 if (RN->isSubRegion()) {
3162 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003163 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00003164 if (!propagateDomainConstraints(SubRegion, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003165 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003166 continue;
3167 }
3168 }
3169
3170 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00003171 isl::set &Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00003172 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003173
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003174 // Under the union of all predecessor conditions we can reach this block.
Tobias Grosser325204a32017-07-15 12:41:32 +00003175 isl::set PredDom =
3176 isl::manage(getPredecessorDomainConstraints(BB, Domain.get(), DT, LI));
3177 Domain = Domain.intersect(PredDom).coalesce();
3178 Domain = Domain.align_params(isl::manage(getParamSpace()));
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003179
Johannes Doerfert642594a2016-04-04 07:57:39 +00003180 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00003181 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Michael Kruse476f8552017-06-29 12:47:41 +00003182 if (!addLoopBoundsToHeaderDomain(BBLoop, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003183 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003184 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00003185
3186 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003187}
3188
Tobias Grosserc80d6972016-09-02 06:33:33 +00003189/// Create a map to map from a given iteration to a subsequent iteration.
3190///
3191/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
3192/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003193/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00003194///
3195/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003196static __isl_give isl_map *
3197createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
3198 auto *MapSpace = isl_space_map_from_set(SetSpace);
3199 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00003200 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003201 if (u != Dim)
3202 NextIterationMap =
3203 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
3204 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
3205 C = isl_constraint_set_constant_si(C, 1);
3206 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
3207 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
3208 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
3209 return NextIterationMap;
3210}
3211
Michael Kruse476f8552017-06-29 12:47:41 +00003212bool Scop::addLoopBoundsToHeaderDomain(
Tobias Grosser13acbb92017-07-15 09:01:31 +00003213 Loop *L, LoopInfo &LI, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003214 int LoopDepth = getRelativeLoopDepth(L);
3215 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003216
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003217 BasicBlock *HeaderBB = L->getHeader();
3218 assert(DomainMap.count(HeaderBB));
Tobias Grosser325204a32017-07-15 12:41:32 +00003219 isl::set &HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003220
Tobias Grosser325204a32017-07-15 12:41:32 +00003221 isl::map NextIterationMap = isl::manage(
3222 createNextIterationMap(HeaderBBDom.get_space().release(), LoopDepth));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003223
Tobias Grosser325204a32017-07-15 12:41:32 +00003224 isl::set UnionBackedgeCondition = HeaderBBDom.empty(HeaderBBDom.get_space());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003225
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003226 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
3227 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003228
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003229 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003230
3231 // If the latch is only reachable via error statements we skip it.
Tobias Grosser325204a32017-07-15 12:41:32 +00003232 isl::set LatchBBDom = DomainMap.lookup(LatchBB);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003233 if (!LatchBBDom)
3234 continue;
3235
Tobias Grosser325204a32017-07-15 12:41:32 +00003236 isl::set BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003237
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003238 TerminatorInst *TI = LatchBB->getTerminator();
3239 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00003240 assert(BI && "Only branch instructions allowed in loop latches");
3241
3242 if (BI->isUnconditional())
Tobias Grosser325204a32017-07-15 12:41:32 +00003243 BackedgeCondition = LatchBBDom;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003244 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003245 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003246 int idx = BI->getSuccessor(0) != HeaderBB;
Tobias Grosser325204a32017-07-15 12:41:32 +00003247 if (!buildConditionSets(*this, LatchBB, TI, L, LatchBBDom.get(),
3248 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003249 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003250
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003251 // Free the non back edge condition set as we do not need it.
3252 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003253
Tobias Grosser325204a32017-07-15 12:41:32 +00003254 BackedgeCondition = isl::manage(ConditionSets[idx]);
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003255 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003256
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003257 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3258 assert(LatchLoopDepth >= LoopDepth);
Tobias Grosser325204a32017-07-15 12:41:32 +00003259 BackedgeCondition = BackedgeCondition.project_out(
3260 isl::dim::set, LoopDepth + 1, LatchLoopDepth - LoopDepth);
3261 UnionBackedgeCondition = UnionBackedgeCondition.unite(BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003262 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003263
Tobias Grosser325204a32017-07-15 12:41:32 +00003264 isl::map ForwardMap = ForwardMap.lex_le(HeaderBBDom.get_space());
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003265 for (int i = 0; i < LoopDepth; i++)
Tobias Grosser325204a32017-07-15 12:41:32 +00003266 ForwardMap = ForwardMap.equate(isl::dim::in, i, isl::dim::out, i);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003267
Tobias Grosser325204a32017-07-15 12:41:32 +00003268 isl::set UnionBackedgeConditionComplement =
3269 UnionBackedgeCondition.complement();
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003270 UnionBackedgeConditionComplement =
Tobias Grosser325204a32017-07-15 12:41:32 +00003271 UnionBackedgeConditionComplement.lower_bound_si(isl::dim::set, LoopDepth,
3272 0);
3273 UnionBackedgeConditionComplement =
3274 UnionBackedgeConditionComplement.apply(ForwardMap);
3275 HeaderBBDom = HeaderBBDom.subtract(UnionBackedgeConditionComplement);
3276 HeaderBBDom = HeaderBBDom.apply(NextIterationMap);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003277
Tobias Grosser325204a32017-07-15 12:41:32 +00003278 auto Parts = partitionSetParts(HeaderBBDom.copy(), LoopDepth);
3279 HeaderBBDom = isl::manage(Parts.second);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003280
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003281 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3282 // the bounded assumptions to the context as they are already implied by the
3283 // <nsw> tag.
3284 if (Affinator.hasNSWAddRecForLoop(L)) {
3285 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003286 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003287 }
3288
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003289 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003290 recordAssumption(INFINITELOOP, UnboundedCtx,
3291 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003292 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003293}
3294
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003295MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003296 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003297
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003298 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003299 if (!PointerBaseInst)
3300 return nullptr;
3301
3302 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3303 if (!BasePtrStmt)
3304 return nullptr;
3305
3306 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3307}
3308
3309bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
Tobias Grosser4071cb52017-06-06 23:13:02 +00003310 isl::union_map Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003311 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003312 return getNonHoistableCtx(BasePtrMA, Writes).is_null();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003313 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003314
Tobias Grosserbe372d52017-02-09 10:11:58 +00003315 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003316 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003317 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003318 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003319
3320 return false;
3321}
3322
Johannes Doerfert5210da52016-06-02 11:06:54 +00003323bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003324 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003325 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003326
Johannes Doerfertcd195322016-11-17 21:41:08 +00003327 if (buildAliasGroups(AA)) {
3328 // Aliasing assumptions do not go through addAssumption but we still want to
3329 // collect statistics so we do it here explicitly.
3330 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003331 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003332 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003333 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003334
3335 // If a problem occurs while building the alias groups we need to delete
3336 // this SCoP and pretend it wasn't valid in the first place. To this end
3337 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003338 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003339
3340 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3341 << " could not be created as the number of parameters involved "
3342 "is too high. The SCoP will be "
3343 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3344 "the maximal number of parameters but be advised that the "
3345 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003346 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003347}
3348
Tobias Grosser889830b2017-02-09 23:12:22 +00003349std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003350Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003351 AliasSetTracker AST(AA);
3352
3353 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003354 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003355 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003356
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003357 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003358 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3359 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003360
3361 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003362 if (StmtDomainEmpty)
3363 continue;
3364
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003365 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003366 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003367 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003368 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003369 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003370 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003371 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003372 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003373 else
3374 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003375 AST.add(Acc);
3376 }
3377 }
3378
Tobias Grosser9edcf072017-01-16 14:07:57 +00003379 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003380 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003381 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003382 continue;
3383 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003384 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003385 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003386 if (AG.size() < 2)
3387 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003388 AliasGroups.push_back(std::move(AG));
3389 }
3390
Tobias Grosser9edcf072017-01-16 14:07:57 +00003391 return std::make_tuple(AliasGroups, HasWriteAccess);
3392}
3393
Tobias Grossere39f9122017-01-16 14:08:00 +00003394void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003395 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3396 AliasGroupTy NewAG;
3397 AliasGroupTy &AG = AliasGroups[u];
3398 AliasGroupTy::iterator AGI = AG.begin();
3399 isl_set *AGDomain = getAccessDomain(*AGI);
3400 while (AGI != AG.end()) {
3401 MemoryAccess *MA = *AGI;
3402 isl_set *MADomain = getAccessDomain(MA);
3403 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3404 NewAG.push_back(MA);
3405 AGI = AG.erase(AGI);
3406 isl_set_free(MADomain);
3407 } else {
3408 AGDomain = isl_set_union(AGDomain, MADomain);
3409 AGI++;
3410 }
3411 }
3412 if (NewAG.size() > 1)
3413 AliasGroups.push_back(std::move(NewAG));
3414 isl_set_free(AGDomain);
3415 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003416}
3417
3418bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3419 // To create sound alias checks we perform the following steps:
3420 // o) We partition each group into read only and non read only accesses.
3421 // o) For each group with more than one base pointer we then compute minimal
3422 // and maximal accesses to each array of a group in read only and non
3423 // read only partitions separately.
3424 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003425 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003426
3427 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3428
3429 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003430
Johannes Doerfert13771732014-10-01 12:40:46 +00003431 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser78a7a6c2017-06-23 08:05:31 +00003432 if (!hasFeasibleRuntimeContext())
3433 return false;
3434
Tobias Grosser57a1d362017-06-23 08:05:27 +00003435 {
3436 IslMaxOperationsGuard MaxOpGuard(getIslCtx(), OptComputeOut);
3437 bool Valid = buildAliasGroup(AG, HasWriteAccess);
3438 if (!Valid)
3439 return false;
3440 }
3441 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
3442 invalidate(COMPLEXITY, DebugLoc());
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003443 return false;
Tobias Grosser57a1d362017-06-23 08:05:27 +00003444 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003445 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003446
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003447 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003448}
3449
Tobias Grosser77f32572017-01-16 15:49:07 +00003450bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003451 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003452 AliasGroupTy ReadOnlyAccesses;
3453 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003454 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003455 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003456
Tobias Grosser77f32572017-01-16 15:49:07 +00003457 if (AliasGroup.size() < 2)
3458 return true;
3459
3460 for (MemoryAccess *Access : AliasGroup) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003461 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "PossibleAlias",
3462 Access->getAccessInstruction())
3463 << "Possibly aliasing pointer, use restrict keyword.");
Tobias Grosser889830b2017-02-09 23:12:22 +00003464 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3465 if (HasWriteAccess.count(Array)) {
3466 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003467 ReadWriteAccesses.push_back(Access);
3468 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003469 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003470 ReadOnlyAccesses.push_back(Access);
3471 }
3472 }
3473
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003474 // If there are no read-only pointers, and less than two read-write pointers,
3475 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003476 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003477 return true;
3478
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003479 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003480 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003481 return true;
3482
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003483 // For non-affine accesses, no alias check can be generated as we cannot
3484 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003485 for (MemoryAccess *MA : AliasGroup) {
3486 if (!MA->isAffine()) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003487 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc(),
3488 MA->getAccessInstruction()->getParent());
Tobias Grosser77f32572017-01-16 15:49:07 +00003489 return false;
3490 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003491 }
3492
3493 // Ensure that for all memory accesses for which we generate alias checks,
3494 // their base pointers are available.
3495 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003496 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3497 addRequiredInvariantLoad(
3498 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3499 }
3500
3501 MinMaxAliasGroups.emplace_back();
3502 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3503 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3504 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3505
3506 bool Valid;
3507
3508 Valid =
3509 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3510
3511 if (!Valid)
3512 return false;
3513
3514 // Bail out if the number of values we need to compare is too large.
3515 // This is important as the number of comparisons grows quadratically with
3516 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003517 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003518 RunTimeChecksMaxArraysPerGroup)
3519 return false;
3520
3521 Valid =
3522 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3523
3524 if (!Valid)
3525 return false;
3526
3527 return true;
3528}
3529
Tobias Grosserc80d6972016-09-02 06:33:33 +00003530/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003531static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003532 // Start with the smallest loop containing the entry and expand that
3533 // loop until it contains all blocks in the region. If there is a loop
3534 // containing all blocks in the region check if it is itself contained
3535 // and if so take the parent loop as it will be the smallest containing
3536 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003537 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003538 while (L) {
3539 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003540 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003541 AllContained &= L->contains(BB);
3542 if (AllContained)
3543 break;
3544 L = L->getParentLoop();
3545 }
3546
Johannes Doerfertef744432016-05-23 12:42:38 +00003547 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003548}
3549
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003550int Scop::NextScopID = 0;
3551
3552std::string Scop::CurrentFunc = "";
3553
3554int Scop::getNextID(std::string ParentFunc) {
3555 if (ParentFunc != CurrentFunc) {
3556 CurrentFunc = ParentFunc;
3557 NextScopID = 0;
3558 }
3559 return NextScopID++;
3560}
3561
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003562Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Eli Friedmane737fc12017-07-17 23:58:33 +00003563 ScopDetection::DetectionContext &DC, OptimizationRemarkEmitter &ORE)
Philip Pfaffe35bdcaf2017-05-15 13:43:01 +00003564 : SE(&ScalarEvolution), R(R), name(R.getNameStr()), IsOptimized(false),
Siddharth Bhat47c72372017-07-05 15:07:28 +00003565 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Eli Friedmane737fc12017-07-17 23:58:33 +00003566 MaxLoopDepth(0), CopyStmtsNum(0), SkipScop(false), DC(DC), ORE(ORE),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003567 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3568 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003569 Schedule(nullptr),
3570 ID(getNextID((*R.getEntry()->getParent()).getName().str())) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003571 if (IslOnErrorAbort)
3572 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003573 buildContext();
3574}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003575
Tobias Grosserbedef002016-12-02 08:10:56 +00003576void Scop::foldSizeConstantsToRight() {
3577 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3578
3579 for (auto Array : arrays()) {
3580 if (Array->getNumberOfDimensions() <= 1)
3581 continue;
3582
3583 isl_space *Space = Array->getSpace();
3584
3585 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3586
3587 if (!isl_union_set_contains(Accessed, Space)) {
3588 isl_space_free(Space);
3589 continue;
3590 }
3591
3592 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3593
3594 isl_map *Transform =
3595 isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3596
3597 std::vector<int> Int;
3598
3599 int Dims = isl_set_dim(Elements, isl_dim_set);
3600 for (int i = 0; i < Dims; i++) {
3601 isl_set *DimOnly =
3602 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3603 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3604 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3605
3606 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3607
3608 if (i == Dims - 1) {
3609 Int.push_back(1);
3610 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3611 isl_basic_set_free(DimHull);
3612 continue;
3613 }
3614
3615 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3616 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3617 isl_val *Val = isl_aff_get_denominator_val(Diff);
3618 isl_aff_free(Diff);
3619
3620 int ValInt = 1;
3621
3622 if (isl_val_is_int(Val))
3623 ValInt = isl_val_get_num_si(Val);
3624 isl_val_free(Val);
3625
3626 Int.push_back(ValInt);
3627
3628 isl_constraint *C = isl_constraint_alloc_equality(
3629 isl_local_space_from_space(isl_map_get_space(Transform)));
3630 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3631 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3632 Transform = isl_map_add_constraint(Transform, C);
3633 isl_basic_set_free(DimHull);
3634 continue;
3635 }
3636
3637 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3638 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3639
3640 int ValInt = 1;
3641 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3642 ValInt = 0;
3643 }
3644
3645 Int.push_back(ValInt);
3646 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3647 isl_basic_set_free(DimHull);
3648 isl_basic_set_free(ZeroSet);
3649 }
3650
3651 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3652
3653 if (!isl_set_is_subset(Elements, MappedElements)) {
3654 isl_set_free(Elements);
3655 isl_set_free(MappedElements);
3656 isl_map_free(Transform);
3657 continue;
3658 }
3659
3660 isl_set_free(MappedElements);
3661
3662 bool CanFold = true;
3663
3664 if (Int[0] <= 1)
3665 CanFold = false;
3666
3667 unsigned NumDims = Array->getNumberOfDimensions();
3668 for (unsigned i = 1; i < NumDims - 1; i++)
3669 if (Int[0] != Int[i] && Int[i])
3670 CanFold = false;
3671
3672 if (!CanFold) {
3673 isl_set_free(Elements);
3674 isl_map_free(Transform);
3675 continue;
3676 }
3677
Tobias Grosserbedef002016-12-02 08:10:56 +00003678 for (auto &Access : AccessFunctions)
3679 if (Access->getScopArrayInfo() == Array)
3680 Access->setAccessRelation(isl_map_apply_range(
3681 Access->getAccessRelation(), isl_map_copy(Transform)));
3682
3683 isl_map_free(Transform);
3684
3685 std::vector<const SCEV *> Sizes;
3686 for (unsigned i = 0; i < NumDims; i++) {
3687 auto Size = Array->getDimensionSize(i);
3688
3689 if (i == NumDims - 1)
3690 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3691 Sizes.push_back(Size);
3692 }
3693
3694 Array->updateSizes(Sizes, false /* CheckConsistency */);
3695
3696 isl_set_free(Elements);
3697 }
3698 isl_union_set_free(Accessed);
3699 return;
3700}
3701
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003702void Scop::markFortranArrays() {
3703 for (ScopStmt &Stmt : Stmts) {
3704 for (MemoryAccess *MemAcc : Stmt) {
3705 Value *FAD = MemAcc->getFortranArrayDescriptor();
3706 if (!FAD)
3707 continue;
3708
3709 // TODO: const_cast-ing to edit
3710 ScopArrayInfo *SAI =
3711 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3712 assert(SAI && "memory access into a Fortran array does not "
3713 "have an associated ScopArrayInfo");
3714 SAI->applyAndSetFAD(FAD);
3715 }
3716 }
3717}
3718
Tobias Grosser491b7992016-12-02 05:21:22 +00003719void Scop::finalizeAccesses() {
3720 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003721 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003722 foldAccessRelations();
3723 assumeNoOutOfBounds();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003724 markFortranArrays();
Tobias Grosser491b7992016-12-02 05:21:22 +00003725}
3726
Tobias Grosser75805372011-04-29 06:27:02 +00003727Scop::~Scop() {
3728 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003729 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003730 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003731 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003732
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003733 for (auto &It : ParameterIds)
3734 isl_id_free(It.second);
3735
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003736 for (auto &AS : RecordedAssumptions)
3737 isl_set_free(AS.Set);
3738
Johannes Doerfertb164c792014-09-18 11:17:17 +00003739 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003740 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003741 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003742 isl_pw_multi_aff_free(MMA.first);
3743 isl_pw_multi_aff_free(MMA.second);
3744 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003745 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003746 isl_pw_multi_aff_free(MMA.first);
3747 isl_pw_multi_aff_free(MMA.second);
3748 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003749 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003750
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003751 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003752 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003753
3754 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003755 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003756 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003757 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003758 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003759 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003760 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003761}
3762
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003763void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003764 // Check all array accesses for each base pointer and find a (virtual) element
3765 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003766 for (ScopStmt &Stmt : *this)
3767 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003768 if (!Access->isArrayKind())
3769 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003770 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003771 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3772
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003773 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003774 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003775 unsigned DivisibleSize = Array->getElemSizeInBytes();
3776 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003777 while (!isDivisible(Subscript, DivisibleSize, *SE))
3778 DivisibleSize /= 2;
3779 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003780 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003781 }
3782
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003783 for (auto &Stmt : *this)
3784 for (auto &Access : Stmt)
3785 Access->updateDimensionality();
3786}
3787
Tobias Grosser491b7992016-12-02 05:21:22 +00003788void Scop::foldAccessRelations() {
3789 for (auto &Stmt : *this)
3790 for (auto &Access : Stmt)
3791 Access->foldAccessRelation();
3792}
3793
3794void Scop::assumeNoOutOfBounds() {
3795 for (auto &Stmt : *this)
3796 for (auto &Access : Stmt)
3797 Access->assumeNoOutOfBound();
3798}
3799
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003800void Scop::removeFromStmtMap(ScopStmt &Stmt) {
3801 if (Stmt.isRegionStmt())
3802 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3803 StmtMap.erase(BB);
3804 else
3805 StmtMap.erase(Stmt.getBasicBlock());
3806}
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003807
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003808void Scop::removeStmts(std::function<bool(ScopStmt &)> ShouldDelete) {
3809 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3810 if (!ShouldDelete(*StmtIt)) {
3811 StmtIt++;
3812 continue;
3813 }
3814
3815 removeFromStmtMap(*StmtIt);
3816 StmtIt = Stmts.erase(StmtIt);
3817 }
3818}
3819
3820void Scop::removeStmtNotInDomainMap() {
3821 auto ShouldDelete = [this](ScopStmt &Stmt) -> bool {
Tobias Grosser199ec4a2017-07-19 16:31:10 +00003822 return !this->DomainMap.lookup(Stmt.getEntryBlock());
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003823 };
3824 removeStmts(ShouldDelete);
3825}
3826
3827void Scop::simplifySCoP(bool AfterHoisting) {
3828
3829 auto ShouldDelete = [AfterHoisting](ScopStmt &Stmt) -> bool {
Johannes Doerfert26404542016-05-10 12:19:47 +00003830 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003831
Tobias Grosser3012a0b2017-07-16 22:44:17 +00003832 // Remove read only statements only after invariant load hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003833 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003834 bool OnlyRead = true;
3835 for (MemoryAccess *MA : Stmt) {
3836 if (MA->isRead())
3837 continue;
3838
3839 OnlyRead = false;
3840 break;
3841 }
3842
3843 RemoveStmt = OnlyRead;
3844 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003845 return RemoveStmt;
3846 };
Johannes Doerferteca9e892015-11-03 16:54:49 +00003847
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003848 removeStmts(ShouldDelete);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003849}
3850
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003851InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003852 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3853 if (!LInst)
3854 return nullptr;
3855
3856 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3857 LInst = cast<LoadInst>(Rep);
3858
Johannes Doerfert96e54712016-02-07 17:30:13 +00003859 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003860 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003861 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003862 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003863 continue;
3864
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003865 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003866 for (auto *MA : MAs)
3867 if (MA->getAccessInstruction() == Val)
3868 return &IAClass;
3869 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003870
3871 return nullptr;
3872}
3873
Tobias Grosserc80d6972016-09-02 06:33:33 +00003874/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003875static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003876 bool MAInvalidCtxIsEmpty,
3877 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003878 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3879 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3880 // TODO: We can provide more information for better but more expensive
3881 // results.
3882 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3883 LInst->getAlignment(), DL))
3884 return false;
3885
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003886 // If the location might be overwritten we do not hoist it unconditionally.
3887 //
3888 // TODO: This is probably to conservative.
3889 if (!NonHoistableCtxIsEmpty)
3890 return false;
3891
Michael Krusea6d48f52017-06-08 12:06:15 +00003892 // If a dereferenceable load is in a statement that is modeled precisely we
3893 // can hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003894 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003895 return true;
3896
3897 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003898 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003899 // statement domain.
3900 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3901 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3902 return false;
3903 return true;
3904}
3905
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003906void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003907
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003908 if (InvMAs.empty())
3909 return;
3910
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003911 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003912 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003913
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003914 // Get the context under which the statement is executed but remove the error
3915 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003916 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003917 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003918
Tobias Grosser90411a92017-02-16 19:11:33 +00003919 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003920 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Eli Friedmane737fc12017-07-17 23:58:33 +00003921 invalidate(COMPLEXITY, AccInst->getDebugLoc(), AccInst->getParent());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003922 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003923 for (auto &InvMA : InvMAs)
3924 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003925 return;
3926 }
3927
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003928 // Project out all parameters that relate to loads in the statement. Otherwise
3929 // we could have cyclic dependences on the constraints under which the
3930 // hoisted loads are executed and we could not determine an order in which to
3931 // pre-load them. This happens because not only lower bounds are part of the
3932 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003933 for (auto &InvMA : InvMAs) {
3934 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003935 Instruction *AccInst = MA->getAccessInstruction();
3936 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003937 SetVector<Value *> Values;
3938 for (const SCEV *Parameter : Parameters) {
3939 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003940 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003941 if (!Values.count(AccInst))
3942 continue;
3943
3944 if (isl_id *ParamId = getIdForParam(Parameter)) {
3945 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003946 if (Dim >= 0)
3947 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003948 isl_id_free(ParamId);
3949 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003950 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003951 }
3952 }
3953
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003954 for (auto &InvMA : InvMAs) {
3955 auto *MA = InvMA.MA;
3956 auto *NHCtx = InvMA.NonHoistableCtx;
3957
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003958 // Check for another invariant access that accesses the same location as
3959 // MA and if found consolidate them. Otherwise create a new equivalence
3960 // class at the end of InvariantEquivClasses.
3961 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003962 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003963 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3964
Johannes Doerfert85676e32016-04-23 14:32:34 +00003965 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003966 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003967 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3968
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003969 isl_set *MACtx;
3970 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003971 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3972 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003973 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003974 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003975 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003976 } else {
3977 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003978 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003979 MACtx = isl_set_gist_params(MACtx, getContext());
3980 }
3981
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003982 bool Consolidated = false;
3983 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003984 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003985 continue;
3986
Johannes Doerfertdf880232016-03-03 12:26:58 +00003987 // If the pointer and the type is equal check if the access function wrt.
3988 // to the domain is equal too. It can happen that the domain fixes
3989 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003990 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003991 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003992 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003993 if (!MAs.empty()) {
3994 auto *LastMA = MAs.front();
3995
3996 auto *AR = isl_map_range(MA->getAccessRelation());
3997 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3998 bool SameAR = isl_set_is_equal(AR, LastAR);
3999 isl_set_free(AR);
4000 isl_set_free(LastAR);
4001
4002 if (!SameAR)
4003 continue;
4004 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004005
4006 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004007 MAs.push_front(MA);
4008
Johannes Doerfertdf880232016-03-03 12:26:58 +00004009 Consolidated = true;
4010
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004011 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004012 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00004013 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00004014 IAClassDomainCtx =
4015 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00004016 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00004017 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004018 break;
4019 }
4020
4021 if (Consolidated)
4022 continue;
4023
4024 // If we did not consolidate MA, thus did not find an equivalence class
4025 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004026 InvariantEquivClasses.emplace_back(
4027 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004028 }
4029
4030 isl_set_free(DomainCtx);
4031}
4032
Tobias Grosser1eeedf42017-07-20 19:55:19 +00004033/// Check if an access range is too complex.
4034///
4035/// An access range is too complex, if it contains either many disjuncts or
4036/// very complex expressions. As a simple heuristic, we assume if a set to
4037/// be too complex if the sum of existentially quantified dimensions and
4038/// set dimensions is larger than a threshold. This reliably detects both
4039/// sets with many disjuncts as well as sets with many divisions as they
4040/// arise in h264.
4041///
4042/// @param AccessRange The range to check for complexity.
4043///
4044/// @returns True if the access range is too complex.
4045static bool isAccessRangeTooComplex(isl::set AccessRange) {
4046 unsigned NumTotalDims = 0;
4047
4048 auto CountDimensions = [&NumTotalDims](isl::basic_set BSet) -> isl::stat {
4049 NumTotalDims += BSet.dim(isl::dim::div);
4050 NumTotalDims += BSet.dim(isl::dim::set);
4051 return isl::stat::ok;
4052 };
4053
4054 AccessRange.foreach_basic_set(CountDimensions);
4055
4056 if (NumTotalDims > MaxDimensionsInAccessRange)
4057 return true;
4058
4059 return false;
4060}
4061
Tobias Grosser4071cb52017-06-06 23:13:02 +00004062isl::set Scop::getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004063 // TODO: Loads that are not loop carried, hence are in a statement with
4064 // zero iterators, are by construction invariant, though we
4065 // currently "hoist" them anyway. This is necessary because we allow
4066 // them to be treated as parameters (e.g., in conditions) and our code
4067 // generation would otherwise use the old value.
4068
4069 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00004070 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004071
Johannes Doerfertc9765462016-11-17 22:11:56 +00004072 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
4073 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004074 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004075
4076 // Skip accesses that have an invariant base pointer which is defined but
4077 // not loaded inside the SCoP. This can happened e.g., if a readnone call
4078 // returns a pointer that is used as a base address. However, as we want
4079 // to hoist indirect pointers, we allow the base pointer to be defined in
4080 // the region if it is also a memory access. Each ScopArrayInfo object
4081 // that has a base pointer origin has a base pointer that is loaded and
4082 // that it is invariant, thus it will be hoisted too. However, if there is
4083 // no base pointer origin we check that the base pointer is defined
4084 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004085 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00004086 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004087 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004088
Tobias Grosser4071cb52017-06-06 23:13:02 +00004089 isl::map AccessRelation = give(Access->getAccessRelation());
4090 assert(!AccessRelation.is_empty());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004091
Tobias Grosser4071cb52017-06-06 23:13:02 +00004092 if (AccessRelation.involves_dims(isl::dim::in, 0, Stmt.getNumIterators()))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004093 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004094
Tobias Grosser4071cb52017-06-06 23:13:02 +00004095 AccessRelation = AccessRelation.intersect_domain(give(Stmt.getDomain()));
4096 isl::set SafeToLoad;
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004097
4098 auto &DL = getFunction().getParent()->getDataLayout();
4099 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
4100 DL)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00004101 SafeToLoad = isl::set::universe(AccessRelation.get_space().range());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004102 } else if (BB != LI->getParent()) {
4103 // Skip accesses in non-affine subregions as they might not be executed
4104 // under the same condition as the entry of the non-affine subregion.
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004105 return nullptr;
4106 } else {
Tobias Grosser4071cb52017-06-06 23:13:02 +00004107 SafeToLoad = AccessRelation.range();
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004108 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004109
Tobias Grosser1eeedf42017-07-20 19:55:19 +00004110 if (isAccessRangeTooComplex(AccessRelation.range()))
4111 return nullptr;
4112
Tobias Grosser4071cb52017-06-06 23:13:02 +00004113 isl::union_map Written = Writes.intersect_range(SafeToLoad);
4114 isl::set WrittenCtx = Written.params();
4115 bool IsWritten = !WrittenCtx.is_empty();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004116
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004117 if (!IsWritten)
4118 return WrittenCtx;
4119
Tobias Grosser4071cb52017-06-06 23:13:02 +00004120 WrittenCtx = WrittenCtx.remove_divs();
4121 bool TooComplex =
4122 isl_set_n_basic_set(WrittenCtx.get()) >= MaxDisjunctsInDomain;
4123 if (TooComplex || !isRequiredInvariantLoad(LI))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004124 return nullptr;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004125
Tobias Grosser4071cb52017-06-06 23:13:02 +00004126 addAssumption(INVARIANTLOAD, WrittenCtx.copy(), LI->getDebugLoc(),
Eli Friedmane737fc12017-07-17 23:58:33 +00004127 AS_RESTRICTION, LI->getParent());
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004128 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004129}
4130
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004131void Scop::verifyInvariantLoads() {
4132 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004133 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00004134 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00004135 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00004136 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004137 invalidate(INVARIANTLOAD, LI->getDebugLoc(), LI->getParent());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004138 return;
4139 }
4140 }
4141}
4142
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004143void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00004144 if (!PollyInvariantLoadHoisting)
4145 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004146
Tobias Grosser4071cb52017-06-06 23:13:02 +00004147 isl::union_map Writes = give(getWrites());
Tobias Grosser0865e7752016-02-29 07:29:42 +00004148 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004149 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004150
Tobias Grosser0865e7752016-02-29 07:29:42 +00004151 for (MemoryAccess *Access : Stmt)
Tobias Grosser4071cb52017-06-06 23:13:02 +00004152 if (isl::set NHCtx = getNonHoistableCtx(Access, Writes))
4153 InvariantAccesses.push_back({Access, NHCtx.release()});
Tobias Grosser0865e7752016-02-29 07:29:42 +00004154
4155 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00004156 for (auto InvMA : InvariantAccesses)
4157 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00004158 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004159 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004160}
4161
Tobias Grosserf3adab42017-05-10 10:59:58 +00004162/// Find the canonical scop array info object for a set of invariant load
4163/// hoisted loads. The canonical array is the one that corresponds to the
4164/// first load in the list of accesses which is used as base pointer of a
4165/// scop array.
4166static const ScopArrayInfo *findCanonicalArray(Scop *S,
4167 MemoryAccessList &Accesses) {
4168 for (MemoryAccess *Access : Accesses) {
4169 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
4170 Access->getAccessInstruction(), MemoryKind::Array);
4171 if (CanonicalArray)
4172 return CanonicalArray;
4173 }
4174 return nullptr;
4175}
4176
4177/// Check if @p Array severs as base array in an invariant load.
4178static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
4179 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
4180 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
4181 if (Access2->getScopArrayInfo() == Array)
4182 return true;
4183 return false;
4184}
4185
4186/// Replace the base pointer arrays in all memory accesses referencing @p Old,
4187/// with a reference to @p New.
4188static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
4189 const ScopArrayInfo *New) {
4190 for (ScopStmt &Stmt : *S)
4191 for (MemoryAccess *Access : Stmt) {
4192 if (Access->getLatestScopArrayInfo() != Old)
4193 continue;
4194
4195 isl_id *Id = New->getBasePtrId();
4196 isl_map *Map = Access->getAccessRelation();
4197 Map = isl_map_set_tuple_id(Map, isl_dim_out, Id);
4198 Access->setAccessRelation(Map);
4199 }
4200}
4201
4202void Scop::canonicalizeDynamicBasePtrs() {
4203 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
4204 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
4205
4206 const ScopArrayInfo *CanonicalBasePtrSAI =
4207 findCanonicalArray(this, BasePtrAccesses);
4208
4209 if (!CanonicalBasePtrSAI)
4210 continue;
4211
4212 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
4213 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
4214 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
4215 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
4216 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
4217 continue;
4218
4219 // we currently do not canonicalize arrays where some accesses are
4220 // hoisted as invariant loads. If we would, we need to update the access
4221 // function of the invariant loads as well. However, as this is not a
4222 // very common situation, we leave this for now to avoid further
4223 // complexity increases.
4224 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
4225 continue;
4226
4227 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
4228 }
4229 }
4230}
4231
Michael Kruseb738ffa2017-06-28 13:02:43 +00004232ScopArrayInfo *Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
4233 ArrayRef<const SCEV *> Sizes,
4234 MemoryKind Kind,
4235 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004236 assert((BasePtr || BaseName) &&
4237 "BasePtr and BaseName can not be nullptr at the same time.");
4238 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
4239 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
4240 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004241 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004242 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00004243 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00004244 DL, this, BaseName));
4245 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004246 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004247 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00004248 // In case of mismatching array sizes, we bail out by setting the run-time
4249 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004250 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004251 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004252 }
Tobias Grosserab671442015-05-23 05:58:27 +00004253 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004254}
4255
Michael Kruseb738ffa2017-06-28 13:02:43 +00004256ScopArrayInfo *Scop::createScopArrayInfo(Type *ElementType,
4257 const std::string &BaseName,
4258 const std::vector<unsigned> &Sizes) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004259 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
4260 std::vector<const SCEV *> SCEVSizes;
4261
4262 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00004263 if (size)
4264 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
4265 else
4266 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00004267
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004268 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
4269 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00004270 return SAI;
4271}
4272
Tobias Grosserf3adab42017-05-10 10:59:58 +00004273const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
4274 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00004275 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004276 return SAI;
4277}
4278
4279const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
4280 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004281 assert(SAI && "No ScopArrayInfo available for this base pointer");
4282 return SAI;
4283}
4284
Tobias Grosser74394f02013-01-14 22:40:23 +00004285std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004286
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004287std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004288 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004289 return stringFromIslObj(AssumedContext);
4290}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004291
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004292std::string Scop::getInvalidContextStr() const {
4293 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004294}
Tobias Grosser75805372011-04-29 06:27:02 +00004295
4296std::string Scop::getNameStr() const {
4297 std::string ExitName, EntryName;
Siddharth Bhat07bee292017-06-02 08:01:22 +00004298 std::tie(EntryName, ExitName) = getEntryExitStr();
4299 return EntryName + "---" + ExitName;
4300}
4301
4302std::pair<std::string, std::string> Scop::getEntryExitStr() const {
4303 std::string ExitName, EntryName;
Tobias Grosser75805372011-04-29 06:27:02 +00004304 raw_string_ostream ExitStr(ExitName);
4305 raw_string_ostream EntryStr(EntryName);
4306
Tobias Grosserf240b482014-01-09 10:42:15 +00004307 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004308 EntryStr.str();
4309
4310 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00004311 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004312 ExitStr.str();
4313 } else
4314 ExitName = "FunctionExit";
4315
Siddharth Bhat07bee292017-06-02 08:01:22 +00004316 return std::make_pair(EntryName, ExitName);
Tobias Grosser75805372011-04-29 06:27:02 +00004317}
4318
Tobias Grosser74394f02013-01-14 22:40:23 +00004319__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00004320__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00004321 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00004322}
4323
Tobias Grossere86109f2013-10-29 21:05:49 +00004324__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004325 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00004326 return isl_set_copy(AssumedContext);
4327}
4328
Michael Krusef3091bf2017-03-17 13:09:52 +00004329bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004330 if (PollyProcessUnprofitable)
4331 return true;
4332
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004333 if (isEmpty())
4334 return false;
4335
4336 unsigned OptimizableStmtsOrLoops = 0;
4337 for (auto &Stmt : *this) {
4338 if (Stmt.getNumIterators() == 0)
4339 continue;
4340
4341 bool ContainsArrayAccs = false;
4342 bool ContainsScalarAccs = false;
4343 for (auto *MA : Stmt) {
4344 if (MA->isRead())
4345 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004346 ContainsArrayAccs |= MA->isLatestArrayKind();
4347 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004348 }
4349
Michael Krusef3091bf2017-03-17 13:09:52 +00004350 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004351 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4352 }
4353
4354 return OptimizableStmtsOrLoops > 1;
4355}
4356
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004357bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004358 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004359 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00004360 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4361 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4362 isl_set_is_subset(PositiveContext, NegativeContext));
4363 isl_set_free(PositiveContext);
4364 if (!IsFeasible) {
4365 isl_set_free(NegativeContext);
4366 return false;
4367 }
4368
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004369 auto *DomainContext = isl_union_set_params(getDomains());
4370 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00004371 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004372 isl_set_free(NegativeContext);
4373 isl_set_free(DomainContext);
4374
Johannes Doerfert43788c52015-08-20 05:58:56 +00004375 return IsFeasible;
4376}
4377
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004378static std::string toString(AssumptionKind Kind) {
4379 switch (Kind) {
4380 case ALIASING:
4381 return "No-aliasing";
4382 case INBOUNDS:
4383 return "Inbounds";
4384 case WRAPPING:
4385 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004386 case UNSIGNED:
4387 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004388 case COMPLEXITY:
4389 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004390 case PROFITABLE:
4391 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004392 case ERRORBLOCK:
4393 return "No-error";
4394 case INFINITELOOP:
4395 return "Finite loop";
4396 case INVARIANTLOAD:
4397 return "Invariant load";
4398 case DELINEARIZATION:
4399 return "Delinearization";
4400 }
4401 llvm_unreachable("Unknown AssumptionKind!");
4402}
4403
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004404bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4405 if (Sign == AS_ASSUMPTION) {
4406 if (isl_set_is_subset(Context, Set))
4407 return false;
4408
4409 if (isl_set_is_subset(AssumedContext, Set))
4410 return false;
4411 } else {
4412 if (isl_set_is_disjoint(Set, Context))
4413 return false;
4414
4415 if (isl_set_is_subset(Set, InvalidContext))
4416 return false;
4417 }
4418 return true;
4419}
4420
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004421bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004422 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004423 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4424 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004425
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004426 // Do never emit trivial assumptions as they only clutter the output.
4427 if (!PollyRemarksMinimal) {
4428 isl_set *Univ = nullptr;
4429 if (Sign == AS_ASSUMPTION)
4430 Univ = isl_set_universe(isl_set_get_space(Set));
4431
4432 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4433 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4434 isl_set_free(Univ);
4435
4436 if (IsTrivial)
4437 return false;
4438 }
4439
Johannes Doerfertcd195322016-11-17 21:41:08 +00004440 switch (Kind) {
4441 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004442 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004443 break;
4444 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004445 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004446 break;
4447 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004448 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004449 break;
4450 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004451 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004452 break;
4453 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004454 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004455 break;
4456 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004457 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004458 break;
4459 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004460 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004461 break;
4462 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004463 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004464 break;
4465 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004466 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004467 break;
4468 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004469 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004470 break;
4471 }
4472
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004473 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4474 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Eli Friedmane737fc12017-07-17 23:58:33 +00004475 if (BB)
4476 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc, BB)
4477 << Msg);
4478 else
4479 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc,
4480 R.getEntry())
4481 << Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004482 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004483}
4484
4485void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004486 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004487 // Simplify the assumptions/restrictions first.
4488 Set = isl_set_gist_params(Set, getContext());
4489
Eli Friedmane737fc12017-07-17 23:58:33 +00004490 if (!trackAssumption(Kind, Set, Loc, Sign, BB)) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004491 isl_set_free(Set);
4492 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004493 }
4494
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004495 if (Sign == AS_ASSUMPTION) {
4496 AssumedContext = isl_set_intersect(AssumedContext, Set);
4497 AssumedContext = isl_set_coalesce(AssumedContext);
4498 } else {
4499 InvalidContext = isl_set_union(InvalidContext, Set);
4500 InvalidContext = isl_set_coalesce(InvalidContext);
4501 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004502}
4503
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004504void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004505 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004506 assert((isl_set_is_params(Set) || BB) &&
4507 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004508 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004509}
4510
4511void Scop::addRecordedAssumptions() {
4512 while (!RecordedAssumptions.empty()) {
4513 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004514
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004515 if (!AS.BB) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004516 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign, nullptr /* BasicBlock */);
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004517 continue;
4518 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004519
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004520 // If the domain was deleted the assumptions are void.
4521 isl_set *Dom = getDomainConditions(AS.BB);
4522 if (!Dom) {
4523 isl_set_free(AS.Set);
4524 continue;
4525 }
4526
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004527 // If a basic block was given use its domain to simplify the assumption.
4528 // In case of restrictions we know they only have to hold on the domain,
4529 // thus we can intersect them with the domain of the block. However, for
4530 // assumptions the domain has to imply them, thus:
4531 // _ _____
4532 // Dom => S <==> A v B <==> A - B
4533 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004534 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004535 // assumption.
4536 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004537 if (AS.Sign == AS_RESTRICTION)
4538 S = isl_set_params(isl_set_intersect(S, Dom));
4539 else /* (AS.Sign == AS_ASSUMPTION) */
4540 S = isl_set_params(isl_set_subtract(Dom, S));
4541
Eli Friedmane737fc12017-07-17 23:58:33 +00004542 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION, AS.BB);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004543 }
4544}
4545
Eli Friedmane737fc12017-07-17 23:58:33 +00004546void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB) {
4547 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION, BB);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004548}
4549
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004550__isl_give isl_set *Scop::getInvalidContext() const {
4551 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004552}
4553
Tobias Grosser75805372011-04-29 06:27:02 +00004554void Scop::printContext(raw_ostream &OS) const {
4555 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004556 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004557
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004558 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004559 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004560
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004561 OS.indent(4) << "Invalid Context:\n";
4562 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004563
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004564 unsigned Dim = 0;
4565 for (const SCEV *Parameter : Parameters)
4566 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004567}
4568
Johannes Doerfertb164c792014-09-18 11:17:17 +00004569void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004570 int noOfGroups = 0;
4571 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004572 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004573 noOfGroups += 1;
4574 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004575 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004576 }
4577
Tobias Grosserbb853c22015-07-25 12:31:03 +00004578 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004579 if (MinMaxAliasGroups.empty()) {
4580 OS.indent(8) << "n/a\n";
4581 return;
4582 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004583
Tobias Grosserbb853c22015-07-25 12:31:03 +00004584 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004585
4586 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004587 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004588 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004589 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004590 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4591 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004592 }
4593 OS << " ]]\n";
4594 }
4595
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004596 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004597 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004598 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004599 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004600 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4601 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004602 }
4603 OS << " ]]\n";
4604 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004605 }
4606}
4607
Tobias Grosser75805372011-04-29 06:27:02 +00004608void Scop::printStatements(raw_ostream &OS) const {
4609 OS << "Statements {\n";
4610
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004611 for (const ScopStmt &Stmt : *this)
4612 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00004613
4614 OS.indent(4) << "}\n";
4615}
4616
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004617void Scop::printArrayInfo(raw_ostream &OS) const {
4618 OS << "Arrays {\n";
4619
Tobias Grosserab671442015-05-23 05:58:27 +00004620 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004621 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004622
4623 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004624
4625 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4626
4627 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004628 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004629
4630 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004631}
4632
Tobias Grosser75805372011-04-29 06:27:02 +00004633void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004634 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004635 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004636 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004637 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004638 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004639 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004640 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004641 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004642 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004643 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004644 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4645 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004646 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004647 }
4648 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004649 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004650 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004651 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00004652 printStatements(OS.indent(4));
4653}
4654
4655void Scop::dump() const { print(dbgs()); }
4656
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004657isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004658
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004659__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4660 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004661 // First try to use the SCEVAffinator to generate a piecewise defined
4662 // affine function from @p E in the context of @p BB. If that tasks becomes to
4663 // complex the affinator might return a nullptr. In such a case we invalidate
4664 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004665 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004666 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004667 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004668 // TODO: We could use a heuristic and either use:
4669 // SCEVAffinator::takeNonNegativeAssumption
4670 // or
4671 // SCEVAffinator::interpretAsUnsigned
4672 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004673 if (NonNegative)
4674 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004675 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004676 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004677
4678 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
Eli Friedmane737fc12017-07-17 23:58:33 +00004679 invalidate(COMPLEXITY, DL, BB);
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004680 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004681}
4682
Tobias Grosser808cd692015-07-14 09:33:13 +00004683__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004684 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4685 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004686
Tobias Grosser808cd692015-07-14 09:33:13 +00004687 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004688 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004689
4690 return Domain;
4691}
4692
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004693__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4694 PWACtx PWAC = getPwAff(E, BB);
4695 isl_set_free(PWAC.second);
4696 return PWAC.first;
4697}
4698
Tobias Grossere5a35142015-11-12 14:07:09 +00004699__isl_give isl_union_map *
4700Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4701 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004702
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004703 for (ScopStmt &Stmt : *this) {
4704 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004705 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004706 continue;
4707
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004708 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004709 isl_map *AccessDomain = MA->getAccessRelation();
4710 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004711 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004712 }
4713 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004714 return isl_union_map_coalesce(Accesses);
4715}
4716
4717__isl_give isl_union_map *Scop::getMustWrites() {
4718 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004719}
4720
4721__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004722 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004723}
4724
Tobias Grosser37eb4222014-02-20 21:43:54 +00004725__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004726 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004727}
4728
4729__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004730 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004731}
4732
Tobias Grosser2ac23382015-11-12 14:07:13 +00004733__isl_give isl_union_map *Scop::getAccesses() {
4734 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4735}
4736
Roman Gareevb3224ad2016-09-14 06:26:09 +00004737// Check whether @p Node is an extension node.
4738//
4739// @return true if @p Node is an extension node.
4740isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4741 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4742 return isl_bool_error;
4743 else
4744 return isl_bool_true;
4745}
4746
4747bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4748 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4749 nullptr) == isl_stat_error;
4750}
4751
Tobias Grosser808cd692015-07-14 09:33:13 +00004752__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004753 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004754 if (containsExtensionNode(Tree)) {
4755 isl_schedule_free(Tree);
4756 return nullptr;
4757 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004758 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004759 isl_schedule_free(Tree);
4760 return S;
4761}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004762
Tobias Grosser808cd692015-07-14 09:33:13 +00004763__isl_give isl_schedule *Scop::getScheduleTree() const {
4764 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4765 getDomains());
4766}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004767
Tobias Grosser808cd692015-07-14 09:33:13 +00004768void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4769 auto *S = isl_schedule_from_domain(getDomains());
4770 S = isl_schedule_insert_partial_schedule(
4771 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4772 isl_schedule_free(Schedule);
4773 Schedule = S;
4774}
4775
4776void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4777 isl_schedule_free(Schedule);
4778 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004779}
4780
4781bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4782 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004783 for (ScopStmt &Stmt : *this) {
4784 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004785 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4786 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4787
4788 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4789 isl_union_set_free(StmtDomain);
4790 isl_union_set_free(NewStmtDomain);
4791 continue;
4792 }
4793
4794 Changed = true;
4795
4796 isl_union_set_free(StmtDomain);
4797 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4798
4799 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004800 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004801 isl_union_set_free(NewStmtDomain);
4802 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004803 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004804 }
4805 isl_union_set_free(Domain);
4806 return Changed;
4807}
4808
Tobias Grosser75805372011-04-29 06:27:02 +00004809ScalarEvolution *Scop::getSE() const { return SE; }
4810
Tobias Grosserc80d6972016-09-02 06:33:33 +00004811// Create an isl_multi_union_aff that defines an identity mapping from the
4812// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004813//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004814// # Example:
4815//
4816// Domain: { A[i,j]; B[i,j,k] }
4817// N: 1
4818//
4819// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4820//
4821// @param USet A union set describing the elements for which to generate a
4822// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004823// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004824// @returns A mapping from USet to its N-th dimension.
Tobias Grosser99320862017-05-26 17:22:03 +00004825static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) {
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004826 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004827 assert(USet);
Siddharth Bhat8bb436e2017-05-29 11:34:29 +00004828 assert(!USet.is_empty());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004829
Tobias Grosser99320862017-05-26 17:22:03 +00004830 auto Result = isl::union_pw_multi_aff::empty(USet.get_space());
Tobias Grosser808cd692015-07-14 09:33:13 +00004831
Tobias Grosser99320862017-05-26 17:22:03 +00004832 auto Lambda = [&Result, N](isl::set S) -> isl::stat {
4833 int Dim = S.dim(isl::dim::set);
4834 auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set,
4835 N, Dim - N);
4836 if (N > 1)
4837 PMA = PMA.drop_dims(isl::dim::out, 0, N - 1);
Tobias Grosser808cd692015-07-14 09:33:13 +00004838
Tobias Grosser99320862017-05-26 17:22:03 +00004839 Result = Result.add_pw_multi_aff(PMA);
4840 return isl::stat::ok;
4841 };
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004842
Tobias Grosser99320862017-05-26 17:22:03 +00004843 isl::stat Res = USet.foreach_set(Lambda);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004844 (void)Res;
4845
Tobias Grosser99320862017-05-26 17:22:03 +00004846 assert(Res == isl::stat::ok);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004847
Tobias Grosser99320862017-05-26 17:22:03 +00004848 return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result));
Tobias Grosser808cd692015-07-14 09:33:13 +00004849}
4850
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004851void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop,
4852 std::vector<Instruction *> Instructions) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004853 assert(BB && "Unexpected nullptr!");
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004854 Stmts.emplace_back(*this, *BB, SurroundingLoop, Instructions);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004855 auto *Stmt = &Stmts.back();
Michael Kruse4dfa7322017-07-18 15:41:49 +00004856 StmtMap[BB].push_back(Stmt);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004857}
4858
Michael Kruse55454072017-03-15 22:16:43 +00004859void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004860 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004861 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004862 auto *Stmt = &Stmts.back();
4863 for (BasicBlock *BB : R->blocks())
Michael Kruse4dfa7322017-07-18 15:41:49 +00004864 StmtMap[BB].push_back(Stmt);
Tobias Grosser808cd692015-07-14 09:33:13 +00004865}
4866
Roman Gareevb3224ad2016-09-14 06:26:09 +00004867ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4868 __isl_take isl_map *TargetRel,
4869 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004870#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004871 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4872 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4873 assert(isl_set_is_subset(Domain, TargetDomain) &&
4874 "Target access not defined for complete statement domain");
4875 assert(isl_set_is_subset(Domain, SourceDomain) &&
4876 "Source access not defined for complete statement domain");
4877 isl_set_free(SourceDomain);
4878 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004879#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004880 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4881 CopyStmtsNum++;
4882 return &(Stmts.back());
4883}
4884
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004885void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004886 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004887 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004888 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004889 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4890 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004891}
4892
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004893/// To generate a schedule for the elements in a Region we traverse the Region
4894/// in reverse-post-order and add the contained RegionNodes in traversal order
4895/// to the schedule of the loop that is currently at the top of the LoopStack.
4896/// For loop-free codes, this results in a correct sequential ordering.
4897///
4898/// Example:
4899/// bb1(0)
4900/// / \.
4901/// bb2(1) bb3(2)
4902/// \ / \.
4903/// bb4(3) bb5(4)
4904/// \ /
4905/// bb6(5)
4906///
4907/// Including loops requires additional processing. Whenever a loop header is
4908/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4909/// from an empty schedule, we first process all RegionNodes that are within
4910/// this loop and complete the sequential schedule at this loop-level before
4911/// processing about any other nodes. To implement this
4912/// loop-nodes-first-processing, the reverse post-order traversal is
4913/// insufficient. Hence, we additionally check if the traversal yields
4914/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4915/// These region-nodes are then queue and only traverse after the all nodes
4916/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004917void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004918 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004919
4920 ReversePostOrderTraversal<Region *> RTraversal(R);
4921 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4922 std::deque<RegionNode *> DelayList;
4923 bool LastRNWaiting = false;
4924
4925 // Iterate over the region @p R in reverse post-order but queue
4926 // sub-regions/blocks iff they are not part of the last encountered but not
4927 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4928 // that we queued the last sub-region/block from the reverse post-order
4929 // iterator. If it is set we have to explore the next sub-region/block from
4930 // the iterator (if any) to guarantee progress. If it is not set we first try
4931 // the next queued sub-region/blocks.
4932 while (!WorkList.empty() || !DelayList.empty()) {
4933 RegionNode *RN;
4934
4935 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4936 RN = WorkList.front();
4937 WorkList.pop_front();
4938 LastRNWaiting = false;
4939 } else {
4940 RN = DelayList.front();
4941 DelayList.pop_front();
4942 }
4943
4944 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004945 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004946 L = OuterScopLoop;
4947
Tobias Grosser151ae322016-04-03 19:36:52 +00004948 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004949 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004950 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004951 LastRNWaiting = true;
4952 DelayList.push_back(RN);
4953 continue;
4954 }
4955 LoopStack.push_back({L, nullptr, 0});
4956 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004957 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004958 }
4959
4960 return;
4961}
4962
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004963void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004964
Tobias Grosser8362c262016-01-06 15:30:06 +00004965 if (RN->isSubRegion()) {
4966 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004967 if (!isNonAffineSubRegion(LocalRegion)) {
4968 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004969 return;
4970 }
4971 }
Michael Kruse046dde42015-08-10 13:01:57 +00004972
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004973 auto &LoopData = LoopStack.back();
4974 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004975
Michael Kruse1ce67912017-07-20 17:18:58 +00004976 for (auto *Stmt : getStmtListFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004977 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4978 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004979 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004980 }
4981
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004982 // Check if we just processed the last node in this loop. If we did, finalize
4983 // the loop by:
4984 //
4985 // - adding new schedule dimensions
4986 // - folding the resulting schedule into the parent loop schedule
4987 // - dropping the loop schedule from the LoopStack.
4988 //
4989 // Then continue to check surrounding loops, which might also have been
4990 // completed by this node.
4991 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00004992 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004993 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004994 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004995
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004996 LoopStack.pop_back();
4997 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004998
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004999 if (Schedule) {
Tobias Grosser99320862017-05-26 17:22:03 +00005000 isl::union_set Domain = give(isl_schedule_get_domain(Schedule));
5001 isl::multi_union_pw_aff MUPA = mapToDimension(Domain, LoopStack.size());
5002 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA.release());
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005003 NextLoopData.Schedule =
5004 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00005005 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00005006
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005007 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
5008 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00005009 }
Tobias Grosser75805372011-04-29 06:27:02 +00005010}
5011
Michael Kruse6f7721f2016-02-24 22:08:19 +00005012ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00005013 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00005014 if (StmtMapIt == StmtMap.end())
5015 return nullptr;
Michael Kruse4dfa7322017-07-18 15:41:49 +00005016 assert(StmtMapIt->second.size() == 1);
5017 return StmtMapIt->second.front();
Johannes Doerfert7c494212014-10-31 23:13:39 +00005018}
5019
Michael Kruse6eba4b12017-07-20 17:08:50 +00005020ArrayRef<ScopStmt *> Scop::getStmtListFor(BasicBlock *BB) const {
5021 auto StmtMapIt = StmtMap.find(BB);
5022 if (StmtMapIt == StmtMap.end())
5023 return {};
5024 assert(StmtMapIt->second.size() == 1 &&
5025 "Each statement corresponds to exactly one BB.");
5026 return StmtMapIt->second;
5027}
5028
5029ScopStmt *Scop::getLastStmtFor(BasicBlock *BB) const {
5030 ArrayRef<ScopStmt *> StmtList = getStmtListFor(BB);
5031 if (StmtList.size() > 0)
5032 return StmtList.back();
5033 return nullptr;
5034}
5035
Michael Kruse1ce67912017-07-20 17:18:58 +00005036ArrayRef<ScopStmt *> Scop::getStmtListFor(RegionNode *RN) const {
Michael Kruse6f7721f2016-02-24 22:08:19 +00005037 if (RN->isSubRegion())
Michael Kruse1ce67912017-07-20 17:18:58 +00005038 return getStmtListFor(RN->getNodeAs<Region>());
5039 return getStmtListFor(RN->getNodeAs<BasicBlock>());
Michael Kruse6f7721f2016-02-24 22:08:19 +00005040}
5041
Michael Kruse1ce67912017-07-20 17:18:58 +00005042ArrayRef<ScopStmt *> Scop::getStmtListFor(Region *R) const {
5043 return getStmtListFor(R->getEntry());
Michael Krusea902ba62015-12-13 19:21:45 +00005044}
5045
Johannes Doerfert96425c22015-08-30 21:13:53 +00005046int Scop::getRelativeLoopDepth(const Loop *L) const {
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00005047 if (!L || !R.contains(L))
Johannes Doerfert96425c22015-08-30 21:13:53 +00005048 return -1;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00005049 // outermostLoopInRegion always returns nullptr for top level regions
5050 if (R.isTopLevelRegion()) {
5051 // LoopInfo's depths start at 1, we start at 0
5052 return L->getLoopDepth() - 1;
5053 } else {
5054 Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
5055 assert(OuterLoop);
5056 return L->getLoopDepth() - OuterLoop->getLoopDepth();
5057 }
Johannes Doerfertd020b772015-08-27 06:53:52 +00005058}
5059
Roman Gareevd7754a12016-07-30 09:25:51 +00005060ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
5061 for (auto &SAI : arrays()) {
5062 if (SAI->getName() == BaseName)
5063 return SAI;
5064 }
5065 return nullptr;
5066}
5067
Michael Kruse8b805802017-07-19 17:11:25 +00005068void Scop::addAccessData(MemoryAccess *Access) {
5069 const ScopArrayInfo *SAI = Access->getOriginalScopArrayInfo();
5070 assert(SAI && "can only use after access relations have been constructed");
5071
5072 if (Access->isOriginalValueKind() && Access->isRead())
5073 ValueUseAccs[SAI].push_back(Access);
5074 else if (Access->isOriginalAnyPHIKind() && Access->isWrite())
5075 PHIIncomingAccs[SAI].push_back(Access);
5076}
5077
5078void Scop::removeAccessData(MemoryAccess *Access) {
5079 if (Access->isOriginalValueKind() && Access->isRead()) {
5080 auto &Uses = ValueUseAccs[Access->getScopArrayInfo()];
5081 std::remove(Uses.begin(), Uses.end(), Access);
5082 } else if (Access->isOriginalAnyPHIKind() && Access->isWrite()) {
5083 auto &Incomings = PHIIncomingAccs[Access->getScopArrayInfo()];
5084 std::remove(Incomings.begin(), Incomings.end(), Access);
5085 }
5086}
5087
5088MemoryAccess *Scop::getValueDef(const ScopArrayInfo *SAI) const {
5089 assert(SAI->isValueKind());
5090
5091 Instruction *Val = dyn_cast<Instruction>(SAI->getBasePtr());
5092 if (!Val)
5093 return nullptr;
5094
5095 ScopStmt *Stmt = getStmtFor(Val);
5096 if (!Stmt)
5097 return nullptr;
5098
5099 return Stmt->lookupValueWriteOf(Val);
5100}
5101
5102ArrayRef<MemoryAccess *> Scop::getValueUses(const ScopArrayInfo *SAI) const {
5103 assert(SAI->isValueKind());
5104 auto It = ValueUseAccs.find(SAI);
5105 if (It == ValueUseAccs.end())
5106 return {};
5107 return It->second;
5108}
5109
5110MemoryAccess *Scop::getPHIRead(const ScopArrayInfo *SAI) const {
5111 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
5112
5113 if (SAI->isExitPHIKind())
5114 return nullptr;
5115
5116 PHINode *PHI = cast<PHINode>(SAI->getBasePtr());
5117 ScopStmt *Stmt = getStmtFor(PHI);
5118 assert(Stmt && "PHINode must be within the SCoP");
5119
5120 return Stmt->lookupPHIReadOf(PHI);
5121}
5122
5123ArrayRef<MemoryAccess *> Scop::getPHIIncomings(const ScopArrayInfo *SAI) const {
5124 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
5125 auto It = PHIIncomingAccs.find(SAI);
5126 if (It == PHIIncomingAccs.end())
5127 return {};
5128 return It->second;
5129}
5130
Johannes Doerfert99191c72016-05-31 09:41:04 +00005131//===----------------------------------------------------------------------===//
5132void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
5133 AU.addRequired<LoopInfoWrapperPass>();
5134 AU.addRequired<RegionInfoPass>();
5135 AU.addRequired<DominatorTreeWrapperPass>();
5136 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005137 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005138 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005139 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005140 AU.setPreservesAll();
5141}
5142
Tobias Grossercd01a362017-02-17 08:12:36 +00005143void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
5144 NumLoopsInScop += Stats.NumLoops;
5145 MaxNumLoopsInScop =
5146 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
5147
Tobias Grossercd01a362017-02-17 08:12:36 +00005148 if (Stats.MaxDepth == 1)
5149 NumScopsDepthOne++;
5150 else if (Stats.MaxDepth == 2)
5151 NumScopsDepthTwo++;
5152 else if (Stats.MaxDepth == 3)
5153 NumScopsDepthThree++;
5154 else if (Stats.MaxDepth == 4)
5155 NumScopsDepthFour++;
5156 else if (Stats.MaxDepth == 5)
5157 NumScopsDepthFive++;
5158 else
5159 NumScopsDepthLarger++;
5160}
5161
Johannes Doerfert99191c72016-05-31 09:41:04 +00005162bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005163 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005164
5165 if (!SD.isMaxRegionInScop(*R))
5166 return false;
5167
5168 Function *F = R->getEntry()->getParent();
5169 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5170 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5171 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5172 auto const &DL = F->getParent()->getDataLayout();
5173 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005174 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005175
Michael Kruse89b1f942017-03-17 13:56:53 +00005176 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005177 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00005178
5179 if (S) {
5180 ScopDetection::LoopStats Stats =
5181 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
5182 updateLoopCountStatistic(Stats);
5183 }
5184
Tobias Grosser75805372011-04-29 06:27:02 +00005185 return false;
5186}
5187
Johannes Doerfert99191c72016-05-31 09:41:04 +00005188void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005189 if (S)
5190 S->print(OS);
5191 else
5192 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00005193}
Tobias Grosser75805372011-04-29 06:27:02 +00005194
Johannes Doerfert99191c72016-05-31 09:41:04 +00005195char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005196
Johannes Doerfert99191c72016-05-31 09:41:04 +00005197Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
5198
5199INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005200 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005201 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00005202INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005203INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00005204INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00005205INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00005206INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005207INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00005208INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005209INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005210 "Polly - Create polyhedral description of Scops", false,
5211 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005212
5213//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00005214ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
5215 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
5216 AssumptionCache &AC) {
Michael Krusea6d48f52017-06-08 12:06:15 +00005217 /// Create polyhedral description of scops for all the valid regions of a
Philip Pfaffe838e0882017-05-15 12:55:14 +00005218 /// function.
5219 for (auto &It : SD) {
5220 Region *R = const_cast<Region *>(It);
5221 if (!SD.isMaxRegionInScop(*R))
5222 continue;
5223
5224 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
5225 std::unique_ptr<Scop> S = SB.getScop();
5226 if (!S)
5227 continue;
5228 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
5229 assert(Inserted && "Building Scop for the same region twice!");
5230 (void)Inserted;
5231 }
5232}
5233
5234AnalysisKey ScopInfoAnalysis::Key;
5235
5236ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
5237 FunctionAnalysisManager &FAM) {
5238 auto &SD = FAM.getResult<ScopAnalysis>(F);
5239 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
5240 auto &LI = FAM.getResult<LoopAnalysis>(F);
5241 auto &AA = FAM.getResult<AAManager>(F);
5242 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
5243 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
5244 auto &DL = F.getParent()->getDataLayout();
5245 return {DL, SD, SE, LI, AA, DT, AC};
5246}
5247
5248PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
5249 FunctionAnalysisManager &FAM) {
5250 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
5251 for (auto &It : SI) {
5252 if (It.second)
5253 It.second->print(Stream);
5254 else
5255 Stream << "Invalid Scop!\n";
5256 }
5257 return PreservedAnalyses::all();
5258}
5259
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005260void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
5261 AU.addRequired<LoopInfoWrapperPass>();
5262 AU.addRequired<RegionInfoPass>();
5263 AU.addRequired<DominatorTreeWrapperPass>();
5264 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005265 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005266 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005267 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005268 AU.setPreservesAll();
5269}
5270
5271bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005272 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005273 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5274 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5275 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5276 auto const &DL = F.getParent()->getDataLayout();
5277 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005278 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005279
Philip Pfaffe838e0882017-05-15 12:55:14 +00005280 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005281 return false;
5282}
5283
5284void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005285 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005286 if (It.second)
5287 It.second->print(OS);
5288 else
5289 OS << "Invalid Scop!\n";
5290 }
5291}
5292
5293char ScopInfoWrapperPass::ID = 0;
5294
5295Pass *polly::createScopInfoWrapperPassPass() {
5296 return new ScopInfoWrapperPass();
5297}
5298
5299INITIALIZE_PASS_BEGIN(
5300 ScopInfoWrapperPass, "polly-function-scops",
5301 "Polly - Create polyhedral description of all Scops of a function", false,
5302 false);
5303INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005304INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005305INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5306INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5307INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005308INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005309INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5310INITIALIZE_PASS_END(
5311 ScopInfoWrapperPass, "polly-function-scops",
5312 "Polly - Create polyhedral description of all Scops of a function", false,
5313 false)