blob: af09745e4c0d53448569764b78d15018e5f9ccf8 [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 Grosser77eef902017-07-21 23:07:56 +000025#include "polly/Support/ISLOStream.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000026#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000027#include "polly/Support/ScopHelper.h"
Tobias Grosser9737c7b2015-11-22 11:06:51 +000028#include "llvm/ADT/DepthFirstIterator.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000029#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000030#include "llvm/ADT/PostOrderIterator.h"
31#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000032#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000033#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000034#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000035#include "llvm/Analysis/AliasAnalysis.h"
Michael Kruse89b1f942017-03-17 13:56:53 +000036#include "llvm/Analysis/AssumptionCache.h"
Johannes Doerfert1dc12af2016-04-23 12:59:18 +000037#include "llvm/Analysis/Loads.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000038#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000039#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000040#include "llvm/Analysis/RegionIterator.h"
41#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000042#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000043#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000044#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000045#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000046#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000047#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000048#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000049#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000050#include "isl/schedule.h"
51#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000052#include "isl/set.h"
53#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000054#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000055#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000056#include <sstream>
57#include <string>
58#include <vector>
59
60using namespace llvm;
61using namespace polly;
62
Chandler Carruth95fef942014-04-22 03:30:19 +000063#define DEBUG_TYPE "polly-scops"
64
Johannes Doerfert81aa6e82016-11-18 14:37:08 +000065STATISTIC(AssumptionsAliasing, "Number of aliasing assumptions taken.");
66STATISTIC(AssumptionsInbounds, "Number of inbounds assumptions taken.");
67STATISTIC(AssumptionsWrapping, "Number of wrapping assumptions taken.");
68STATISTIC(AssumptionsUnsigned, "Number of unsigned assumptions taken.");
69STATISTIC(AssumptionsComplexity, "Number of too complex SCoPs.");
70STATISTIC(AssumptionsUnprofitable, "Number of unprofitable SCoPs.");
71STATISTIC(AssumptionsErrorBlock, "Number of error block assumptions taken.");
72STATISTIC(AssumptionsInfiniteLoop, "Number of bounded loop assumptions taken.");
73STATISTIC(AssumptionsInvariantLoad,
Johannes Doerfertcd195322016-11-17 21:41:08 +000074 "Number of invariant loads assumptions taken.");
Johannes Doerfert81aa6e82016-11-18 14:37:08 +000075STATISTIC(AssumptionsDelinearization,
Johannes Doerfertcd195322016-11-17 21:41:08 +000076 "Number of delinearization assumptions taken.");
77
Tobias Grossercd01a362017-02-17 08:12:36 +000078STATISTIC(NumLoopsInScop, "Number of loops in scops");
79STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
80STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
81STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
82STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
83STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
84STATISTIC(NumScopsDepthLarger,
85 "Number of scops with maximal loop depth 6 and larger");
86STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
87
Tobias Grosser75dc40c2015-12-20 13:31:48 +000088// The maximal number of basic sets we allow during domain construction to
89// be created. More complex scops will result in very high compile time and
90// are also unlikely to result in good code
Tobias Grosser90411a92017-02-16 19:11:33 +000091static int const MaxDisjunctsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +000092
Tobias Grosserc8a82762017-02-16 19:11:25 +000093// The number of disjunct in the context after which we stop to add more
94// disjuncts. This parameter is there to avoid exponential growth in the
95// number of disjunct when adding non-convex sets to the context.
96static int const MaxDisjunctsInContext = 4;
97
Tobias Grosser1eeedf42017-07-20 19:55:19 +000098// The maximal number of dimensions we allow during invariant load construction.
99// More complex access ranges will result in very high compile time and are also
100// unlikely to result in good code. This value is very high and should only
101// trigger for corner cases (e.g., the "dct_luma" function in h264, SPEC2006).
102static int const MaxDimensionsInAccessRange = 9;
103
Tobias Grosser97715842017-05-19 04:01:52 +0000104static cl::opt<int>
105 OptComputeOut("polly-analysis-computeout",
106 cl::desc("Bound the scop analysis by a maximal amount of "
107 "computational steps (0 means no bound)"),
Tobias Grosser57a1d362017-06-23 08:05:27 +0000108 cl::Hidden, cl::init(800000), cl::ZeroOrMore,
Tobias Grosser97715842017-05-19 04:01:52 +0000109 cl::cat(PollyCategory));
Tobias Grosser45e9fd12017-05-19 03:45:00 +0000110
Johannes Doerfert2f705842016-04-12 16:09:44 +0000111static cl::opt<bool> PollyRemarksMinimal(
112 "polly-remarks-minimal",
113 cl::desc("Do not emit remarks about assumptions that are known"),
114 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
115
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +0000116// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000117// operations can overflow easily. Additive reductions and bit operations
118// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +0000119static cl::opt<bool> DisableMultiplicativeReductions(
120 "polly-disable-multiplicative-reductions",
121 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
122 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000123
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +0000124static cl::opt<int> RunTimeChecksMaxAccessDisjuncts(
125 "polly-rtc-max-array-disjuncts",
126 cl::desc("The maximal number of disjunts allowed in memory accesses to "
127 "to build RTCs."),
128 cl::Hidden, cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
129
Johannes Doerfert9143d672014-09-27 11:02:39 +0000130static cl::opt<unsigned> RunTimeChecksMaxParameters(
131 "polly-rtc-max-parameters",
132 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
133 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
134
Tobias Grosser71500722015-03-28 15:11:14 +0000135static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
136 "polly-rtc-max-arrays-per-group",
137 cl::desc("The maximal number of arrays to compare in each alias group."),
138 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000139
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000140static cl::opt<std::string> UserContextStr(
141 "polly-context", cl::value_desc("isl parameter set"),
142 cl::desc("Provide additional constraints on the context parameters"),
143 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000144
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000145static cl::opt<bool> DetectReductions("polly-detect-reductions",
146 cl::desc("Detect and exploit reductions"),
147 cl::Hidden, cl::ZeroOrMore,
148 cl::init(true), cl::cat(PollyCategory));
149
Tobias Grosser2937b592016-04-29 11:43:20 +0000150static cl::opt<bool>
151 IslOnErrorAbort("polly-on-isl-error-abort",
152 cl::desc("Abort if an isl error is encountered"),
153 cl::init(true), cl::cat(PollyCategory));
154
Tobias Grosserd7c49752017-02-28 09:45:54 +0000155static cl::opt<bool> PollyPreciseInbounds(
156 "polly-precise-inbounds",
157 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
158 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
159
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000160static cl::opt<bool>
161 PollyIgnoreInbounds("polly-ignore-inbounds",
162 cl::desc("Do not take inbounds assumptions at all"),
163 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
164
Tobias Grosser5842dee2017-03-17 13:00:53 +0000165static cl::opt<bool> PollyIgnoreParamBounds(
166 "polly-ignore-parameter-bounds",
167 cl::desc(
168 "Do not add parameter bounds and do no gist simplify sets accordingly"),
169 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
170
Tobias Grosserc2f15102017-03-01 21:11:27 +0000171static cl::opt<bool> PollyPreciseFoldAccesses(
172 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000173 cl::desc("Fold memory accesses to model more possible delinearizations "
174 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000175 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000176
Michael Kruse5ae08c02017-05-06 14:03:58 +0000177bool polly::UseInstructionNames;
178static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000179 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000180 cl::desc("Use LLVM-IR names when deriving statement names"),
181 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
182 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000183
Tobias Grosserd5fcbef2017-05-27 04:40:18 +0000184static cl::opt<bool> PollyPrintInstructions(
185 "polly-print-instructions", cl::desc("Output instructions per ScopStmt"),
186 cl::Hidden, cl::Optional, cl::init(false), cl::cat(PollyCategory));
187
Michael Kruse7bf39442015-09-10 12:46:52 +0000188//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000189
Michael Kruse046dde42015-08-10 13:01:57 +0000190// Create a sequence of two schedules. Either argument may be null and is
191// interpreted as the empty schedule. Can also return null if both schedules are
192// empty.
193static __isl_give isl_schedule *
194combineInSequence(__isl_take isl_schedule *Prev,
195 __isl_take isl_schedule *Succ) {
196 if (!Prev)
197 return Succ;
198 if (!Succ)
199 return Prev;
200
201 return isl_schedule_sequence(Prev, Succ);
202}
203
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000204static isl::set addRangeBoundsToSet(isl::set S, const ConstantRange &Range,
205 int dim, isl::dim type) {
206 isl::val V;
207 isl::ctx Ctx = S.get_ctx();
Johannes Doerferte7044942015-02-24 11:58:30 +0000208
Tobias Grosser3281f602017-02-16 18:39:14 +0000209 // The upper and lower bound for a parameter value is derived either from
210 // the data type of the parameter or from the - possibly more restrictive -
211 // range metadata.
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000212 V = valFromAPInt(Ctx.get(), Range.getSignedMin(), true);
213 S = S.lower_bound_val(type, dim, V);
214 V = valFromAPInt(Ctx.get(), Range.getSignedMax(), true);
215 S = S.upper_bound_val(type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000216
Tobias Grosser3281f602017-02-16 18:39:14 +0000217 if (Range.isFullSet())
218 return S;
219
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000220 if (isl_set_n_basic_set(S.get()) > MaxDisjunctsInContext)
Tobias Grosserc8a82762017-02-16 19:11:25 +0000221 return S;
222
Tobias Grosser3281f602017-02-16 18:39:14 +0000223 // In case of signed wrapping, we can refine the set of valid values by
224 // excluding the part not covered by the wrapping range.
225 if (Range.isSignWrappedSet()) {
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000226 V = valFromAPInt(Ctx.get(), Range.getLower(), true);
227 isl::set SLB = S.lower_bound_val(type, dim, V);
Tobias Grosser3281f602017-02-16 18:39:14 +0000228
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000229 V = valFromAPInt(Ctx.get(), Range.getUpper(), true);
230 V = V.sub_ui(1);
231 isl::set SUB = S.upper_bound_val(type, dim, V);
232 S = SLB.unite(SUB);
Tobias Grosser3281f602017-02-16 18:39:14 +0000233 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000234
Tobias Grosser3281f602017-02-16 18:39:14 +0000235 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000236}
237
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000238static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
239 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
240 if (!BasePtrLI)
241 return nullptr;
242
Johannes Doerfert952b5302016-05-23 12:40:48 +0000243 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000244 return nullptr;
245
246 ScalarEvolution &SE = *S->getSE();
247
248 auto *OriginBaseSCEV =
249 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
250 if (!OriginBaseSCEV)
251 return nullptr;
252
253 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
254 if (!OriginBaseSCEVUnknown)
255 return nullptr;
256
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000257 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000258 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000259}
260
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000261ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000262 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000263 const DataLayout &DL, Scop *S,
264 const char *BaseName)
Michael Kruseb738ffa2017-06-28 13:02:43 +0000265 : BasePtr(BasePtr), ElementType(ElementType), IsOnHeap(false), Kind(Kind),
266 DL(DL), S(*S), FAD(nullptr) {
Tobias Grosser92245222015-07-28 14:53:44 +0000267 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000268 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000269 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
270 Kind == MemoryKind::PHI ? "__phi" : "",
271 UseInstructionNames);
Tobias Grosser77eef902017-07-21 23:07:56 +0000272 Id = isl::id::alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000273
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000274 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000275
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000276 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000277 BasePtrOriginSAI = nullptr;
278 return;
279 }
280
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000281 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
282 if (BasePtrOriginSAI)
283 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000284}
285
Tobias Grosser77eef902017-07-21 23:07:56 +0000286isl::space ScopArrayInfo::getSpace() const {
287 auto Space = isl::space(Id.get_ctx(), 0, getNumberOfDimensions());
288 Space = Space.set_tuple_id(isl::dim::set, Id);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000289 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();
Tobias Grosser77eef902017-07-21 23:07:56 +0000294 isl::space Space = getSpace();
Tobias Grosser2ade9862017-05-23 06:41:04 +0000295 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 Grosser77eef902017-07-21 23:07:56 +0000356 DimensionSizesPw[0] = PwAff;
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());
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000380 DimensionSizesPw.clear();
381 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000382 if (!Expr) {
383 DimensionSizesPw.push_back(nullptr);
384 continue;
385 }
Tobias Grosser77eef902017-07-21 23:07:56 +0000386 isl::pw_aff Size = isl::manage(S.getPwAffOnly(Expr));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000387 DimensionSizesPw.push_back(Size);
388 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000389 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000390}
391
Tobias Grosser77eef902017-07-21 23:07:56 +0000392ScopArrayInfo::~ScopArrayInfo() {}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000393
Tobias Grosser77eef902017-07-21 23:07:56 +0000394std::string ScopArrayInfo::getName() const { return Id.get_name(); }
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000395
396int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000397 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000398}
399
Tobias Grosser77eef902017-07-21 23:07:56 +0000400isl::id ScopArrayInfo::getBasePtrId() const { return Id; }
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000401
Michael Kruse5d518462017-07-21 15:54:07 +0000402#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +0000403LLVM_DUMP_METHOD void ScopArrayInfo::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +0000404#endif
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000405
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000406void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000407 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000408 unsigned u = 0;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000409 // If this is a Fortran array, then we can print the outermost dimension
410 // as a isl_pw_aff even though there is no SCEV information.
411 bool IsOutermostSizeKnown = SizeAsPwAff && FAD;
412
413 if (!IsOutermostSizeKnown && getNumberOfDimensions() > 0 &&
414 !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000415 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000416 u++;
417 }
418 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000419 OS << "[";
420
Tobias Grosser26253842015-11-10 14:24:21 +0000421 if (SizeAsPwAff) {
Tobias Grosser77eef902017-07-21 23:07:56 +0000422 isl::pw_aff Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000423 OS << " " << Size << " ";
Tobias Grosser26253842015-11-10 14:24:21 +0000424 } else {
425 OS << *getDimensionSize(u);
426 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000427
428 OS << "]";
429 }
430
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000431 OS << ";";
432
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000433 if (BasePtrOriginSAI)
434 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
435
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000436 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000437}
438
439const ScopArrayInfo *
440ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
441 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
442 assert(Id && "Output dimension didn't have an ID");
443 return getFromId(Id);
444}
445
Michael Krused56b90a2016-09-01 09:03:27 +0000446const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000447 void *User = isl_id_get_user(Id);
448 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
449 isl_id_free(Id);
450 return SAI;
451}
452
Michael Kruse3b425ff2016-04-11 14:34:08 +0000453void MemoryAccess::wrapConstantDimensions() {
454 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000455 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000456 isl::ctx Ctx = ArraySpace.get_ctx();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000457 unsigned DimsArray = SAI->getNumberOfDimensions();
458
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000459 isl::multi_aff DivModAff = isl::multi_aff::identity(
460 ArraySpace.map_from_domain_and_range(ArraySpace));
461 isl::local_space LArraySpace = isl::local_space(ArraySpace);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000462
463 // Begin with last dimension, to iteratively carry into higher dimensions.
464 for (int i = DimsArray - 1; i > 0; i--) {
465 auto *DimSize = SAI->getDimensionSize(i);
466 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
467
468 // This transformation is not applicable to dimensions with dynamic size.
469 if (!DimSizeCst)
470 continue;
471
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000472 // This transformation is not applicable to dimensions of size zero.
473 if (DimSize->isZero())
474 continue;
475
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000476 isl::val DimSizeVal =
477 valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
478 isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
479 isl::aff PrevVar =
480 isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000481
482 // Compute: index % size
483 // Modulo must apply in the divide of the previous iteration, if any.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000484 isl::aff Modulo = Var.mod_val(DimSizeVal);
485 Modulo = Modulo.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000486
487 // Compute: floor(index / size)
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000488 isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
489 Divide = Divide.floor();
490 Divide = Divide.add(PrevVar);
491 Divide = Divide.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000492
493 // Apply Modulo and Divide.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000494 DivModAff = DivModAff.set_aff(i, Modulo);
495 DivModAff = DivModAff.set_aff(i - 1, Divide);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000496 }
497
498 // Apply all modulo/divides on the accesses.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000499 isl::map Relation = AccessRelation;
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000500 Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
501 Relation = Relation.detect_equalities();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000502 AccessRelation = Relation;
Michael Kruse3b425ff2016-04-11 14:34:08 +0000503}
504
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000505void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000506 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000507 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000508 isl::space AccessSpace = AccessRelation.get_space().range();
Tobias Grosser7be82452017-05-21 20:38:33 +0000509 isl::ctx Ctx = ArraySpace.get_ctx();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000510
Tobias Grosser7be82452017-05-21 20:38:33 +0000511 auto DimsArray = ArraySpace.dim(isl::dim::set);
512 auto DimsAccess = AccessSpace.dim(isl::dim::set);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000513 auto DimsMissing = DimsArray - DimsAccess;
514
Michael Kruse375cb5f2016-02-24 22:08:24 +0000515 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000516 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000517 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000518 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000519
Tobias Grosser7be82452017-05-21 20:38:33 +0000520 isl::map Map = isl::map::from_domain_and_range(
521 isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000522
523 for (unsigned i = 0; i < DimsMissing; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000524 Map = Map.fix_si(isl::dim::out, i, 0);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000525
526 for (unsigned i = DimsMissing; i < DimsArray; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000527 Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000528
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000529 AccessRelation = AccessRelation.apply_range(Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000530
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000531 // For the non delinearized arrays, divide the access function of the last
532 // subscript by the size of the elements in the array.
533 //
534 // A stride one array access in C expressed as A[i] is expressed in
535 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
536 // two subsequent values of 'i' index two values that are stored next to
537 // each other in memory. By this division we make this characteristic
538 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000539 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000540 // that divides the offsets of all accesses to this base pointer.
541 if (DimsAccess == 1) {
Tobias Grosser7be82452017-05-21 20:38:33 +0000542 isl::val V = isl::val(Ctx, ArrayElemSize);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000543 AccessRelation = AccessRelation.floordiv_val(V);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000544 }
545
Michael Kruse3b425ff2016-04-11 14:34:08 +0000546 // We currently do this only if we added at least one dimension, which means
547 // some dimension's indices have not been specified, an indicator that some
548 // index values have been added together.
549 // TODO: Investigate general usefulness; Effect on unit tests is to make index
550 // expressions more complicated.
551 if (DimsMissing)
552 wrapConstantDimensions();
553
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000554 if (!isAffine())
555 computeBoundsOnAccessRelation(ArrayElemSize);
556
Tobias Grosserd840fc72016-02-04 13:18:42 +0000557 // Introduce multi-element accesses in case the type loaded by this memory
558 // access is larger than the canonical element type of the array.
559 //
560 // An access ((float *)A)[i] to an array char *A is modeled as
561 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000562 if (ElemBytes > ArrayElemSize) {
563 assert(ElemBytes % ArrayElemSize == 0 &&
564 "Loaded element size should be multiple of canonical element size");
Tobias Grosser7be82452017-05-21 20:38:33 +0000565 isl::map Map = isl::map::from_domain_and_range(
566 isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000567 for (unsigned i = 0; i < DimsArray - 1; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000568 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000569
Tobias Grosser7be82452017-05-21 20:38:33 +0000570 isl::constraint C;
571 isl::local_space LS;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000572
Tobias Grosser7be82452017-05-21 20:38:33 +0000573 LS = isl::local_space(Map.get_space());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000574 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
575
Tobias Grosser7be82452017-05-21 20:38:33 +0000576 C = isl::constraint::alloc_inequality(LS);
577 C = C.set_constant_val(isl::val(Ctx, Num - 1));
578 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
579 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
580 Map = Map.add_constraint(C);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000581
Tobias Grosser7be82452017-05-21 20:38:33 +0000582 C = isl::constraint::alloc_inequality(LS);
583 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, -1);
584 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, 1);
585 C = C.set_constant_val(isl::val(Ctx, 0));
586 Map = Map.add_constraint(C);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000587 AccessRelation = AccessRelation.apply_range(Map);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000588 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000589}
590
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000591const std::string
592MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
593 switch (RT) {
594 case MemoryAccess::RT_NONE:
595 llvm_unreachable("Requested a reduction operator string for a memory "
596 "access which isn't a reduction");
597 case MemoryAccess::RT_ADD:
598 return "+";
599 case MemoryAccess::RT_MUL:
600 return "*";
601 case MemoryAccess::RT_BOR:
602 return "|";
603 case MemoryAccess::RT_BXOR:
604 return "^";
605 case MemoryAccess::RT_BAND:
606 return "&";
607 }
608 llvm_unreachable("Unknown reduction type");
609 return "";
610}
611
Tobias Grosserc80d6972016-09-02 06:33:33 +0000612/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000613static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
614 const Instruction *Load) {
615 if (!BinOp)
616 return MemoryAccess::RT_NONE;
617 switch (BinOp->getOpcode()) {
618 case Instruction::FAdd:
619 if (!BinOp->hasUnsafeAlgebra())
620 return MemoryAccess::RT_NONE;
621 // Fall through
622 case Instruction::Add:
623 return MemoryAccess::RT_ADD;
624 case Instruction::Or:
625 return MemoryAccess::RT_BOR;
626 case Instruction::Xor:
627 return MemoryAccess::RT_BXOR;
628 case Instruction::And:
629 return MemoryAccess::RT_BAND;
630 case Instruction::FMul:
631 if (!BinOp->hasUnsafeAlgebra())
632 return MemoryAccess::RT_NONE;
633 // Fall through
634 case Instruction::Mul:
635 if (DisableMultiplicativeReductions)
636 return MemoryAccess::RT_NONE;
637 return MemoryAccess::RT_MUL;
638 default:
639 return MemoryAccess::RT_NONE;
640 }
641}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000642
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000643MemoryAccess::~MemoryAccess() { isl_set_free(InvalidDomain); }
Tobias Grosser75805372011-04-29 06:27:02 +0000644
Michael Kruse2fa35192016-09-01 19:53:31 +0000645const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000646 isl_id *ArrayId = getArrayId();
647 void *User = isl_id_get_user(ArrayId);
648 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
649 isl_id_free(ArrayId);
650 return SAI;
651}
652
Michael Kruse2fa35192016-09-01 19:53:31 +0000653const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
654 isl_id *ArrayId = getLatestArrayId();
655 void *User = isl_id_get_user(ArrayId);
656 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
657 isl_id_free(ArrayId);
658 return SAI;
659}
660
661__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000662 return isl_map_get_tuple_id(AccessRelation.get(), isl_dim_out);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000663}
664
Michael Kruse2fa35192016-09-01 19:53:31 +0000665__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
666 if (!hasNewAccessRelation())
667 return getOriginalArrayId();
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000668 return NewAccessRelation.get_tuple_id(isl::dim::out).release();
Michael Kruse2fa35192016-09-01 19:53:31 +0000669}
670
Tobias Grosserd840fc72016-02-04 13:18:42 +0000671__isl_give isl_map *MemoryAccess::getAddressFunction() const {
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000672 return isl_map_lexmin(getAccessRelation().release());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000673}
674
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000675__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
676 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000677 isl_map *Schedule, *ScheduledAccRel;
678 isl_union_set *UDomain;
679
680 UDomain = isl_union_set_from_set(getStatement()->getDomain());
681 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
682 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000683 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000684 return isl_pw_multi_aff_from_map(ScheduledAccRel);
685}
686
Tobias Grosser22da5f02017-07-23 04:08:27 +0000687isl::map MemoryAccess::getOriginalAccessRelation() const {
688 return AccessRelation;
Tobias Grosser5d453812011-10-06 00:04:11 +0000689}
690
Johannes Doerferta99130f2014-10-13 12:58:03 +0000691std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000692 return stringFromIslObj(AccessRelation.get());
Tobias Grosser5d453812011-10-06 00:04:11 +0000693}
694
Tobias Grosser22da5f02017-07-23 04:08:27 +0000695isl::space MemoryAccess::getOriginalAccessRelationSpace() const {
696 return AccessRelation.get_space();
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000697}
698
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000699isl::map MemoryAccess::getNewAccessRelation() const {
700 return NewAccessRelation;
Tobias Grosser75805372011-04-29 06:27:02 +0000701}
702
Tobias Grosser6f730082015-09-05 07:46:47 +0000703std::string MemoryAccess::getNewAccessRelationStr() const {
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000704 return stringFromIslObj(NewAccessRelation.get());
Tobias Grosser6f730082015-09-05 07:46:47 +0000705}
706
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000707std::string MemoryAccess::getAccessRelationStr() const {
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000708 return isl::manage(getAccessRelation().get()).to_str();
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000709}
710
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000711isl::basic_map MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
712 isl::space Space = isl::space(Statement->getIslCtx(), 0, 1);
713 Space = Space.align_params(isl::manage(Statement->getDomainSpace()));
Tobias Grosser75805372011-04-29 06:27:02 +0000714
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000715 return isl::basic_map::from_domain_and_range(
716 isl::basic_set::universe(isl::manage(Statement->getDomainSpace())),
717 isl::basic_set::universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000718}
719
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000720// Formalize no out-of-bound access assumption
721//
722// When delinearizing array accesses we optimistically assume that the
723// delinearized accesses do not access out of bound locations (the subscript
724// expression of each array evaluates for each statement instance that is
725// executed to a value that is larger than zero and strictly smaller than the
726// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000727// dimension for which we do not need to assume any upper bound. At this point
728// we formalize this assumption to ensure that at code generation time the
729// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000730//
731// To find the set of constraints necessary to avoid out of bound accesses, we
732// first build the set of data locations that are not within array bounds. We
733// then apply the reverse access relation to obtain the set of iterations that
734// may contain invalid accesses and reduce this set of iterations to the ones
735// that are actually executed by intersecting them with the domain of the
736// statement. If we now project out all loop dimensions, we obtain a set of
737// parameters that may cause statement instances to be executed that may
738// possibly yield out of bound memory accesses. The complement of these
739// constraints is the set of constraints that needs to be assumed to ensure such
740// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000741void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000742 if (PollyIgnoreInbounds)
743 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000744 auto *SAI = getScopArrayInfo();
Tobias Grosser22da5f02017-07-23 04:08:27 +0000745 isl::space Space = getOriginalAccessRelationSpace().range();
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000746 isl::set Outside = isl::set::empty(Space);
747 for (int i = 1, Size = Space.dim(isl::dim::set); i < Size; ++i) {
748 isl::local_space LS(Space);
749 isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
750 isl::pw_aff Zero = isl::pw_aff(LS);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000751
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000752 isl::set DimOutside = Var.lt_set(Zero);
Tobias Grosser77eef902017-07-21 23:07:56 +0000753 isl::pw_aff SizeE = SAI->getDimensionSizePw(i);
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000754 SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set));
755 SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
756 DimOutside = DimOutside.unite(SizeE.le_set(Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000757
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000758 Outside = Outside.unite(DimOutside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000759 }
760
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000761 Outside = Outside.apply(getAccessRelation().reverse());
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000762 Outside = Outside.intersect(give(Statement->getDomain()));
763 Outside = Outside.params();
Tobias Grosserf54bb772015-06-26 12:09:28 +0000764
765 // Remove divs to avoid the construction of overly complicated assumptions.
766 // Doing so increases the set of parameter combinations that are assumed to
767 // not appear. This is always save, but may make the resulting run-time check
768 // bail out more often than strictly necessary.
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000769 Outside = Outside.remove_divs();
770 Outside = Outside.complement();
Michael Kruse7071e8b2016-04-11 13:24:29 +0000771 const auto &Loc = getAccessInstruction()
772 ? getAccessInstruction()->getDebugLoc()
773 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000774 if (!PollyPreciseInbounds)
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000775 Outside = Outside.gist_params(give(Statement->getDomain()).params());
776 Statement->getParent()->recordAssumption(INBOUNDS, Outside.release(), Loc,
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000777 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000778}
779
Johannes Doerfertcea61932016-02-21 19:13:19 +0000780void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000781 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000782 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000783
Tobias Grosser53fc3552017-05-23 07:07:09 +0000784 isl::pw_aff SubscriptPWA = give(getPwAff(Subscripts[0]));
785 isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000786
Tobias Grosser53fc3552017-05-23 07:07:09 +0000787 isl::map LengthMap;
Johannes Doerferta7920982016-02-25 14:08:48 +0000788 if (Subscripts[1] == nullptr) {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000789 LengthMap = isl::map::universe(SubscriptMap.get_space());
Johannes Doerferta7920982016-02-25 14:08:48 +0000790 } else {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000791 isl::pw_aff LengthPWA = give(getPwAff(Subscripts[1]));
792 LengthMap = isl::map::from_pw_aff(LengthPWA);
793 isl::space RangeSpace = LengthMap.get_space().range();
794 LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
Johannes Doerferta7920982016-02-25 14:08:48 +0000795 }
Tobias Grosser53fc3552017-05-23 07:07:09 +0000796 LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
797 LengthMap = LengthMap.align_params(SubscriptMap.get_space());
798 SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
799 LengthMap = LengthMap.sum(SubscriptMap);
800 AccessRelation =
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000801 LengthMap.set_tuple_id(isl::dim::in, give(getStatement()->getDomainId()));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000802}
803
Johannes Doerferte7044942015-02-24 11:58:30 +0000804void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
805 ScalarEvolution *SE = Statement->getParent()->getSE();
806
Johannes Doerfertcea61932016-02-21 19:13:19 +0000807 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000808 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000809 return;
810
811 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000812 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
813 return;
814
815 auto *PtrSCEV = SE->getSCEV(Ptr);
816 if (isa<SCEVCouldNotCompute>(PtrSCEV))
817 return;
818
819 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
820 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
821 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
822
823 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
824 if (Range.isFullSet())
825 return;
826
Michael Kruse960c0d02017-05-18 21:55:36 +0000827 if (Range.isWrappedSet() || Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000828 return;
829
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000830 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000831
Johannes Doerferte7044942015-02-24 11:58:30 +0000832 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000833 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000834 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000835 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000836
837 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000838 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000839
Tobias Grosserb3a85882017-02-12 08:11:12 +0000840 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
841
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000842 isl::map Relation = AccessRelation;
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000843 isl::set AccessRange = Relation.range();
844 AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
845 isl::dim::set);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000846 AccessRelation = Relation.intersect_range(AccessRange);
Johannes Doerferte7044942015-02-24 11:58:30 +0000847}
848
Tobias Grosser491b7992016-12-02 05:21:22 +0000849void MemoryAccess::foldAccessRelation() {
850 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
851 return;
852
Michael Krusee2bccbb2015-09-18 19:59:43 +0000853 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000854
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000855 isl::map NewAccessRelation = AccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000856
Tobias Grosser619190d2015-03-30 17:22:28 +0000857 for (int i = Size - 2; i >= 0; --i) {
Tobias Grossera32de132017-05-23 07:22:56 +0000858 isl::space Space;
859 isl::map MapOne, MapTwo;
860 isl::pw_aff DimSize = give(getPwAff(Sizes[i + 1]));
Tobias Grosser619190d2015-03-30 17:22:28 +0000861
Tobias Grossera32de132017-05-23 07:22:56 +0000862 isl::space SpaceSize = DimSize.get_space();
863 isl::id ParamId =
864 give(isl_space_get_dim_id(SpaceSize.get(), isl_dim_param, 0));
Tobias Grosser619190d2015-03-30 17:22:28 +0000865
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000866 Space = AccessRelation.get_space();
Tobias Grossera32de132017-05-23 07:22:56 +0000867 Space = Space.range().map_from_set();
868 Space = Space.align_params(SpaceSize);
Tobias Grosser619190d2015-03-30 17:22:28 +0000869
Tobias Grossera32de132017-05-23 07:22:56 +0000870 int ParamLocation = Space.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosser619190d2015-03-30 17:22:28 +0000871
Tobias Grossera32de132017-05-23 07:22:56 +0000872 MapOne = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000873 for (int j = 0; j < Size; ++j)
Tobias Grossera32de132017-05-23 07:22:56 +0000874 MapOne = MapOne.equate(isl::dim::in, j, isl::dim::out, j);
875 MapOne = MapOne.lower_bound_si(isl::dim::in, i + 1, 0);
Tobias Grosser619190d2015-03-30 17:22:28 +0000876
Tobias Grossera32de132017-05-23 07:22:56 +0000877 MapTwo = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000878 for (int j = 0; j < Size; ++j)
879 if (j < i || j > i + 1)
Tobias Grossera32de132017-05-23 07:22:56 +0000880 MapTwo = MapTwo.equate(isl::dim::in, j, isl::dim::out, j);
Tobias Grosser619190d2015-03-30 17:22:28 +0000881
Tobias Grossera32de132017-05-23 07:22:56 +0000882 isl::local_space LS(Space);
883 isl::constraint C;
884 C = isl::constraint::alloc_equality(LS);
885 C = C.set_constant_si(-1);
886 C = C.set_coefficient_si(isl::dim::in, i, 1);
887 C = C.set_coefficient_si(isl::dim::out, i, -1);
888 MapTwo = MapTwo.add_constraint(C);
889 C = isl::constraint::alloc_equality(LS);
890 C = C.set_coefficient_si(isl::dim::in, i + 1, 1);
891 C = C.set_coefficient_si(isl::dim::out, i + 1, -1);
892 C = C.set_coefficient_si(isl::dim::param, ParamLocation, 1);
893 MapTwo = MapTwo.add_constraint(C);
894 MapTwo = MapTwo.upper_bound_si(isl::dim::in, i + 1, -1);
Tobias Grosser619190d2015-03-30 17:22:28 +0000895
Tobias Grossera32de132017-05-23 07:22:56 +0000896 MapOne = MapOne.unite(MapTwo);
897 NewAccessRelation = NewAccessRelation.apply_range(MapOne);
Tobias Grosser619190d2015-03-30 17:22:28 +0000898 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000899
Tobias Grosser77eef902017-07-21 23:07:56 +0000900 isl::id BaseAddrId = getScopArrayInfo()->getBasePtrId();
Tobias Grossera32de132017-05-23 07:22:56 +0000901 isl::space Space = give(Statement->getDomainSpace());
902 NewAccessRelation = NewAccessRelation.set_tuple_id(
903 isl::dim::in, Space.get_tuple_id(isl::dim::set));
904 NewAccessRelation = NewAccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
905 NewAccessRelation =
906 NewAccessRelation.gist_domain(give(Statement->getDomain()));
Tobias Grosserc2f15102017-03-01 21:11:27 +0000907
908 // Access dimension folding might in certain cases increase the number of
909 // disjuncts in the memory access, which can possibly complicate the generated
910 // run-time checks and can lead to costly compilation.
Tobias Grossera32de132017-05-23 07:22:56 +0000911 if (!PollyPreciseFoldAccesses &&
912 isl_map_n_basic_map(NewAccessRelation.get()) >
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000913 isl_map_n_basic_map(AccessRelation.get())) {
Tobias Grosserc2f15102017-03-01 21:11:27 +0000914 } else {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000915 AccessRelation = NewAccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000916 }
Tobias Grosser619190d2015-03-30 17:22:28 +0000917}
918
Tobias Grosserc80d6972016-09-02 06:33:33 +0000919/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000920static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000921 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000922 if (Size == 1)
923 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000924
925 // Only one factor needs to be divisible.
926 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
927 for (auto *FactorExpr : MulExpr->operands())
928 if (isDivisible(FactorExpr, Size, SE))
929 return true;
930 return false;
931 }
932
933 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
Michael Krusea6d48f52017-06-08 12:06:15 +0000934 // to be divisible.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000935 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
936 for (auto *OpExpr : NAryExpr->operands())
937 if (!isDivisible(OpExpr, Size, SE))
938 return false;
939 return true;
940 }
941
942 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
943 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
944 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
945 return MulSCEV == Expr;
946}
947
Michael Krusee2bccbb2015-09-18 19:59:43 +0000948void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000949 assert(AccessRelation.is_null() && "AccessRelation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000950
Johannes Doerfert85676e32016-04-23 14:32:34 +0000951 // Initialize the invalid domain which describes all iterations for which the
952 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000953 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
954 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
955 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000956
Tobias Grosserfe46c3f2017-07-23 04:08:11 +0000957 isl_ctx *Ctx = Id.get_ctx().release();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000958 isl::id BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000959
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000960 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
961 buildMemIntrinsicAccessRelation();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000962 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000963 return;
964 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000965
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000966 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000967 // We overapproximate non-affine accesses with a possible access to the
968 // whole array. For read accesses it does not make a difference, if an
969 // access must or may happen. However, for write accesses it is important to
970 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000971 if (AccessRelation.is_null())
972 AccessRelation = createBasicAccessMap(Statement);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000973
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000974 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000975 return;
976 }
977
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000978 isl::space Space = isl::space(Ctx, 0, Statement->getNumIterators(), 0);
979 AccessRelation = isl::map::universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000980
Michael Krusee2bccbb2015-09-18 19:59:43 +0000981 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000982 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000983 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000984 AccessRelation =
985 AccessRelation.flat_range_product(isl::manage(SubscriptMap));
Sebastian Pop18016682014-04-08 21:20:44 +0000986 }
987
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000988 Space = isl::manage(Statement->getDomainSpace());
989 AccessRelation = AccessRelation.set_tuple_id(
990 isl::dim::in, Space.get_tuple_id(isl::dim::set));
991 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000992
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000993 AccessRelation =
994 AccessRelation.gist_domain(isl::manage(Statement->getDomain()));
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000995}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000996
Michael Krusecac948e2015-10-02 13:53:07 +0000997MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000998 AccessType AccType, Value *BaseAddress,
999 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +00001000 ArrayRef<const SCEV *> Subscripts,
1001 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +00001002 MemoryKind Kind)
Johannes Doerfertcea61932016-02-21 19:13:19 +00001003 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Tobias Grosser81331282017-05-03 07:57:35 +00001004 InvalidDomain(nullptr), BaseAddr(BaseAddress), ElementType(ElementType),
1005 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
1006 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +00001007 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001008 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +00001009 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001010 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001011
Tobias Grosser81331282017-05-03 07:57:35 +00001012 std::string IdName = Stmt->getBaseName() + Access;
Tobias Grosserfe46c3f2017-07-23 04:08:11 +00001013 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001014}
Michael Krusee2bccbb2015-09-18 19:59:43 +00001015
Roman Gareevb3224ad2016-09-14 06:26:09 +00001016MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
1017 __isl_take isl_map *AccRel)
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001018 : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
1019 Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001020 IsAffine(true), AccessRelation(nullptr),
1021 NewAccessRelation(isl::manage(AccRel)), FAD(nullptr) {
1022 auto *ArrayInfoId = NewAccessRelation.get_tuple_id(isl::dim::out).release();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001023 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1024 Sizes.push_back(nullptr);
1025 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1026 Sizes.push_back(SAI->getDimensionSize(i));
1027 ElementType = SAI->getElementType();
1028 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001029 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001030 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001031
Tobias Grosser81331282017-05-03 07:57:35 +00001032 std::string IdName = Stmt->getBaseName() + Access;
Tobias Grosserfe46c3f2017-07-23 04:08:11 +00001033 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001034}
1035
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001036void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +00001037 auto *Ctx = Statement->getParent()->getContext();
1038 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001039 AccessRelation = AccessRelation.gist_params(isl::manage(Ctx));
Tobias Grosser75805372011-04-29 06:27:02 +00001040}
1041
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001042const std::string MemoryAccess::getReductionOperatorStr() const {
1043 return MemoryAccess::getReductionOperatorStr(getReductionType());
1044}
1045
Tobias Grosserfe46c3f2017-07-23 04:08:11 +00001046isl::id MemoryAccess::getId() const { return Id; }
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001047
Johannes Doerfertf6183392014-07-01 20:52:51 +00001048raw_ostream &polly::operator<<(raw_ostream &OS,
1049 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001050 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001051 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001052 else
1053 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001054 return OS;
1055}
1056
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001057void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001058
Tobias Grosser75805372011-04-29 06:27:02 +00001059void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001060 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001061 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001062 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001063 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001064 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001065 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001066 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001067 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001068 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001069 break;
1070 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001071
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001072 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001073
1074 if (FAD) {
1075 OS << "[Fortran array descriptor: " << FAD->getName();
1076 OS << "] ";
1077 };
1078
Tobias Grossera535dff2015-12-13 19:59:01 +00001079 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001080 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001081 if (hasNewAccessRelation())
1082 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001083}
1084
Michael Kruse5d518462017-07-21 15:54:07 +00001085#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001086LLVM_DUMP_METHOD void MemoryAccess::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +00001087#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001088
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001089__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
1090 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001091 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +00001092 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
1093 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
1094 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +00001095 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001096}
1097
Tobias Grosser75805372011-04-29 06:27:02 +00001098// Create a map in the size of the provided set domain, that maps from the
1099// one element of the provided set domain to another element of the provided
1100// set domain.
1101// The mapping is limited to all points that are equal in all but the last
1102// dimension and for which the last dimension of the input is strict smaller
1103// than the last dimension of the output.
1104//
1105// getEqualAndLarger(set[i0, i1, ..., iX]):
1106//
1107// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1108// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1109//
Tobias Grosser2a526fe2016-09-08 11:18:56 +00001110static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +00001111 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001112 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +00001113 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001114
1115 // Set all but the last dimension to be equal for the input and output
1116 //
1117 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1118 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001119 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +00001120 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001121
1122 // Set the last dimension of the input to be strict smaller than the
1123 // last dimension of the output.
1124 //
1125 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001126 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1127 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001128 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001129}
1130
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001131__isl_give isl_set *
1132MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001133 isl_map *S = const_cast<isl_map *>(Schedule);
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001134 isl_map *AccessRelation = getAccessRelation().release();
Sebastian Popa00a0292012-12-18 07:46:06 +00001135 isl_space *Space = isl_space_range(isl_map_get_space(S));
1136 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001137
Sebastian Popa00a0292012-12-18 07:46:06 +00001138 S = isl_map_reverse(S);
1139 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001140
Sebastian Popa00a0292012-12-18 07:46:06 +00001141 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1142 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1143 NextScatt = isl_map_apply_domain(NextScatt, S);
1144 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001145
Sebastian Popa00a0292012-12-18 07:46:06 +00001146 isl_set *Deltas = isl_map_deltas(NextScatt);
1147 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001148}
1149
Sebastian Popa00a0292012-12-18 07:46:06 +00001150bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001151 int StrideWidth) const {
1152 isl_set *Stride, *StrideX;
1153 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001154
Sebastian Popa00a0292012-12-18 07:46:06 +00001155 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001156 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001157 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1158 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1159 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1160 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001161 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001162
Tobias Grosser28dd4862012-01-24 16:42:16 +00001163 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001164 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001165
Tobias Grosser28dd4862012-01-24 16:42:16 +00001166 return IsStrideX;
1167}
1168
Michael Krused56b90a2016-09-01 09:03:27 +00001169bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001170 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001171}
1172
Michael Krused56b90a2016-09-01 09:03:27 +00001173bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001174 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001175}
1176
Tobias Grosserbedef002016-12-02 08:10:56 +00001177void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001178 AccessRelation = isl::manage(NewAccess);
Tobias Grosserbedef002016-12-02 08:10:56 +00001179}
1180
Michael Krused56b90a2016-09-01 09:03:27 +00001181void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001182 assert(NewAccess);
1183
1184#ifndef NDEBUG
1185 // Check domain space compatibility.
1186 auto *NewSpace = isl_map_get_space(NewAccess);
1187 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1188 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1189 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1190 isl_space_free(NewDomainSpace);
1191 isl_space_free(OriginalDomainSpace);
1192
Michael Kruse706f79a2017-05-21 22:46:57 +00001193 // Reads must be executed unconditionally. Writes might be executed in a
1194 // subdomain only.
1195 if (isRead()) {
1196 // Check whether there is an access for every statement instance.
1197 auto *StmtDomain = getStatement()->getDomain();
1198 StmtDomain = isl_set_intersect_params(
1199 StmtDomain, getStatement()->getParent()->getContext());
1200 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1201 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1202 "Partial READ accesses not supported");
1203 isl_set_free(NewDomain);
1204 isl_set_free(StmtDomain);
1205 }
Michael Kruse772ce722016-09-01 19:16:58 +00001206
Michael Kruse772ce722016-09-01 19:16:58 +00001207 auto *NewAccessSpace = isl_space_range(NewSpace);
1208 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1209 "Must specify the array that is accessed");
1210 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1211 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1212 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001213
1214 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1215 InvariantEquivClassTy *EqClass =
1216 getStatement()->getParent()->lookupInvariantEquivClass(
1217 SAI->getBasePtr());
1218 assert(EqClass &&
1219 "Access functions to indirect arrays must have an invariant and "
1220 "hoisted base pointer");
1221 }
1222
1223 // Check whether access dimensions correspond to number of dimensions of the
1224 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001225 auto Dims = SAI->getNumberOfDimensions();
1226 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1227 "Access dims must match array dims");
1228 isl_space_free(NewAccessSpace);
1229 isl_id_free(NewArrayId);
1230#endif
1231
Tobias Grosser4556c9b2017-07-17 20:47:10 +00001232 NewAccess = isl_map_gist_domain(NewAccess, getStatement()->getDomain());
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001233 NewAccessRelation = isl::manage(NewAccess);
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001234}
Tobias Grosser75805372011-04-29 06:27:02 +00001235
Michael Kruse706f79a2017-05-21 22:46:57 +00001236bool MemoryAccess::isLatestPartialAccess() const {
1237 isl::set StmtDom = give(getStatement()->getDomain());
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001238 isl::set AccDom = getLatestAccessRelation().domain();
Michael Kruse706f79a2017-05-21 22:46:57 +00001239
1240 return isl_set_is_subset(StmtDom.keep(), AccDom.keep()) == isl_bool_false;
1241}
1242
Tobias Grosser75805372011-04-29 06:27:02 +00001243//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001244
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001245__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001246 isl_set *Domain = getDomain();
1247 if (isl_set_is_empty(Domain)) {
1248 isl_set_free(Domain);
1249 return isl_map_from_aff(
1250 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1251 }
1252 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001253 if (!Schedule) {
1254 isl_set_free(Domain);
1255 return nullptr;
1256 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001257 Schedule = isl_union_map_intersect_domain(
1258 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1259 if (isl_union_map_is_empty(Schedule)) {
1260 isl_set_free(Domain);
1261 isl_union_map_free(Schedule);
1262 return isl_map_from_aff(
1263 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1264 }
1265 auto *M = isl_map_from_union_map(Schedule);
1266 M = isl_map_coalesce(M);
1267 M = isl_map_gist_domain(M, Domain);
1268 M = isl_map_coalesce(M);
1269 return M;
1270}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001271
Tobias Grosser37eb4222014-02-20 21:43:54 +00001272void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1273 assert(isl_set_is_subset(NewDomain, Domain) &&
1274 "New domain is not a subset of old domain!");
1275 isl_set_free(Domain);
1276 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001277}
1278
Michael Krusecac948e2015-10-02 13:53:07 +00001279void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001280 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001281 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001282 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001283
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001284 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001285 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001286 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001287 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001288 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001289 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001290 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001291 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001292 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001293
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001294 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1295 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001296 Access->buildAccessRelation(SAI);
Michael Kruse8b805802017-07-19 17:11:25 +00001297 S.addAccessData(Access);
Tobias Grosser75805372011-04-29 06:27:02 +00001298 }
1299}
1300
Michael Krusecac948e2015-10-02 13:53:07 +00001301void ScopStmt::addAccess(MemoryAccess *Access) {
1302 Instruction *AccessInst = Access->getAccessInstruction();
1303
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001304 if (Access->isArrayKind()) {
1305 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1306 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001307 } else if (Access->isValueKind() && Access->isWrite()) {
1308 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001309 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001310 assert(!ValueWrites.lookup(AccessVal));
1311
1312 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001313 } else if (Access->isValueKind() && Access->isRead()) {
1314 Value *AccessVal = Access->getAccessValue();
1315 assert(!ValueReads.lookup(AccessVal));
1316
1317 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001318 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001319 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001320 assert(!PHIWrites.lookup(PHI));
1321
1322 PHIWrites[PHI] = Access;
Michael Kruse3562f272017-07-20 16:47:57 +00001323 } else if (Access->isAnyPHIKind() && Access->isRead()) {
1324 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1325 assert(!PHIReads.lookup(PHI));
1326
1327 PHIReads[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001328 }
1329
1330 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001331}
1332
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001333void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001334 for (MemoryAccess *MA : *this)
1335 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001336
Johannes Doerferta60ad842016-05-10 12:18:22 +00001337 auto *Ctx = Parent.getContext();
1338 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1339 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001340}
1341
Tobias Grosserc80d6972016-09-02 06:33:33 +00001342/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001343static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1344 void *User) {
1345 isl_set **BoundedParts = static_cast<isl_set **>(User);
1346 if (isl_basic_set_is_bounded(BSet))
1347 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1348 else
1349 isl_basic_set_free(BSet);
1350 return isl_stat_ok;
1351}
1352
Tobias Grosserc80d6972016-09-02 06:33:33 +00001353/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001354static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1355 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1356 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1357 isl_set_free(S);
1358 return BoundedParts;
1359}
1360
Tobias Grosserc80d6972016-09-02 06:33:33 +00001361/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001362///
1363/// @returns A separation of @p S into first an unbounded then a bounded subset,
1364/// both with regards to the dimension @p Dim.
1365static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1366partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1367
1368 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001369 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001370
1371 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001372 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001373
1374 // Remove dimensions that are greater than Dim as they are not interesting.
1375 assert(NumDimsS >= Dim + 1);
1376 OnlyDimS =
1377 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1378
1379 // Create artificial parametric upper bounds for dimensions smaller than Dim
1380 // as we are not interested in them.
1381 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1382 for (unsigned u = 0; u < Dim; u++) {
1383 isl_constraint *C = isl_inequality_alloc(
1384 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1385 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1386 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1387 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1388 }
1389
1390 // Collect all bounded parts of OnlyDimS.
1391 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1392
1393 // Create the dimensions greater than Dim again.
1394 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1395 NumDimsS - Dim - 1);
1396
1397 // Remove the artificial upper bound parameters again.
1398 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1399
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001400 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001401 return std::make_pair(UnboundedParts, BoundedParts);
1402}
1403
Tobias Grosserc80d6972016-09-02 06:33:33 +00001404/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001405static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1406 __isl_take isl_set *To) {
1407 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1408 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1409 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1410 }
1411 return To;
1412}
1413
Tobias Grosserc80d6972016-09-02 06:33:33 +00001414/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001415static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001416 __isl_take isl_pw_aff *L,
1417 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001418 switch (Pred) {
1419 case ICmpInst::ICMP_EQ:
1420 return isl_pw_aff_eq_set(L, R);
1421 case ICmpInst::ICMP_NE:
1422 return isl_pw_aff_ne_set(L, R);
1423 case ICmpInst::ICMP_SLT:
1424 return isl_pw_aff_lt_set(L, R);
1425 case ICmpInst::ICMP_SLE:
1426 return isl_pw_aff_le_set(L, R);
1427 case ICmpInst::ICMP_SGT:
1428 return isl_pw_aff_gt_set(L, R);
1429 case ICmpInst::ICMP_SGE:
1430 return isl_pw_aff_ge_set(L, R);
1431 case ICmpInst::ICMP_ULT:
1432 return isl_pw_aff_lt_set(L, R);
1433 case ICmpInst::ICMP_UGT:
1434 return isl_pw_aff_gt_set(L, R);
1435 case ICmpInst::ICMP_ULE:
1436 return isl_pw_aff_le_set(L, R);
1437 case ICmpInst::ICMP_UGE:
1438 return isl_pw_aff_ge_set(L, R);
1439 default:
1440 llvm_unreachable("Non integer predicate not supported");
1441 }
1442}
1443
Tobias Grosserc80d6972016-09-02 06:33:33 +00001444/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001445///
1446/// Helper function that will make sure the dimensions of the result have the
1447/// same isl_id's as the @p Domain.
1448static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1449 __isl_take isl_pw_aff *L,
1450 __isl_take isl_pw_aff *R,
1451 __isl_keep isl_set *Domain) {
1452 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1453 return setDimensionIds(Domain, ConsequenceCondSet);
1454}
1455
Michael Kruse476f8552017-06-29 12:47:41 +00001456/// Compute the isl representation for the SCEV @p E in this BB.
1457///
1458/// @param S The Scop in which @p BB resides in.
1459/// @param BB The BB for which isl representation is to be
1460/// computed.
1461/// @param InvalidDomainMap A map of BB to their invalid domains.
1462/// @param E The SCEV that should be translated.
1463/// @param NonNegative Flag to indicate the @p E has to be non-negative.
1464///
1465/// Note that this function will also adjust the invalid context accordingly.
1466
1467__isl_give isl_pw_aff *
1468getPwAff(Scop &S, BasicBlock *BB,
Tobias Grosser13acbb92017-07-15 09:01:31 +00001469 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, const SCEV *E,
1470 bool NonNegative = false) {
Michael Kruse476f8552017-06-29 12:47:41 +00001471 PWACtx PWAC = S.getPwAff(E, BB, NonNegative);
Tobias Grosser13acbb92017-07-15 09:01:31 +00001472 InvalidDomainMap[BB] = InvalidDomainMap[BB].unite(isl::manage(PWAC.second));
Michael Kruse476f8552017-06-29 12:47:41 +00001473 return PWAC.first;
1474}
1475
Tobias Grosserc80d6972016-09-02 06:33:33 +00001476/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001477///
1478/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001479/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1480/// have as many elements as @p SI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001481static bool
1482buildConditionSets(Scop &S, BasicBlock *BB, SwitchInst *SI, Loop *L,
1483 __isl_keep isl_set *Domain,
1484 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1485 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001486
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001487 Value *Condition = getConditionFromTerminator(SI);
1488 assert(Condition && "No condition for switch");
1489
1490 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001491 isl_pw_aff *LHS, *RHS;
Michael Kruse476f8552017-06-29 12:47:41 +00001492 LHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001493
1494 unsigned NumSuccessors = SI->getNumSuccessors();
1495 ConditionSets.resize(NumSuccessors);
1496 for (auto &Case : SI->cases()) {
1497 unsigned Idx = Case.getSuccessorIndex();
1498 ConstantInt *CaseValue = Case.getCaseValue();
1499
Michael Kruse476f8552017-06-29 12:47:41 +00001500 RHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001501 isl_set *CaseConditionSet =
1502 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1503 ConditionSets[Idx] = isl_set_coalesce(
1504 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1505 }
1506
1507 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1508 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1509 for (unsigned u = 2; u < NumSuccessors; u++)
1510 ConditionSetUnion =
1511 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1512 ConditionSets[0] = setDimensionIds(
1513 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1514
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001515 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001516
1517 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001518}
1519
Michael Kruse08655852017-07-20 12:37:02 +00001520/// Build condition sets for unsigned ICmpInst(s).
1521/// Special handling is required for unsigned operands to ensure that if
1522/// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst
1523/// it should wrap around.
1524///
1525/// @param IsStrictUpperBound holds information on the predicate relation
1526/// between TestVal and UpperBound, i.e,
1527/// TestVal < UpperBound OR TestVal <= UpperBound
1528static __isl_give isl_set *
1529buildUnsignedConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1530 __isl_keep isl_set *Domain, const SCEV *SCEV_TestVal,
1531 const SCEV *SCEV_UpperBound,
1532 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1533 bool IsStrictUpperBound) {
1534
1535 // Do not take NonNeg assumption on TestVal
1536 // as it might have MSB (Sign bit) set.
1537 isl_pw_aff *TestVal = getPwAff(S, BB, InvalidDomainMap, SCEV_TestVal, false);
1538 // Take NonNeg assumption on UpperBound.
1539 isl_pw_aff *UpperBound =
1540 getPwAff(S, BB, InvalidDomainMap, SCEV_UpperBound, true);
1541
1542 // 0 <= TestVal
1543 isl_set *First =
1544 isl_pw_aff_le_set(isl_pw_aff_zero_on_domain(isl_local_space_from_space(
1545 isl_pw_aff_get_domain_space(TestVal))),
1546 isl_pw_aff_copy(TestVal));
1547
1548 isl_set *Second;
1549 if (IsStrictUpperBound)
1550 // TestVal < UpperBound
1551 Second = isl_pw_aff_lt_set(TestVal, UpperBound);
1552 else
1553 // TestVal <= UpperBound
1554 Second = isl_pw_aff_le_set(TestVal, UpperBound);
1555
1556 isl_set *ConsequenceCondSet = isl_set_intersect(First, Second);
1557 ConsequenceCondSet = setDimensionIds(Domain, ConsequenceCondSet);
1558 return ConsequenceCondSet;
1559}
1560
Tobias Grosserc80d6972016-09-02 06:33:33 +00001561/// Build the conditions sets for the branch condition @p Condition in
1562/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001563///
1564/// This will fill @p ConditionSets with the conditions under which control
1565/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001566/// have as many elements as @p TI has successors. If @p TI is nullptr the
1567/// context under which @p Condition is true/false will be returned as the
1568/// new elements of @p ConditionSets.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001569static bool
1570buildConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1571 TerminatorInst *TI, Loop *L, __isl_keep isl_set *Domain,
1572 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1573 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001574
1575 isl_set *ConsequenceCondSet = nullptr;
1576 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1577 if (CCond->isZero())
1578 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1579 else
1580 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1581 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1582 auto Opcode = BinOp->getOpcode();
1583 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1584
Michael Kruse476f8552017-06-29 12:47:41 +00001585 bool Valid = buildConditionSets(S, BB, BinOp->getOperand(0), TI, L, Domain,
1586 InvalidDomainMap, ConditionSets) &&
1587 buildConditionSets(S, BB, BinOp->getOperand(1), TI, L, Domain,
1588 InvalidDomainMap, ConditionSets);
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001589 if (!Valid) {
1590 while (!ConditionSets.empty())
1591 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001592 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001593 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001594
1595 isl_set_free(ConditionSets.pop_back_val());
1596 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1597 isl_set_free(ConditionSets.pop_back_val());
1598 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1599
1600 if (Opcode == Instruction::And)
1601 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1602 else
1603 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1604 } else {
1605 auto *ICond = dyn_cast<ICmpInst>(Condition);
1606 assert(ICond &&
1607 "Condition of exiting branch was neither constant nor ICmp!");
1608
1609 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001610 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001611 // For unsigned comparisons we assumed the signed bit of neither operand
1612 // to be set. The comparison is equal to a signed comparison under this
1613 // assumption.
1614 bool NonNeg = ICond->isUnsigned();
Michael Kruse08655852017-07-20 12:37:02 +00001615 const SCEV *LeftOperand = SE.getSCEVAtScope(ICond->getOperand(0), L),
1616 *RightOperand = SE.getSCEVAtScope(ICond->getOperand(1), L);
1617
1618 switch (ICond->getPredicate()) {
1619 case ICmpInst::ICMP_ULT:
1620 ConsequenceCondSet =
1621 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1622 RightOperand, InvalidDomainMap, true);
1623 break;
1624 case ICmpInst::ICMP_ULE:
1625 ConsequenceCondSet =
1626 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1627 RightOperand, InvalidDomainMap, false);
1628 break;
1629 case ICmpInst::ICMP_UGT:
1630 ConsequenceCondSet =
1631 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1632 LeftOperand, InvalidDomainMap, true);
1633 break;
1634 case ICmpInst::ICMP_UGE:
1635 ConsequenceCondSet =
1636 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1637 LeftOperand, InvalidDomainMap, false);
1638 break;
1639 default:
1640 LHS = getPwAff(S, BB, InvalidDomainMap, LeftOperand, NonNeg);
1641 RHS = getPwAff(S, BB, InvalidDomainMap, RightOperand, NonNeg);
1642 ConsequenceCondSet =
1643 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1644 break;
1645 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001646 }
1647
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001648 // If no terminator was given we are only looking for parameter constraints
1649 // under which @p Condition is true/false.
1650 if (!TI)
1651 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001652 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001653 ConsequenceCondSet = isl_set_coalesce(
1654 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001655
Johannes Doerfertb2885792016-04-26 09:20:41 +00001656 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001657 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001658 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001659
Michael Krusef7a4a942016-05-02 12:25:36 +00001660 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001661 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1662 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001663 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001664 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001665 }
1666
Michael Krusef7a4a942016-05-02 12:25:36 +00001667 if (TooComplex) {
Eli Friedmane737fc12017-07-17 23:58:33 +00001668 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc(),
1669 TI ? TI->getParent() : nullptr /* BasicBlock */);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001670 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001671 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001672 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001673 }
1674
1675 ConditionSets.push_back(ConsequenceCondSet);
1676 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001677
1678 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001679}
1680
Tobias Grosserc80d6972016-09-02 06:33:33 +00001681/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001682///
1683/// This will fill @p ConditionSets with the conditions under which control
1684/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1685/// have as many elements as @p TI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001686static bool
1687buildConditionSets(Scop &S, BasicBlock *BB, TerminatorInst *TI, Loop *L,
1688 __isl_keep isl_set *Domain,
1689 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1690 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001691
1692 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Michael Kruse476f8552017-06-29 12:47:41 +00001693 return buildConditionSets(S, BB, SI, L, Domain, InvalidDomainMap,
1694 ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001695
1696 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1697
1698 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001699 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001700 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001701 }
1702
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001703 Value *Condition = getConditionFromTerminator(TI);
1704 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001705
Michael Kruse476f8552017-06-29 12:47:41 +00001706 return buildConditionSets(S, BB, Condition, TI, L, Domain, InvalidDomainMap,
1707 ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001708}
1709
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001710void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001711 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001712
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001713 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001714 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001715}
1716
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001717void ScopStmt::collectSurroundingLoops() {
1718 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1719 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1720 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1721 isl_id_free(DimId);
1722 }
1723}
1724
Michael Kruse55454072017-03-15 22:16:43 +00001725ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001726 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
Michael Kruse55454072017-03-15 22:16:43 +00001727 R(&R), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001728
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001729 BaseName = getIslCompatibleName(
1730 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001731}
1732
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001733ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop,
1734 std::vector<Instruction *> Instructions)
Johannes Doerferta3519512016-04-23 13:02:23 +00001735 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001736 R(nullptr), Build(nullptr), SurroundingLoop(SurroundingLoop),
1737 Instructions(Instructions) {
Tobias Grosser75805372011-04-29 06:27:02 +00001738
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001739 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), "",
1740 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001741}
1742
Roman Gareevb3224ad2016-09-14 06:26:09 +00001743ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1744 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1745 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1746 R(nullptr), Build(nullptr) {
1747 BaseName = getIslCompatibleName("CopyStmt_", "",
1748 std::to_string(parent.getCopyStmtsNum()));
1749 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1750 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1751 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1752 auto *Access =
1753 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1754 parent.addAccessFunction(Access);
1755 addAccess(Access);
1756 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1757 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1758 parent.addAccessFunction(Access);
1759 addAccess(Access);
1760}
1761
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001762void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001763 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001764
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001765 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001766 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001767 buildAccessRelations();
1768
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001769 if (DetectReductions)
1770 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001771}
1772
Tobias Grosserc80d6972016-09-02 06:33:33 +00001773/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001774///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001775/// Check if the stored value for @p StoreMA is a binary operator with one or
1776/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001777/// used only once (by @p StoreMA) and its load operands are also used only
1778/// once, we have found a possible reduction chain. It starts at an operand
1779/// load and includes the binary operator and @p StoreMA.
1780///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001781/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001782/// escape this block or into any other store except @p StoreMA.
1783void ScopStmt::collectCandiateReductionLoads(
1784 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1785 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1786 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001787 return;
1788
1789 // Skip if there is not one binary operator between the load and the store
1790 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001791 if (!BinOp)
1792 return;
1793
1794 // Skip if the binary operators has multiple uses
1795 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001796 return;
1797
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001798 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001799 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1800 return;
1801
Johannes Doerfert9890a052014-07-01 00:32:29 +00001802 // Skip if the binary operator is outside the current SCoP
1803 if (BinOp->getParent() != Store->getParent())
1804 return;
1805
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001806 // Skip if it is a multiplicative reduction and we disabled them
1807 if (DisableMultiplicativeReductions &&
1808 (BinOp->getOpcode() == Instruction::Mul ||
1809 BinOp->getOpcode() == Instruction::FMul))
1810 return;
1811
Johannes Doerferte58a0122014-06-27 20:31:28 +00001812 // Check the binary operator operands for a candidate load
1813 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1814 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1815 if (!PossibleLoad0 && !PossibleLoad1)
1816 return;
1817
1818 // A load is only a candidate if it cannot escape (thus has only this use)
1819 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001820 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001821 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001822 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001823 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001824 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001825}
1826
Tobias Grosserc80d6972016-09-02 06:33:33 +00001827/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001828///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001829/// Iterate over all store memory accesses and check for valid binary reduction
1830/// like chains. For all candidates we check if they have the same base address
1831/// and there are no other accesses which overlap with them. The base address
1832/// check rules out impossible reductions candidates early. The overlap check,
1833/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001834/// guarantees that none of the intermediate results will escape during
1835/// execution of the loop nest. We basically check here that no other memory
1836/// access can access the same memory as the potential reduction.
1837void ScopStmt::checkForReductions() {
1838 SmallVector<MemoryAccess *, 2> Loads;
1839 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1840
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001841 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001842 // stores and collecting possible reduction loads.
1843 for (MemoryAccess *StoreMA : MemAccs) {
1844 if (StoreMA->isRead())
1845 continue;
1846
1847 Loads.clear();
1848 collectCandiateReductionLoads(StoreMA, Loads);
1849 for (MemoryAccess *LoadMA : Loads)
1850 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1851 }
1852
1853 // Then check each possible candidate pair.
1854 for (const auto &CandidatePair : Candidates) {
1855 bool Valid = true;
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001856 isl_map *LoadAccs = CandidatePair.first->getAccessRelation().release();
1857 isl_map *StoreAccs = CandidatePair.second->getAccessRelation().release();
Johannes Doerferte58a0122014-06-27 20:31:28 +00001858
1859 // Skip those with obviously unequal base addresses.
1860 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1861 isl_map_free(LoadAccs);
1862 isl_map_free(StoreAccs);
1863 continue;
1864 }
1865
1866 // And check if the remaining for overlap with other memory accesses.
1867 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1868 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1869 isl_set *AllAccs = isl_map_range(AllAccsRel);
1870
1871 for (MemoryAccess *MA : MemAccs) {
1872 if (MA == CandidatePair.first || MA == CandidatePair.second)
1873 continue;
1874
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001875 isl_map *AccRel = isl_map_intersect_domain(
1876 MA->getAccessRelation().release(), getDomain());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001877 isl_set *Accs = isl_map_range(AccRel);
1878
Tobias Grosser55a7af72016-09-08 14:08:07 +00001879 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001880 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1881 Valid = Valid && isl_set_is_empty(OverlapAccs);
1882 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001883 } else {
1884 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001885 }
1886 }
1887
1888 isl_set_free(AllAccs);
1889 if (!Valid)
1890 continue;
1891
Johannes Doerfertf6183392014-07-01 20:52:51 +00001892 const LoadInst *Load =
1893 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1894 MemoryAccess::ReductionType RT =
1895 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1896
Johannes Doerferte58a0122014-06-27 20:31:28 +00001897 // If no overlapping access was found we mark the load and store as
1898 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001899 CandidatePair.first->markAsReductionLike(RT);
1900 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001901 }
Tobias Grosser75805372011-04-29 06:27:02 +00001902}
1903
Tobias Grosser74394f02013-01-14 22:40:23 +00001904std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001905
Tobias Grosser54839312015-04-21 11:37:25 +00001906std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001907 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001908 if (!S)
1909 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001910 auto Str = stringFromIslObj(S);
1911 isl_map_free(S);
1912 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001913}
1914
Johannes Doerferta3519512016-04-23 13:02:23 +00001915void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1916 isl_set_free(InvalidDomain);
1917 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001918}
1919
Michael Kruse375cb5f2016-02-24 22:08:24 +00001920BasicBlock *ScopStmt::getEntryBlock() const {
1921 if (isBlockStmt())
1922 return getBasicBlock();
1923 return getRegion()->getEntry();
1924}
1925
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001926unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001927
Tobias Grosser75805372011-04-29 06:27:02 +00001928const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1929
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001930Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001931 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001932}
1933
Tobias Grosser74394f02013-01-14 22:40:23 +00001934isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001935
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001936__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001937
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001938__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001939 return isl_set_get_space(Domain);
1940}
1941
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001942__isl_give isl_id *ScopStmt::getDomainId() const {
1943 return isl_set_get_tuple_id(Domain);
1944}
Tobias Grossercd95b772012-08-30 11:49:38 +00001945
Johannes Doerfert7c013572016-04-12 09:57:34 +00001946ScopStmt::~ScopStmt() {
1947 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001948 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001949}
Tobias Grosser75805372011-04-29 06:27:02 +00001950
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001951void ScopStmt::printInstructions(raw_ostream &OS) const {
1952 OS << "Instructions {\n";
1953
1954 for (Instruction *Inst : Instructions)
1955 OS.indent(16) << *Inst << "\n";
1956
Michael Krusee52ebd12017-07-22 16:44:39 +00001957 OS.indent(12) << "}\n";
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001958}
1959
Michael Krusecd4c9772017-07-21 15:35:53 +00001960void ScopStmt::print(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00001961 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001962 OS.indent(12) << "Domain :=\n";
1963
1964 if (Domain) {
1965 OS.indent(16) << getDomainStr() << ";\n";
1966 } else
1967 OS.indent(16) << "n/a\n";
1968
Tobias Grosser54839312015-04-21 11:37:25 +00001969 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001970
1971 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001972 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001973 } else
1974 OS.indent(16) << "n/a\n";
1975
Tobias Grosser083d3d32014-06-28 08:59:45 +00001976 for (MemoryAccess *Access : MemAccs)
1977 Access->print(OS);
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001978
Michael Krusecd4c9772017-07-21 15:35:53 +00001979 if (PrintInstructions)
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001980 printInstructions(OS.indent(12));
Tobias Grosser75805372011-04-29 06:27:02 +00001981}
1982
Michael Kruse5d518462017-07-21 15:54:07 +00001983#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001984LLVM_DUMP_METHOD void ScopStmt::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00001985#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001986
Michael Krusee60eca72017-05-11 22:56:12 +00001987void ScopStmt::removeAccessData(MemoryAccess *MA) {
1988 if (MA->isRead() && MA->isOriginalValueKind()) {
1989 bool Found = ValueReads.erase(MA->getAccessValue());
1990 (void)Found;
1991 assert(Found && "Expected access data not found");
1992 }
1993 if (MA->isWrite() && MA->isOriginalValueKind()) {
1994 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1995 (void)Found;
1996 assert(Found && "Expected access data not found");
1997 }
1998 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1999 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
2000 (void)Found;
2001 assert(Found && "Expected access data not found");
2002 }
Michael Kruse3562f272017-07-20 16:47:57 +00002003 if (MA->isRead() && MA->isOriginalAnyPHIKind()) {
2004 bool Found = PHIReads.erase(cast<PHINode>(MA->getAccessInstruction()));
2005 (void)Found;
2006 assert(Found && "Expected access data not found");
2007 }
Michael Krusee60eca72017-05-11 22:56:12 +00002008}
2009
Michael Kruse10071822016-05-23 14:45:58 +00002010void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00002011 // Remove the memory accesses from this statement together with all scalar
2012 // accesses that were caused by it. MemoryKind::Value READs have no access
2013 // instruction, hence would not be removed by this function. However, it is
2014 // only used for invariant LoadInst accesses, its arguments are always affine,
2015 // hence synthesizable, and therefore there are no MemoryKind::Value READ
2016 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00002017 auto Predicate = [&](MemoryAccess *Acc) {
2018 return Acc->getAccessInstruction() == MA->getAccessInstruction();
2019 };
Michael Krusee60eca72017-05-11 22:56:12 +00002020 for (auto *MA : MemAccs) {
Michael Kruse8b805802017-07-19 17:11:25 +00002021 if (Predicate(MA)) {
Michael Krusee60eca72017-05-11 22:56:12 +00002022 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00002023 Parent.removeAccessData(MA);
2024 }
Michael Krusee60eca72017-05-11 22:56:12 +00002025 }
Michael Kruse10071822016-05-23 14:45:58 +00002026 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
2027 MemAccs.end());
2028 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002029}
2030
Michael Kruse0446d812017-03-10 16:05:24 +00002031void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
2032 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
2033 assert(MAIt != MemAccs.end());
2034 MemAccs.erase(MAIt);
2035
Michael Krusee60eca72017-05-11 22:56:12 +00002036 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00002037 Parent.removeAccessData(MA);
Michael Krusee60eca72017-05-11 22:56:12 +00002038
Michael Kruse0446d812017-03-10 16:05:24 +00002039 auto It = InstructionToAccess.find(MA->getAccessInstruction());
2040 if (It != InstructionToAccess.end()) {
2041 It->second.remove(MA);
2042 if (It->second.empty())
2043 InstructionToAccess.erase(MA->getAccessInstruction());
2044 }
2045}
2046
Michael Krusecd4c9772017-07-21 15:35:53 +00002047raw_ostream &polly::operator<<(raw_ostream &O, const ScopStmt &S) {
2048 S.print(O, PollyPrintInstructions);
2049 return O;
2050}
2051
Tobias Grosser75805372011-04-29 06:27:02 +00002052//===----------------------------------------------------------------------===//
2053/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00002054
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00002055void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00002056 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
2057 isl_set_free(Context);
2058 Context = NewContext;
2059}
2060
Eli Friedman5e589ea2017-06-20 22:53:02 +00002061namespace {
Tobias Grosserc80d6972016-09-02 06:33:33 +00002062/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002063struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00002064 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002065 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002066
2067public:
2068 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00002069 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002070
2071 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
2072 ValueToValueMap &VMap) {
2073 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
2074 return SSPR.visit(E);
2075 }
2076
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002077 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
2078 auto *Start = visit(E->getStart());
2079 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
2080 visit(E->getStepRecurrence(SE)),
2081 E->getLoop(), SCEV::FlagAnyWrap);
2082 return SE.getAddExpr(Start, AddRec);
2083 }
2084
2085 const SCEV *visitUnknown(const SCEVUnknown *E) {
2086 if (auto *NewValue = VMap.lookup(E->getValue()))
2087 return SE.getUnknown(NewValue);
2088 return E;
2089 }
2090};
2091
Eli Friedman5e589ea2017-06-20 22:53:02 +00002092/// Check whether we should remap a SCEV expression.
2093struct SCEVFindInsideScop : public SCEVTraversal<SCEVFindInsideScop> {
2094 ValueToValueMap &VMap;
2095 bool FoundInside = false;
2096 Scop *S;
2097
2098public:
2099 SCEVFindInsideScop(ValueToValueMap &VMap, ScalarEvolution &SE, Scop *S)
2100 : SCEVTraversal(*this), VMap(VMap), S(S) {}
2101
2102 static bool hasVariant(const SCEV *E, ScalarEvolution &SE,
2103 ValueToValueMap &VMap, Scop *S) {
2104 SCEVFindInsideScop SFIS(VMap, SE, S);
2105 SFIS.visitAll(E);
2106 return SFIS.FoundInside;
2107 }
2108
2109 bool follow(const SCEV *E) {
2110 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(E)) {
2111 FoundInside |= S->getRegion().contains(AddRec->getLoop());
2112 } else if (auto *Unknown = dyn_cast<SCEVUnknown>(E)) {
2113 if (Instruction *I = dyn_cast<Instruction>(Unknown->getValue()))
2114 FoundInside |= S->getRegion().contains(I) && !VMap.count(I);
2115 }
2116 return !FoundInside;
2117 }
2118 bool isDone() { return FoundInside; }
2119};
2120} // namespace
2121
2122const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *E) {
2123 // Check whether it makes sense to rewrite the SCEV. (ScalarEvolution
2124 // doesn't like addition between an AddRec and an expression that
2125 // doesn't have a dominance relationship with it.)
2126 if (SCEVFindInsideScop::hasVariant(E, *SE, InvEquivClassVMap, this))
2127 return E;
2128
2129 // Rewrite SCEV.
2130 return SCEVSensitiveParameterRewriter::rewrite(E, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002131}
2132
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002133// This table of function names is used to translate parameter names in more
2134// human-readable names. This makes it easier to interpret Polly analysis
2135// results.
2136StringMap<std::string> KnownNames = {
2137 {"_Z13get_global_idj", "global_id"},
2138 {"_Z12get_local_idj", "local_id"},
2139 {"_Z15get_global_sizej", "global_size"},
2140 {"_Z14get_local_sizej", "local_size"},
2141 {"_Z12get_work_dimv", "work_dim"},
2142 {"_Z17get_global_offsetj", "global_offset"},
2143 {"_Z12get_group_idj", "group_id"},
2144 {"_Z14get_num_groupsj", "num_groups"},
2145};
2146
2147static std::string getCallParamName(CallInst *Call) {
2148 std::string Result;
2149 raw_string_ostream OS(Result);
2150 std::string Name = Call->getCalledFunction()->getName();
2151
2152 auto Iterator = KnownNames.find(Name);
2153 if (Iterator != KnownNames.end())
Tobias Grosserdff902f2017-06-01 12:46:51 +00002154 Name = "__" + Iterator->getValue();
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002155 OS << Name;
2156 for (auto &Operand : Call->arg_operands()) {
2157 ConstantInt *Op = cast<ConstantInt>(&Operand);
2158 OS << "_" << Op->getValue();
2159 }
2160 OS.flush();
2161 return Result;
2162}
2163
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002164void Scop::createParameterId(const SCEV *Parameter) {
2165 assert(Parameters.count(Parameter));
2166 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002167
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002168 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002169
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002170 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
2171 Value *Val = ValueParameter->getValue();
2172 CallInst *Call = dyn_cast<CallInst>(Val);
Tobias Grosser8f99c162011-11-15 11:38:55 +00002173
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002174 if (Call && isConstCall(Call)) {
2175 ParameterName = getCallParamName(Call);
2176 } else if (UseInstructionNames) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002177 // If this parameter references a specific Value and this value has a name
2178 // we use this name as it is likely to be unique and more useful than just
2179 // a number.
2180 if (Val->hasName())
2181 ParameterName = Val->getName();
2182 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
2183 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
2184 if (LoadOrigin->hasName()) {
2185 ParameterName += "_loaded_from_";
2186 ParameterName +=
2187 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
2188 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002189 }
2190 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00002191
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002192 ParameterName = getIslCompatibleName("", ParameterName, "");
2193 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00002194
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002195 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
2196 const_cast<void *>((const void *)Parameter));
2197 ParameterIds[Parameter] = Id;
2198}
2199
2200void Scop::addParams(const ParameterSetTy &NewParameters) {
2201 for (const SCEV *Parameter : NewParameters) {
2202 // Normalize the SCEV to get the representing element for an invariant load.
2203 Parameter = extractConstantFactor(Parameter, *SE).second;
2204 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2205
2206 if (Parameters.insert(Parameter))
2207 createParameterId(Parameter);
2208 }
2209}
2210
2211__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
2212 // Normalize the SCEV to get the representing element for an invariant load.
2213 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2214 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00002215}
Tobias Grosser75805372011-04-29 06:27:02 +00002216
Michael Krused56b90a2016-09-01 09:03:27 +00002217__isl_give isl_set *
2218Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002219 isl_set *DomainContext = isl_union_set_params(getDomains());
2220 return isl_set_intersect_params(C, DomainContext);
2221}
2222
Johannes Doerferte0b08072016-05-23 12:43:44 +00002223bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2224 return DT.dominates(BB, getEntry());
2225}
2226
Michael Kruse476f8552017-06-29 12:47:41 +00002227void Scop::addUserAssumptions(
2228 AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002229 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse89b1f942017-03-17 13:56:53 +00002230 for (auto &Assumption : AC.assumptions()) {
2231 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2232 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002233 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002234
Michael Kruse89b1f942017-03-17 13:56:53 +00002235 bool InScop = contains(CI);
2236 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2237 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002238
Michael Kruse89b1f942017-03-17 13:56:53 +00002239 auto *L = LI.getLoopFor(CI->getParent());
2240 auto *Val = CI->getArgOperand(0);
2241 ParameterSetTy DetectedParams;
2242 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00002243 ORE.emit(
2244 OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreUserAssumption", CI)
2245 << "Non-affine user assumption ignored.");
Michael Kruse89b1f942017-03-17 13:56:53 +00002246 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002247 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002248
2249 // Collect all newly introduced parameters.
2250 ParameterSetTy NewParams;
2251 for (auto *Param : DetectedParams) {
2252 Param = extractConstantFactor(Param, *SE).second;
2253 Param = getRepresentingInvariantLoadSCEV(Param);
2254 if (Parameters.count(Param))
2255 continue;
2256 NewParams.insert(Param);
2257 }
2258
2259 SmallVector<isl_set *, 2> ConditionSets;
2260 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
2261 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
2262 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
Michael Kruse476f8552017-06-29 12:47:41 +00002263 bool Valid = buildConditionSets(*this, Stmt.getEntryBlock(), Val, TI, L,
2264 Dom, InvalidDomainMap, ConditionSets);
Michael Kruse89b1f942017-03-17 13:56:53 +00002265 isl_set_free(Dom);
2266
2267 if (!Valid)
2268 continue;
2269
2270 isl_set *AssumptionCtx = nullptr;
2271 if (InScop) {
2272 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2273 isl_set_free(ConditionSets[0]);
2274 } else {
2275 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2276 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2277 }
2278
2279 // Project out newly introduced parameters as they are not otherwise useful.
2280 if (!NewParams.empty()) {
2281 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2282 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2283 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2284 isl_id_free(Id);
2285
2286 if (!NewParams.count(Param))
2287 continue;
2288
2289 AssumptionCtx =
2290 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2291 }
2292 }
Eli Friedmane737fc12017-07-17 23:58:33 +00002293 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "UserAssumption", CI)
2294 << "Use user assumption: " << stringFromIslObj(AssumptionCtx));
Michael Kruse89b1f942017-03-17 13:56:53 +00002295 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002296 }
2297}
2298
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002299void Scop::addUserContext() {
2300 if (UserContextStr.empty())
2301 return;
2302
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002303 isl_set *UserContext =
2304 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002305 isl_space *Space = getParamSpace();
2306 if (isl_space_dim(Space, isl_dim_param) !=
2307 isl_set_dim(UserContext, isl_dim_param)) {
2308 auto SpaceStr = isl_space_to_str(Space);
2309 errs() << "Error: the context provided in -polly-context has not the same "
2310 << "number of dimensions than the computed context. Due to this "
2311 << "mismatch, the -polly-context option is ignored. Please provide "
2312 << "the context in the parameter space: " << SpaceStr << ".\n";
2313 free(SpaceStr);
2314 isl_set_free(UserContext);
2315 isl_space_free(Space);
2316 return;
2317 }
2318
2319 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002320 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2321 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002322
2323 if (strcmp(NameContext, NameUserContext) != 0) {
2324 auto SpaceStr = isl_space_to_str(Space);
2325 errs() << "Error: the name of dimension " << i
2326 << " provided in -polly-context "
2327 << "is '" << NameUserContext << "', but the name in the computed "
2328 << "context is '" << NameContext
2329 << "'. Due to this name mismatch, "
2330 << "the -polly-context option is ignored. Please provide "
2331 << "the context in the parameter space: " << SpaceStr << ".\n";
2332 free(SpaceStr);
2333 isl_set_free(UserContext);
2334 isl_space_free(Space);
2335 return;
2336 }
2337
2338 UserContext =
2339 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2340 isl_space_get_dim_id(Space, isl_dim_param, i));
2341 }
2342
2343 Context = isl_set_intersect(Context, UserContext);
2344 isl_space_free(Space);
2345}
2346
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002347void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002348 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002349
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002350 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002351 for (LoadInst *LInst : RIL) {
2352 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2353
Johannes Doerfert96e54712016-02-07 17:30:13 +00002354 Type *Ty = LInst->getType();
2355 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002356 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002357 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002358 continue;
2359 }
2360
2361 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002362 InvariantEquivClasses.emplace_back(
2363 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002364 }
2365}
2366
Tobias Grosser6be480c2011-11-08 15:41:13 +00002367void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002368 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002369 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002370 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002371 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002372}
2373
Tobias Grosser18daaca2012-05-22 10:47:27 +00002374void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002375 unsigned PDim = 0;
2376 for (auto *Parameter : Parameters) {
2377 ConstantRange SRange = SE->getSignedRange(Parameter);
Tobias Grosser99ea1d02017-05-21 20:23:20 +00002378 Context =
2379 addRangeBoundsToSet(give(Context), SRange, PDim++, isl::dim::param)
2380 .release();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002381 }
2382}
2383
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002384// We use the outermost dimension to generate GPU transfers for Fortran arrays
2385// even when the array bounds are not known statically. To do so, we need the
2386// outermost dimension information. We add this into the context so that the
2387// outermost dimension is available during codegen.
2388// We currently do not care about dimensions other than the outermost
2389// dimension since it doesn't affect transfers.
2390static isl_set *addFortranArrayOutermostDimParams(__isl_give isl_set *Context,
2391 Scop::array_range Arrays) {
2392
2393 std::vector<isl_id *> OutermostSizeIds;
2394 for (auto Array : Arrays) {
2395 // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2396 // for its outermost dimension. Fortran arrays will have this since the
2397 // outermost dimension size can be picked up from their runtime description.
2398 // TODO: actually need to check if it has a FAD, but for now this works.
2399 if (Array->getNumberOfDimensions() > 0) {
Tobias Grosser77eef902017-07-21 23:07:56 +00002400 isl_pw_aff *PwAff = Array->getDimensionSizePw(0).release();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002401 if (!PwAff)
2402 continue;
2403
2404 isl_id *Id = isl_pw_aff_get_dim_id(PwAff, isl_dim_param, 0);
2405 isl_pw_aff_free(PwAff);
2406 assert(Id && "Invalid Id for PwAff expression in Fortran array");
2407 OutermostSizeIds.push_back(Id);
2408 }
2409 }
2410
2411 const int NumTrueParams = isl_set_dim(Context, isl_dim_param);
2412 Context = isl_set_add_dims(Context, isl_dim_param, OutermostSizeIds.size());
2413
2414 for (size_t i = 0; i < OutermostSizeIds.size(); i++) {
2415 Context = isl_set_set_dim_id(Context, isl_dim_param, NumTrueParams + i,
2416 OutermostSizeIds[i]);
2417 Context =
2418 isl_set_lower_bound_si(Context, isl_dim_param, NumTrueParams + i, 0);
2419 }
2420
2421 return Context;
2422}
2423
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002424void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002425 if (PollyIgnoreParamBounds)
2426 return;
2427
Tobias Grosser6be480c2011-11-08 15:41:13 +00002428 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002429 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002430
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002431 unsigned PDim = 0;
2432 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002433 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002434 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002435 }
2436
2437 // Align the parameters of all data structures to the model.
2438 Context = isl_set_align_params(Context, Space);
2439
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002440 // Add the outermost dimension of the Fortran arrays into the Context.
2441 // See the description of the function for more information.
2442 Context = addFortranArrayOutermostDimParams(Context, arrays());
2443
Johannes Doerferta60ad842016-05-10 12:18:22 +00002444 // As all parameters are known add bounds to them.
2445 addParameterBounds();
2446
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002447 for (ScopStmt &Stmt : *this)
2448 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002449 // Simplify the schedule according to the context too.
2450 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002451}
2452
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002453static __isl_give isl_set *
2454simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2455 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002456 // If we have modeled all blocks in the SCoP that have side effects we can
2457 // simplify the context with the constraints that are needed for anything to
2458 // be executed at all. However, if we have error blocks in the SCoP we already
2459 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002460 // domains, thus we cannot use the remaining domain to simplify the
2461 // assumptions.
2462 if (!S.hasErrorBlock()) {
2463 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2464 AssumptionContext =
2465 isl_set_gist_params(AssumptionContext, DomainParameters);
2466 }
2467
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002468 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2469 return AssumptionContext;
2470}
2471
2472void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002473 // The parameter constraints of the iteration domains give us a set of
2474 // constraints that need to hold for all cases where at least a single
2475 // statement iteration is executed in the whole scop. We now simplify the
2476 // assumed context under the assumption that such constraints hold and at
2477 // least a single statement iteration is executed. For cases where no
2478 // statement instances are executed, the assumptions we have taken about
2479 // the executed code do not matter and can be changed.
2480 //
2481 // WARNING: This only holds if the assumptions we have taken do not reduce
2482 // the set of statement instances that are executed. Otherwise we
2483 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002484 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002485 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002486 // performed. In such a case, modifying the run-time conditions and
2487 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002488 // to not be executed.
2489 //
2490 // Example:
2491 //
2492 // When delinearizing the following code:
2493 //
2494 // for (long i = 0; i < 100; i++)
2495 // for (long j = 0; j < m; j++)
2496 // A[i+p][j] = 1.0;
2497 //
2498 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002499 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002500 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002501 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002502 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002503}
2504
Tobias Grosserc80d6972016-09-02 06:33:33 +00002505/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002506static isl::stat
2507buildMinMaxAccess(isl::set Set, Scop::MinMaxVectorTy &MinMaxAccesses, Scop &S) {
2508 isl::pw_multi_aff MinPMA, MaxPMA;
2509 isl::pw_aff LastDimAff;
2510 isl::aff OneAff;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002511 unsigned Pos;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002512 isl::ctx Ctx = Set.get_ctx();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002513
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002514 Set = Set.remove_divs();
Johannes Doerfert6296d952016-04-22 11:38:19 +00002515
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002516 if (isl_set_n_basic_set(Set.get()) >= MaxDisjunctsInDomain)
2517 return isl::stat::error;
Johannes Doerfert6296d952016-04-22 11:38:19 +00002518
Johannes Doerfert9143d672014-09-27 11:02:39 +00002519 // Restrict the number of parameters involved in the access as the lexmin/
2520 // lexmax computation will take too long if this number is high.
2521 //
2522 // Experiments with a simple test case using an i7 4800MQ:
2523 //
2524 // #Parameters involved | Time (in sec)
2525 // 6 | 0.01
2526 // 7 | 0.04
2527 // 8 | 0.12
2528 // 9 | 0.40
2529 // 10 | 1.54
2530 // 11 | 6.78
2531 // 12 | 30.38
2532 //
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002533 if (isl_set_n_param(Set.get()) > RunTimeChecksMaxParameters) {
Johannes Doerfert9143d672014-09-27 11:02:39 +00002534 unsigned InvolvedParams = 0;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002535 for (unsigned u = 0, e = isl_set_n_param(Set.get()); u < e; u++)
2536 if (Set.involves_dims(isl::dim::param, u, 1))
Johannes Doerfert9143d672014-09-27 11:02:39 +00002537 InvolvedParams++;
2538
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002539 if (InvolvedParams > RunTimeChecksMaxParameters)
2540 return isl::stat::error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002541 }
2542
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +00002543 if (isl_set_n_basic_set(Set.get()) > RunTimeChecksMaxAccessDisjuncts)
2544 return isl::stat::error;
2545
Tobias Grosser57a1d362017-06-23 08:05:27 +00002546 MinPMA = Set.lexmin_pw_multi_aff();
2547 MaxPMA = Set.lexmax_pw_multi_aff();
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002548
Tobias Grosser57a1d362017-06-23 08:05:27 +00002549 if (isl_ctx_last_error(Ctx.get()) == isl_error_quota)
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002550 return isl::stat::error;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002551
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002552 MinPMA = MinPMA.coalesce();
2553 MaxPMA = MaxPMA.coalesce();
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002554
Johannes Doerfertb164c792014-09-18 11:17:17 +00002555 // Adjust the last dimension of the maximal access by one as we want to
2556 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2557 // we test during code generation might now point after the end of the
2558 // allocated array but we will never dereference it anyway.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002559 assert(MaxPMA.dim(isl::dim::out) && "Assumed at least one output dimension");
2560 Pos = MaxPMA.dim(isl::dim::out) - 1;
2561 LastDimAff = MaxPMA.get_pw_aff(Pos);
2562 OneAff = isl::aff(isl::local_space(LastDimAff.get_domain_space()));
2563 OneAff = OneAff.add_constant_si(1);
2564 LastDimAff = LastDimAff.add(OneAff);
2565 MaxPMA = MaxPMA.set_pw_aff(Pos, LastDimAff);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002566
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002567 MinMaxAccesses.push_back(std::make_pair(MinPMA.copy(), MaxPMA.copy()));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002568
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002569 return isl::stat::ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002570}
2571
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002572static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2573 isl_set *Domain = MA->getStatement()->getDomain();
2574 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2575 return isl_set_reset_tuple_id(Domain);
2576}
2577
Tobias Grosserc80d6972016-09-02 06:33:33 +00002578/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002579static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002580 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002581
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002582 MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002583
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002584 isl::union_set Domains = give(S.getDomains());
2585 isl::union_map Accesses = isl::union_map::empty(give(S.getParamSpace()));
Tobias Grossere9522232017-01-16 15:49:04 +00002586
2587 for (MemoryAccess *MA : AliasGroup)
Tobias Grosser1515f6b2017-07-23 04:08:38 +00002588 Accesses = Accesses.add_map(give(MA->getAccessRelation().release()));
Tobias Grossere9522232017-01-16 15:49:04 +00002589
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002590 Accesses = Accesses.intersect_domain(Domains);
2591 isl::union_set Locations = Accesses.range();
2592 Locations = Locations.coalesce();
2593 Locations = Locations.detect_equalities();
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002594
2595 auto Lambda = [&MinMaxAccesses, &S](isl::set Set) -> isl::stat {
2596 return buildMinMaxAccess(Set, MinMaxAccesses, S);
2597 };
2598 return Locations.foreach_set(Lambda) == isl::stat::ok;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002599}
2600
Tobias Grosserc80d6972016-09-02 06:33:33 +00002601/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002602///
2603///{
2604
Tobias Grosserc80d6972016-09-02 06:33:33 +00002605/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002606static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2607 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2608 : RN->getNodeAs<BasicBlock>();
2609}
2610
Tobias Grosserc80d6972016-09-02 06:33:33 +00002611/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002612static inline BasicBlock *
2613getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002614 if (RN->isSubRegion()) {
2615 assert(idx == 0);
2616 return RN->getNodeAs<Region>()->getExit();
2617 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002618 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002619}
2620
Tobias Grosserc80d6972016-09-02 06:33:33 +00002621/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002622static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002623 if (!RN->isSubRegion()) {
2624 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2625 Loop *L = LI.getLoopFor(BB);
2626
2627 // Unreachable statements are not considered to belong to a LLVM loop, as
2628 // they are not part of an actual loop in the control flow graph.
2629 // Nevertheless, we handle certain unreachable statements that are common
2630 // when modeling run-time bounds checks as being part of the loop to be
2631 // able to model them and to later eliminate the run-time bounds checks.
2632 //
2633 // Specifically, for basic blocks that terminate in an unreachable and
Michael Krusea6d48f52017-06-08 12:06:15 +00002634 // where the immediate predecessor is part of a loop, we assume these
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002635 // basic blocks belong to the loop the predecessor belongs to. This
2636 // allows us to model the following code.
2637 //
2638 // for (i = 0; i < N; i++) {
2639 // if (i > 1024)
2640 // abort(); <- this abort might be translated to an
2641 // unreachable
2642 //
2643 // A[i] = ...
2644 // }
2645 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2646 L = LI.getLoopFor(BB->getPrevNode());
2647 return L;
2648 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002649
2650 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2651 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2652 while (L && NonAffineSubRegion->contains(L))
2653 L = L->getParentLoop();
2654 return L;
2655}
2656
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002657/// Get the number of blocks in @p L.
2658///
2659/// The number of blocks in a loop are the number of basic blocks actually
2660/// belonging to the loop, as well as all single basic blocks that the loop
2661/// exits to and which terminate in an unreachable instruction. We do not
2662/// allow such basic blocks in the exit of a scop, hence they belong to the
2663/// scop and represent run-time conditions which we want to model and
2664/// subsequently speculate away.
2665///
2666/// @see getRegionNodeLoop for additional details.
Reid Klecknerdf2b2832017-06-19 17:44:02 +00002667unsigned getNumBlocksInLoop(Loop *L) {
2668 unsigned NumBlocks = L->getNumBlocks();
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002669 SmallVector<llvm::BasicBlock *, 4> ExitBlocks;
2670 L->getExitBlocks(ExitBlocks);
2671
2672 for (auto ExitBlock : ExitBlocks) {
2673 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2674 NumBlocks++;
2675 }
2676 return NumBlocks;
2677}
2678
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002679static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2680 if (!RN->isSubRegion())
2681 return 1;
2682
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002683 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002684 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002685}
2686
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002687static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2688 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002689 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002690 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002691 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002692 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002693 return true;
2694 return false;
2695}
2696
Johannes Doerfert96425c22015-08-30 21:13:53 +00002697///}
2698
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002699static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2700 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002701 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002702 isl_id *DimId =
2703 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2704 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2705}
2706
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002707__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002708 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002709}
2710
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002711__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002712 auto DIt = DomainMap.find(BB);
2713 if (DIt != DomainMap.end())
Tobias Grosser325204a32017-07-15 12:41:32 +00002714 return DIt->getSecond().copy();
Johannes Doerfert41cda152016-04-08 10:32:26 +00002715
2716 auto &RI = *R.getRegionInfo();
2717 auto *BBR = RI.getRegionFor(BB);
2718 while (BBR->getEntry() == BB)
2719 BBR = BBR->getParent();
2720 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002721}
2722
Tobias Grosser13acbb92017-07-15 09:01:31 +00002723bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI,
2724 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002725
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002726 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002727 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002728 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2729 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002730 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002731
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002732 while (LD-- >= 0) {
2733 S = addDomainDimId(S, LD + 1, L);
2734 L = L->getParentLoop();
2735 }
2736
Tobias Grosser13acbb92017-07-15 09:01:31 +00002737 InvalidDomainMap[EntryBB] = isl::manage(isl_set_empty(isl_set_get_space(S)));
Tobias Grosser325204a32017-07-15 12:41:32 +00002738 DomainMap[EntryBB] = isl::manage(S);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002739
Johannes Doerfert432658d2016-01-26 11:01:41 +00002740 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002741 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002742
Michael Kruse476f8552017-06-29 12:47:41 +00002743 if (!buildDomainsWithBranchConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002744 return false;
2745
Michael Kruse476f8552017-06-29 12:47:41 +00002746 if (!propagateDomainConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002747 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002748
2749 // Error blocks and blocks dominated by them have been assumed to never be
2750 // executed. Representing them in the Scop does not add any value. In fact,
2751 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002752 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002753 // will cause problems when building up a ScopStmt for them.
2754 // Furthermore, basic blocks dominated by error blocks may reference
2755 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002756 // can themselves not be constructed properly. To this end we will replace
2757 // the domains of error blocks and those only reachable via error blocks
2758 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002759 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002760 // InvalidDomain. This information is needed during load hoisting.
Michael Kruse476f8552017-06-29 12:47:41 +00002761 if (!propagateInvalidStmtDomains(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002762 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002763
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002764 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002765}
2766
Tobias Grosserc80d6972016-09-02 06:33:33 +00002767/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002768/// to be compatible to domains constructed for loop @p NewL.
2769///
2770/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2771/// edge from @p OldL to @p NewL.
2772static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2773 __isl_take isl_set *Dom,
2774 Loop *OldL, Loop *NewL) {
2775
2776 // If the loops are the same there is nothing to do.
2777 if (NewL == OldL)
2778 return Dom;
2779
2780 int OldDepth = S.getRelativeLoopDepth(OldL);
2781 int NewDepth = S.getRelativeLoopDepth(NewL);
2782 // If both loops are non-affine loops there is nothing to do.
2783 if (OldDepth == -1 && NewDepth == -1)
2784 return Dom;
2785
2786 // Distinguish three cases:
2787 // 1) The depth is the same but the loops are not.
2788 // => One loop was left one was entered.
2789 // 2) The depth increased from OldL to NewL.
2790 // => One loop was entered, none was left.
2791 // 3) The depth decreased from OldL to NewL.
2792 // => Loops were left were difference of the depths defines how many.
2793 if (OldDepth == NewDepth) {
2794 assert(OldL->getParentLoop() == NewL->getParentLoop());
2795 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2796 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2797 Dom = addDomainDimId(Dom, NewDepth, NewL);
2798 } else if (OldDepth < NewDepth) {
2799 assert(OldDepth + 1 == NewDepth);
2800 auto &R = S.getRegion();
2801 (void)R;
2802 assert(NewL->getParentLoop() == OldL ||
2803 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2804 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2805 Dom = addDomainDimId(Dom, NewDepth, NewL);
2806 } else {
2807 assert(OldDepth > NewDepth);
2808 int Diff = OldDepth - NewDepth;
2809 int NumDim = isl_set_n_dim(Dom);
2810 assert(NumDim >= Diff);
2811 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2812 }
2813
2814 return Dom;
2815}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002816
Michael Kruse476f8552017-06-29 12:47:41 +00002817bool Scop::propagateInvalidStmtDomains(
2818 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002819 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse476f8552017-06-29 12:47:41 +00002820
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002821 ReversePostOrderTraversal<Region *> RTraversal(R);
2822 for (auto *RN : RTraversal) {
2823
2824 // Recurse for affine subregions but go on for basic blocks and non-affine
2825 // subregions.
2826 if (RN->isSubRegion()) {
2827 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002828 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002829 propagateInvalidStmtDomains(SubRegion, DT, LI, InvalidDomainMap);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002830 continue;
2831 }
2832 }
2833
2834 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2835 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00002836 isl::set &Domain = DomainMap[BB];
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002837 assert(Domain && "Cannot propagate a nullptr");
2838
Tobias Grosser325204a32017-07-15 12:41:32 +00002839 isl::set InvalidDomain = InvalidDomainMap[BB];
Michael Kruse476f8552017-06-29 12:47:41 +00002840
Tobias Grosser325204a32017-07-15 12:41:32 +00002841 bool IsInvalidBlock = ContainsErrorBlock || Domain.is_subset(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002842
Johannes Doerferta3519512016-04-23 13:02:23 +00002843 if (!IsInvalidBlock) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002844 InvalidDomain = InvalidDomain.intersect(Domain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002845 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002846 InvalidDomain = Domain;
Tobias Grosser325204a32017-07-15 12:41:32 +00002847 isl::set DomPar = Domain.params();
2848 recordAssumption(ERRORBLOCK, DomPar.release(),
2849 BB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002850 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002851 }
2852
Tobias Grosser325204a32017-07-15 12:41:32 +00002853 if (InvalidDomain.is_empty()) {
2854 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002855 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002856 }
2857
Johannes Doerferta3519512016-04-23 13:02:23 +00002858 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002859 auto *TI = BB->getTerminator();
2860 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2861 for (unsigned u = 0; u < NumSuccs; u++) {
2862 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002863
2864 // Skip successors outside the SCoP.
Michael Kruse476f8552017-06-29 12:47:41 +00002865 if (!contains(SuccBB))
Johannes Doerfert7c013572016-04-12 09:57:34 +00002866 continue;
2867
Johannes Doerferte4459a22016-04-25 13:34:50 +00002868 // Skip backedges.
2869 if (DT.dominates(SuccBB, BB))
2870 continue;
2871
Michael Kruse476f8552017-06-29 12:47:41 +00002872 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2873
Johannes Doerferta3519512016-04-23 13:02:23 +00002874 auto *AdjustedInvalidDomain = adjustDomainDimensions(
Tobias Grosser325204a32017-07-15 12:41:32 +00002875 *this, InvalidDomain.copy(), BBLoop, SuccBBLoop);
Michael Kruse476f8552017-06-29 12:47:41 +00002876
Tobias Grosser13acbb92017-07-15 09:01:31 +00002877 auto *SuccInvalidDomain = InvalidDomainMap[SuccBB].copy();
Johannes Doerferta3519512016-04-23 13:02:23 +00002878 SuccInvalidDomain =
2879 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2880 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2881 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
Michael Kruse476f8552017-06-29 12:47:41 +00002882
Tobias Grosser13acbb92017-07-15 09:01:31 +00002883 InvalidDomainMap[SuccBB] = isl::manage(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002884
Michael Krusebc150122016-05-02 12:25:18 +00002885 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002886 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002887 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002888 continue;
2889
Tobias Grosserf44f0052017-07-09 15:47:17 +00002890 InvalidDomainMap.erase(BB);
Eli Friedmane737fc12017-07-17 23:58:33 +00002891 invalidate(COMPLEXITY, TI->getDebugLoc(), TI->getParent());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002892 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002893 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002894
Tobias Grosser325204a32017-07-15 12:41:32 +00002895 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002896 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002897
2898 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002899}
2900
Johannes Doerfert642594a2016-04-04 07:57:39 +00002901void Scop::propagateDomainConstraintsToRegionExit(
2902 BasicBlock *BB, Loop *BBLoop,
Michael Kruse476f8552017-06-29 12:47:41 +00002903 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002904 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002905
2906 // Check if the block @p BB is the entry of a region. If so we propagate it's
2907 // domain to the exit block of the region. Otherwise we are done.
2908 auto *RI = R.getRegionInfo();
2909 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2910 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002911 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002912 return;
2913
Johannes Doerfert642594a2016-04-04 07:57:39 +00002914 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002915 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002916 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002917 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002918 SmallVector<BasicBlock *, 4> LatchBBs;
2919 BBLoop->getLoopLatches(LatchBBs);
2920 for (auto *LatchBB : LatchBBs)
2921 if (BB != LatchBB && BBReg->contains(LatchBB))
2922 return;
2923 L = L->getParentLoop();
2924 }
2925
Tobias Grosser325204a32017-07-15 12:41:32 +00002926 isl::set Domain = DomainMap[BB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002927 assert(Domain && "Cannot propagate a nullptr");
2928
Michael Kruse476f8552017-06-29 12:47:41 +00002929 Loop *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002930
2931 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2932 // adjust the domain before we can propagate it.
Tobias Grosser325204a32017-07-15 12:41:32 +00002933 isl::set AdjustedDomain = isl::manage(
2934 adjustDomainDimensions(*this, Domain.copy(), BBLoop, ExitBBLoop));
2935 isl::set &ExitDomain = DomainMap[ExitBB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002936
2937 // If the exit domain is not yet created we set it otherwise we "add" the
2938 // current domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002939 ExitDomain = ExitDomain ? AdjustedDomain.unite(ExitDomain) : AdjustedDomain;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002940
Johannes Doerferta3519512016-04-23 13:02:23 +00002941 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002942 InvalidDomainMap[ExitBB] = ExitDomain.empty(ExitDomain.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002943
Johannes Doerfert642594a2016-04-04 07:57:39 +00002944 FinishedExitBlocks.insert(ExitBB);
2945}
2946
Michael Kruse476f8552017-06-29 12:47:41 +00002947bool Scop::buildDomainsWithBranchConstraints(
2948 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002949 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse476f8552017-06-29 12:47:41 +00002950
Johannes Doerfert96425c22015-08-30 21:13:53 +00002951 // To create the domain for each block in R we iterate over all blocks and
2952 // subregions in R and propagate the conditions under which the current region
2953 // element is executed. To this end we iterate in reverse post order over R as
2954 // it ensures that we first visit all predecessors of a region node (either a
2955 // basic block or a subregion) before we visit the region node itself.
2956 // Initially, only the domain for the SCoP region entry block is set and from
2957 // there we propagate the current domain to all successors, however we add the
2958 // condition that the successor is actually executed next.
2959 // As we are only interested in non-loop carried constraints here we can
2960 // simply skip loop back edges.
2961
Johannes Doerfert642594a2016-04-04 07:57:39 +00002962 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002963 ReversePostOrderTraversal<Region *> RTraversal(R);
2964 for (auto *RN : RTraversal) {
2965
2966 // Recurse for affine subregions but go on for basic blocks and non-affine
2967 // subregions.
2968 if (RN->isSubRegion()) {
2969 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002970 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002971 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI,
2972 InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002973 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002974 continue;
2975 }
2976 }
2977
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002978 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002979 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002980
Johannes Doerfert96425c22015-08-30 21:13:53 +00002981 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002982 TerminatorInst *TI = BB->getTerminator();
2983
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002984 if (isa<UnreachableInst>(TI))
2985 continue;
2986
Tobias Grosser325204a32017-07-15 12:41:32 +00002987 isl::set Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002988 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002989 continue;
Tobias Grosser325204a32017-07-15 12:41:32 +00002990 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain.get()));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002991
Johannes Doerfert642594a2016-04-04 07:57:39 +00002992 auto *BBLoop = getRegionNodeLoop(RN, LI);
2993 // Propagate the domain from BB directly to blocks that have a superset
2994 // domain, at the moment only region exit nodes of regions that start in BB.
Michael Kruse476f8552017-06-29 12:47:41 +00002995 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI,
2996 InvalidDomainMap);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002997
2998 // If all successors of BB have been set a domain through the propagation
2999 // above we do not need to build condition sets but can just skip this
3000 // block. However, it is important to note that this is a local property
3001 // with regards to the region @p R. To this end FinishedExitBlocks is a
3002 // local variable.
3003 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
3004 return FinishedExitBlocks.count(SuccBB);
3005 };
3006 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
3007 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003008
3009 // Build the condition sets for the successor nodes of the current region
3010 // node. If it is a non-affine subregion we will always execute the single
3011 // exit node, hence the single entry node domain is the condition set. For
3012 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003013 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003014 if (RN->isSubRegion())
Tobias Grosser325204a32017-07-15 12:41:32 +00003015 ConditionSets.push_back(Domain.copy());
3016 else if (!buildConditionSets(*this, BB, TI, BBLoop, Domain.get(),
Michael Kruse476f8552017-06-29 12:47:41 +00003017 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003018 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003019
3020 // Now iterate over the successors and set their initial domain based on
3021 // their condition set. We skip back edges here and have to be careful when
3022 // we leave a loop not to keep constraints over a dimension that doesn't
3023 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003024 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00003025 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Tobias Grosser325204a32017-07-15 12:41:32 +00003026 isl::set CondSet = isl::manage(ConditionSets[u]);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003027 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003028
Johannes Doerfert535de032016-04-19 14:49:05 +00003029 // Skip blocks outside the region.
Tobias Grosser325204a32017-07-15 12:41:32 +00003030 if (!contains(SuccBB))
Johannes Doerfert535de032016-04-19 14:49:05 +00003031 continue;
Johannes Doerfert535de032016-04-19 14:49:05 +00003032
Johannes Doerfert642594a2016-04-04 07:57:39 +00003033 // If we propagate the domain of some block to "SuccBB" we do not have to
3034 // adjust the domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00003035 if (FinishedExitBlocks.count(SuccBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00003036 continue;
Johannes Doerfert642594a2016-04-04 07:57:39 +00003037
Johannes Doerfert96425c22015-08-30 21:13:53 +00003038 // Skip back edges.
Tobias Grosser325204a32017-07-15 12:41:32 +00003039 if (DT.dominates(SuccBB, BB))
Johannes Doerfert96425c22015-08-30 21:13:53 +00003040 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003041
Michael Kruse476f8552017-06-29 12:47:41 +00003042 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
3043
Tobias Grosser325204a32017-07-15 12:41:32 +00003044 CondSet = isl::manage(
3045 adjustDomainDimensions(*this, CondSet.copy(), BBLoop, SuccBBLoop));
Johannes Doerfert96425c22015-08-30 21:13:53 +00003046
3047 // Set the domain for the successor or merge it with an existing domain in
3048 // case there are multiple paths (without loop back edges) to the
3049 // successor block.
Tobias Grosser325204a32017-07-15 12:41:32 +00003050 isl::set &SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00003051
Johannes Doerferta3519512016-04-23 13:02:23 +00003052 if (SuccDomain) {
Tobias Grosser325204a32017-07-15 12:41:32 +00003053 SuccDomain = SuccDomain.unite(CondSet).coalesce();
Johannes Doerferta3519512016-04-23 13:02:23 +00003054 } else {
3055 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00003056 InvalidDomainMap[SuccBB] = CondSet.empty(CondSet.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00003057 SuccDomain = CondSet;
3058 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00003059
Tobias Grosser325204a32017-07-15 12:41:32 +00003060 SuccDomain = SuccDomain.detect_equalities();
Tobias Grosser6d459c52017-05-23 04:26:28 +00003061
Michael Krusebc150122016-05-02 12:25:18 +00003062 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003063 // In case this happens we will clean up and bail.
Tobias Grosser325204a32017-07-15 12:41:32 +00003064 if (isl_set_n_basic_set(SuccDomain.get()) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003065 continue;
3066
3067 invalidate(COMPLEXITY, DebugLoc());
3068 while (++u < ConditionSets.size())
3069 isl_set_free(ConditionSets[u]);
3070 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003071 }
3072 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003073
3074 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003075}
3076
Michael Krused56b90a2016-09-01 09:03:27 +00003077__isl_give isl_set *
3078Scop::getPredecessorDomainConstraints(BasicBlock *BB,
3079 __isl_keep isl_set *Domain,
3080 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00003081 // If @p BB is the ScopEntry we are done
3082 if (R.getEntry() == BB)
3083 return isl_set_universe(isl_set_get_space(Domain));
3084
Johannes Doerfert642594a2016-04-04 07:57:39 +00003085 // The region info of this function.
3086 auto &RI = *R.getRegionInfo();
3087
Michael Kruse476f8552017-06-29 12:47:41 +00003088 Loop *BBLoop = getFirstNonBoxedLoopFor(BB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00003089
3090 // A domain to collect all predecessor domains, thus all conditions under
3091 // which the block is executed. To this end we start with the empty domain.
3092 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
3093
3094 // Set of regions of which the entry block domain has been propagated to BB.
3095 // all predecessors inside any of the regions can be skipped.
3096 SmallSet<Region *, 8> PropagatedRegions;
3097
3098 for (auto *PredBB : predecessors(BB)) {
3099 // Skip backedges.
3100 if (DT.dominates(BB, PredBB))
3101 continue;
3102
3103 // If the predecessor is in a region we used for propagation we can skip it.
3104 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
3105 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
3106 PredBBInRegion)) {
3107 continue;
3108 }
3109
3110 // Check if there is a valid region we can use for propagation, thus look
3111 // for a region that contains the predecessor and has @p BB as exit block.
3112 auto *PredR = RI.getRegionFor(PredBB);
3113 while (PredR->getExit() != BB && !PredR->contains(BB))
3114 PredR->getParent();
3115
3116 // If a valid region for propagation was found use the entry of that region
3117 // for propagation, otherwise the PredBB directly.
3118 if (PredR->getExit() == BB) {
3119 PredBB = PredR->getEntry();
3120 PropagatedRegions.insert(PredR);
3121 }
3122
Johannes Doerfert41cda152016-04-08 10:32:26 +00003123 auto *PredBBDom = getDomainConditions(PredBB);
Michael Kruse476f8552017-06-29 12:47:41 +00003124 Loop *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, getBoxedLoops());
3125
Johannes Doerfert642594a2016-04-04 07:57:39 +00003126 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
3127
3128 PredDom = isl_set_union(PredDom, PredBBDom);
3129 }
3130
3131 return PredDom;
3132}
3133
Michael Kruse476f8552017-06-29 12:47:41 +00003134bool Scop::propagateDomainConstraints(
3135 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00003136 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003137 // Iterate over the region R and propagate the domain constrains from the
3138 // predecessors to the current node. In contrast to the
3139 // buildDomainsWithBranchConstraints function, this one will pull the domain
3140 // information from the predecessors instead of pushing it to the successors.
3141 // Additionally, we assume the domains to be already present in the domain
3142 // map here. However, we iterate again in reverse post order so we know all
3143 // predecessors have been visited before a block or non-affine subregion is
3144 // visited.
3145
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003146 ReversePostOrderTraversal<Region *> RTraversal(R);
3147 for (auto *RN : RTraversal) {
3148
3149 // Recurse for affine subregions but go on for basic blocks and non-affine
3150 // subregions.
3151 if (RN->isSubRegion()) {
3152 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003153 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00003154 if (!propagateDomainConstraints(SubRegion, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003155 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003156 continue;
3157 }
3158 }
3159
3160 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00003161 isl::set &Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00003162 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003163
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003164 // Under the union of all predecessor conditions we can reach this block.
Tobias Grosser325204a32017-07-15 12:41:32 +00003165 isl::set PredDom =
3166 isl::manage(getPredecessorDomainConstraints(BB, Domain.get(), DT, LI));
3167 Domain = Domain.intersect(PredDom).coalesce();
3168 Domain = Domain.align_params(isl::manage(getParamSpace()));
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003169
Johannes Doerfert642594a2016-04-04 07:57:39 +00003170 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00003171 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Michael Kruse476f8552017-06-29 12:47:41 +00003172 if (!addLoopBoundsToHeaderDomain(BBLoop, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003173 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003174 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00003175
3176 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003177}
3178
Tobias Grosserc80d6972016-09-02 06:33:33 +00003179/// Create a map to map from a given iteration to a subsequent iteration.
3180///
3181/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
3182/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003183/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00003184///
3185/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003186static __isl_give isl_map *
3187createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
3188 auto *MapSpace = isl_space_map_from_set(SetSpace);
3189 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00003190 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003191 if (u != Dim)
3192 NextIterationMap =
3193 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
3194 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
3195 C = isl_constraint_set_constant_si(C, 1);
3196 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
3197 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
3198 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
3199 return NextIterationMap;
3200}
3201
Michael Kruse476f8552017-06-29 12:47:41 +00003202bool Scop::addLoopBoundsToHeaderDomain(
Tobias Grosser13acbb92017-07-15 09:01:31 +00003203 Loop *L, LoopInfo &LI, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003204 int LoopDepth = getRelativeLoopDepth(L);
3205 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003206
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003207 BasicBlock *HeaderBB = L->getHeader();
3208 assert(DomainMap.count(HeaderBB));
Tobias Grosser325204a32017-07-15 12:41:32 +00003209 isl::set &HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003210
Tobias Grosser325204a32017-07-15 12:41:32 +00003211 isl::map NextIterationMap = isl::manage(
3212 createNextIterationMap(HeaderBBDom.get_space().release(), LoopDepth));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003213
Tobias Grosser325204a32017-07-15 12:41:32 +00003214 isl::set UnionBackedgeCondition = HeaderBBDom.empty(HeaderBBDom.get_space());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003215
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003216 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
3217 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003218
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003219 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003220
3221 // If the latch is only reachable via error statements we skip it.
Tobias Grosser325204a32017-07-15 12:41:32 +00003222 isl::set LatchBBDom = DomainMap.lookup(LatchBB);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003223 if (!LatchBBDom)
3224 continue;
3225
Tobias Grosser325204a32017-07-15 12:41:32 +00003226 isl::set BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003227
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003228 TerminatorInst *TI = LatchBB->getTerminator();
3229 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00003230 assert(BI && "Only branch instructions allowed in loop latches");
3231
3232 if (BI->isUnconditional())
Tobias Grosser325204a32017-07-15 12:41:32 +00003233 BackedgeCondition = LatchBBDom;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003234 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003235 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003236 int idx = BI->getSuccessor(0) != HeaderBB;
Tobias Grosser325204a32017-07-15 12:41:32 +00003237 if (!buildConditionSets(*this, LatchBB, TI, L, LatchBBDom.get(),
3238 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003239 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003240
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003241 // Free the non back edge condition set as we do not need it.
3242 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003243
Tobias Grosser325204a32017-07-15 12:41:32 +00003244 BackedgeCondition = isl::manage(ConditionSets[idx]);
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003245 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003246
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003247 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3248 assert(LatchLoopDepth >= LoopDepth);
Tobias Grosser325204a32017-07-15 12:41:32 +00003249 BackedgeCondition = BackedgeCondition.project_out(
3250 isl::dim::set, LoopDepth + 1, LatchLoopDepth - LoopDepth);
3251 UnionBackedgeCondition = UnionBackedgeCondition.unite(BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003252 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003253
Tobias Grosser325204a32017-07-15 12:41:32 +00003254 isl::map ForwardMap = ForwardMap.lex_le(HeaderBBDom.get_space());
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003255 for (int i = 0; i < LoopDepth; i++)
Tobias Grosser325204a32017-07-15 12:41:32 +00003256 ForwardMap = ForwardMap.equate(isl::dim::in, i, isl::dim::out, i);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003257
Tobias Grosser325204a32017-07-15 12:41:32 +00003258 isl::set UnionBackedgeConditionComplement =
3259 UnionBackedgeCondition.complement();
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003260 UnionBackedgeConditionComplement =
Tobias Grosser325204a32017-07-15 12:41:32 +00003261 UnionBackedgeConditionComplement.lower_bound_si(isl::dim::set, LoopDepth,
3262 0);
3263 UnionBackedgeConditionComplement =
3264 UnionBackedgeConditionComplement.apply(ForwardMap);
3265 HeaderBBDom = HeaderBBDom.subtract(UnionBackedgeConditionComplement);
3266 HeaderBBDom = HeaderBBDom.apply(NextIterationMap);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003267
Tobias Grosser325204a32017-07-15 12:41:32 +00003268 auto Parts = partitionSetParts(HeaderBBDom.copy(), LoopDepth);
3269 HeaderBBDom = isl::manage(Parts.second);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003270
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003271 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3272 // the bounded assumptions to the context as they are already implied by the
3273 // <nsw> tag.
3274 if (Affinator.hasNSWAddRecForLoop(L)) {
3275 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003276 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003277 }
3278
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003279 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003280 recordAssumption(INFINITELOOP, UnboundedCtx,
3281 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003282 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003283}
3284
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003285MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003286 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003287
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003288 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003289 if (!PointerBaseInst)
3290 return nullptr;
3291
3292 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3293 if (!BasePtrStmt)
3294 return nullptr;
3295
3296 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3297}
3298
3299bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
Tobias Grosser4071cb52017-06-06 23:13:02 +00003300 isl::union_map Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003301 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003302 return getNonHoistableCtx(BasePtrMA, Writes).is_null();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003303 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003304
Tobias Grosserbe372d52017-02-09 10:11:58 +00003305 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003306 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003307 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003308 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003309
3310 return false;
3311}
3312
Johannes Doerfert5210da52016-06-02 11:06:54 +00003313bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003314 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003315 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003316
Johannes Doerfertcd195322016-11-17 21:41:08 +00003317 if (buildAliasGroups(AA)) {
3318 // Aliasing assumptions do not go through addAssumption but we still want to
3319 // collect statistics so we do it here explicitly.
3320 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003321 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003322 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003323 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003324
3325 // If a problem occurs while building the alias groups we need to delete
3326 // this SCoP and pretend it wasn't valid in the first place. To this end
3327 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003328 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003329
3330 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3331 << " could not be created as the number of parameters involved "
3332 "is too high. The SCoP will be "
3333 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3334 "the maximal number of parameters but be advised that the "
3335 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003336 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003337}
3338
Tobias Grosser889830b2017-02-09 23:12:22 +00003339std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003340Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003341 AliasSetTracker AST(AA);
3342
3343 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003344 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003345 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003346
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003347 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003348 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3349 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003350
3351 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003352 if (StmtDomainEmpty)
3353 continue;
3354
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003355 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003356 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003357 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003358 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003359 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003360 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003361 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003362 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003363 else
3364 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003365 AST.add(Acc);
3366 }
3367 }
3368
Tobias Grosser9edcf072017-01-16 14:07:57 +00003369 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003370 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003371 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003372 continue;
3373 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003374 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003375 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003376 if (AG.size() < 2)
3377 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003378 AliasGroups.push_back(std::move(AG));
3379 }
3380
Tobias Grosser9edcf072017-01-16 14:07:57 +00003381 return std::make_tuple(AliasGroups, HasWriteAccess);
3382}
3383
Tobias Grossere39f9122017-01-16 14:08:00 +00003384void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003385 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3386 AliasGroupTy NewAG;
3387 AliasGroupTy &AG = AliasGroups[u];
3388 AliasGroupTy::iterator AGI = AG.begin();
3389 isl_set *AGDomain = getAccessDomain(*AGI);
3390 while (AGI != AG.end()) {
3391 MemoryAccess *MA = *AGI;
3392 isl_set *MADomain = getAccessDomain(MA);
3393 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3394 NewAG.push_back(MA);
3395 AGI = AG.erase(AGI);
3396 isl_set_free(MADomain);
3397 } else {
3398 AGDomain = isl_set_union(AGDomain, MADomain);
3399 AGI++;
3400 }
3401 }
3402 if (NewAG.size() > 1)
3403 AliasGroups.push_back(std::move(NewAG));
3404 isl_set_free(AGDomain);
3405 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003406}
3407
3408bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3409 // To create sound alias checks we perform the following steps:
3410 // o) We partition each group into read only and non read only accesses.
3411 // o) For each group with more than one base pointer we then compute minimal
3412 // and maximal accesses to each array of a group in read only and non
3413 // read only partitions separately.
3414 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003415 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003416
3417 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3418
3419 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003420
Johannes Doerfert13771732014-10-01 12:40:46 +00003421 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser78a7a6c2017-06-23 08:05:31 +00003422 if (!hasFeasibleRuntimeContext())
3423 return false;
3424
Tobias Grosser57a1d362017-06-23 08:05:27 +00003425 {
3426 IslMaxOperationsGuard MaxOpGuard(getIslCtx(), OptComputeOut);
3427 bool Valid = buildAliasGroup(AG, HasWriteAccess);
3428 if (!Valid)
3429 return false;
3430 }
3431 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
3432 invalidate(COMPLEXITY, DebugLoc());
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003433 return false;
Tobias Grosser57a1d362017-06-23 08:05:27 +00003434 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003435 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003436
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003437 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003438}
3439
Tobias Grosser77f32572017-01-16 15:49:07 +00003440bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003441 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003442 AliasGroupTy ReadOnlyAccesses;
3443 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003444 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003445 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003446
Tobias Grosser77f32572017-01-16 15:49:07 +00003447 if (AliasGroup.size() < 2)
3448 return true;
3449
3450 for (MemoryAccess *Access : AliasGroup) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003451 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "PossibleAlias",
3452 Access->getAccessInstruction())
3453 << "Possibly aliasing pointer, use restrict keyword.");
Tobias Grosser889830b2017-02-09 23:12:22 +00003454 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3455 if (HasWriteAccess.count(Array)) {
3456 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003457 ReadWriteAccesses.push_back(Access);
3458 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003459 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003460 ReadOnlyAccesses.push_back(Access);
3461 }
3462 }
3463
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003464 // If there are no read-only pointers, and less than two read-write pointers,
3465 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003466 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003467 return true;
3468
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003469 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003470 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003471 return true;
3472
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003473 // For non-affine accesses, no alias check can be generated as we cannot
3474 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003475 for (MemoryAccess *MA : AliasGroup) {
3476 if (!MA->isAffine()) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003477 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc(),
3478 MA->getAccessInstruction()->getParent());
Tobias Grosser77f32572017-01-16 15:49:07 +00003479 return false;
3480 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003481 }
3482
3483 // Ensure that for all memory accesses for which we generate alias checks,
3484 // their base pointers are available.
3485 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003486 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3487 addRequiredInvariantLoad(
3488 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3489 }
3490
3491 MinMaxAliasGroups.emplace_back();
3492 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3493 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3494 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3495
3496 bool Valid;
3497
3498 Valid =
3499 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3500
3501 if (!Valid)
3502 return false;
3503
3504 // Bail out if the number of values we need to compare is too large.
3505 // This is important as the number of comparisons grows quadratically with
3506 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003507 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003508 RunTimeChecksMaxArraysPerGroup)
3509 return false;
3510
3511 Valid =
3512 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3513
3514 if (!Valid)
3515 return false;
3516
3517 return true;
3518}
3519
Tobias Grosserc80d6972016-09-02 06:33:33 +00003520/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003521static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003522 // Start with the smallest loop containing the entry and expand that
3523 // loop until it contains all blocks in the region. If there is a loop
3524 // containing all blocks in the region check if it is itself contained
3525 // and if so take the parent loop as it will be the smallest containing
3526 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003527 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003528 while (L) {
3529 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003530 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003531 AllContained &= L->contains(BB);
3532 if (AllContained)
3533 break;
3534 L = L->getParentLoop();
3535 }
3536
Johannes Doerfertef744432016-05-23 12:42:38 +00003537 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003538}
3539
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003540int Scop::NextScopID = 0;
3541
3542std::string Scop::CurrentFunc = "";
3543
3544int Scop::getNextID(std::string ParentFunc) {
3545 if (ParentFunc != CurrentFunc) {
3546 CurrentFunc = ParentFunc;
3547 NextScopID = 0;
3548 }
3549 return NextScopID++;
3550}
3551
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003552Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Eli Friedmane737fc12017-07-17 23:58:33 +00003553 ScopDetection::DetectionContext &DC, OptimizationRemarkEmitter &ORE)
Philip Pfaffe35bdcaf2017-05-15 13:43:01 +00003554 : SE(&ScalarEvolution), R(R), name(R.getNameStr()), IsOptimized(false),
Siddharth Bhat47c72372017-07-05 15:07:28 +00003555 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Eli Friedmane737fc12017-07-17 23:58:33 +00003556 MaxLoopDepth(0), CopyStmtsNum(0), SkipScop(false), DC(DC), ORE(ORE),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003557 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3558 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003559 Schedule(nullptr),
3560 ID(getNextID((*R.getEntry()->getParent()).getName().str())) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003561 if (IslOnErrorAbort)
3562 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003563 buildContext();
3564}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003565
Tobias Grosserbedef002016-12-02 08:10:56 +00003566void Scop::foldSizeConstantsToRight() {
3567 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3568
3569 for (auto Array : arrays()) {
3570 if (Array->getNumberOfDimensions() <= 1)
3571 continue;
3572
Tobias Grosser77eef902017-07-21 23:07:56 +00003573 isl_space *Space = Array->getSpace().release();
Tobias Grosserbedef002016-12-02 08:10:56 +00003574
3575 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3576
3577 if (!isl_union_set_contains(Accessed, Space)) {
3578 isl_space_free(Space);
3579 continue;
3580 }
3581
3582 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3583
3584 isl_map *Transform =
Tobias Grosser77eef902017-07-21 23:07:56 +00003585 isl_map_universe(isl_space_map_from_set(Array->getSpace().release()));
Tobias Grosserbedef002016-12-02 08:10:56 +00003586
3587 std::vector<int> Int;
3588
3589 int Dims = isl_set_dim(Elements, isl_dim_set);
3590 for (int i = 0; i < Dims; i++) {
3591 isl_set *DimOnly =
3592 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3593 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3594 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3595
3596 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3597
3598 if (i == Dims - 1) {
3599 Int.push_back(1);
3600 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3601 isl_basic_set_free(DimHull);
3602 continue;
3603 }
3604
3605 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3606 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3607 isl_val *Val = isl_aff_get_denominator_val(Diff);
3608 isl_aff_free(Diff);
3609
3610 int ValInt = 1;
3611
3612 if (isl_val_is_int(Val))
3613 ValInt = isl_val_get_num_si(Val);
3614 isl_val_free(Val);
3615
3616 Int.push_back(ValInt);
3617
3618 isl_constraint *C = isl_constraint_alloc_equality(
3619 isl_local_space_from_space(isl_map_get_space(Transform)));
3620 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3621 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3622 Transform = isl_map_add_constraint(Transform, C);
3623 isl_basic_set_free(DimHull);
3624 continue;
3625 }
3626
3627 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3628 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3629
3630 int ValInt = 1;
3631 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3632 ValInt = 0;
3633 }
3634
3635 Int.push_back(ValInt);
3636 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3637 isl_basic_set_free(DimHull);
3638 isl_basic_set_free(ZeroSet);
3639 }
3640
3641 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3642
3643 if (!isl_set_is_subset(Elements, MappedElements)) {
3644 isl_set_free(Elements);
3645 isl_set_free(MappedElements);
3646 isl_map_free(Transform);
3647 continue;
3648 }
3649
3650 isl_set_free(MappedElements);
3651
3652 bool CanFold = true;
3653
3654 if (Int[0] <= 1)
3655 CanFold = false;
3656
3657 unsigned NumDims = Array->getNumberOfDimensions();
3658 for (unsigned i = 1; i < NumDims - 1; i++)
3659 if (Int[0] != Int[i] && Int[i])
3660 CanFold = false;
3661
3662 if (!CanFold) {
3663 isl_set_free(Elements);
3664 isl_map_free(Transform);
3665 continue;
3666 }
3667
Tobias Grosserbedef002016-12-02 08:10:56 +00003668 for (auto &Access : AccessFunctions)
3669 if (Access->getScopArrayInfo() == Array)
3670 Access->setAccessRelation(isl_map_apply_range(
Tobias Grosser1515f6b2017-07-23 04:08:38 +00003671 Access->getAccessRelation().release(), isl_map_copy(Transform)));
Tobias Grosserbedef002016-12-02 08:10:56 +00003672
3673 isl_map_free(Transform);
3674
3675 std::vector<const SCEV *> Sizes;
3676 for (unsigned i = 0; i < NumDims; i++) {
3677 auto Size = Array->getDimensionSize(i);
3678
3679 if (i == NumDims - 1)
3680 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3681 Sizes.push_back(Size);
3682 }
3683
3684 Array->updateSizes(Sizes, false /* CheckConsistency */);
3685
3686 isl_set_free(Elements);
3687 }
3688 isl_union_set_free(Accessed);
3689 return;
3690}
3691
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003692void Scop::markFortranArrays() {
3693 for (ScopStmt &Stmt : Stmts) {
3694 for (MemoryAccess *MemAcc : Stmt) {
3695 Value *FAD = MemAcc->getFortranArrayDescriptor();
3696 if (!FAD)
3697 continue;
3698
3699 // TODO: const_cast-ing to edit
3700 ScopArrayInfo *SAI =
3701 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3702 assert(SAI && "memory access into a Fortran array does not "
3703 "have an associated ScopArrayInfo");
3704 SAI->applyAndSetFAD(FAD);
3705 }
3706 }
3707}
3708
Tobias Grosser491b7992016-12-02 05:21:22 +00003709void Scop::finalizeAccesses() {
3710 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003711 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003712 foldAccessRelations();
3713 assumeNoOutOfBounds();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003714 markFortranArrays();
Tobias Grosser491b7992016-12-02 05:21:22 +00003715}
3716
Tobias Grosser75805372011-04-29 06:27:02 +00003717Scop::~Scop() {
3718 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003719 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003720 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003721 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003722
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003723 for (auto &It : ParameterIds)
3724 isl_id_free(It.second);
3725
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003726 for (auto &AS : RecordedAssumptions)
3727 isl_set_free(AS.Set);
3728
Johannes Doerfertb164c792014-09-18 11:17:17 +00003729 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003730 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003731 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003732 isl_pw_multi_aff_free(MMA.first);
3733 isl_pw_multi_aff_free(MMA.second);
3734 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003735 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003736 isl_pw_multi_aff_free(MMA.first);
3737 isl_pw_multi_aff_free(MMA.second);
3738 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003739 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003740
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003741 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003742 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003743
3744 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003745 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003746 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003747 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003748 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003749 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003750 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003751}
3752
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003753void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003754 // Check all array accesses for each base pointer and find a (virtual) element
3755 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003756 for (ScopStmt &Stmt : *this)
3757 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003758 if (!Access->isArrayKind())
3759 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003760 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003761 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3762
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003763 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003764 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003765 unsigned DivisibleSize = Array->getElemSizeInBytes();
3766 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003767 while (!isDivisible(Subscript, DivisibleSize, *SE))
3768 DivisibleSize /= 2;
3769 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003770 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003771 }
3772
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003773 for (auto &Stmt : *this)
3774 for (auto &Access : Stmt)
3775 Access->updateDimensionality();
3776}
3777
Tobias Grosser491b7992016-12-02 05:21:22 +00003778void Scop::foldAccessRelations() {
3779 for (auto &Stmt : *this)
3780 for (auto &Access : Stmt)
3781 Access->foldAccessRelation();
3782}
3783
3784void Scop::assumeNoOutOfBounds() {
3785 for (auto &Stmt : *this)
3786 for (auto &Access : Stmt)
3787 Access->assumeNoOutOfBound();
3788}
3789
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003790void Scop::removeFromStmtMap(ScopStmt &Stmt) {
3791 if (Stmt.isRegionStmt())
3792 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3793 StmtMap.erase(BB);
3794 else
3795 StmtMap.erase(Stmt.getBasicBlock());
3796}
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003797
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003798void Scop::removeStmts(std::function<bool(ScopStmt &)> ShouldDelete) {
3799 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3800 if (!ShouldDelete(*StmtIt)) {
3801 StmtIt++;
3802 continue;
3803 }
3804
3805 removeFromStmtMap(*StmtIt);
3806 StmtIt = Stmts.erase(StmtIt);
3807 }
3808}
3809
3810void Scop::removeStmtNotInDomainMap() {
3811 auto ShouldDelete = [this](ScopStmt &Stmt) -> bool {
Tobias Grosser199ec4a2017-07-19 16:31:10 +00003812 return !this->DomainMap.lookup(Stmt.getEntryBlock());
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003813 };
3814 removeStmts(ShouldDelete);
3815}
3816
3817void Scop::simplifySCoP(bool AfterHoisting) {
3818
3819 auto ShouldDelete = [AfterHoisting](ScopStmt &Stmt) -> bool {
Johannes Doerfert26404542016-05-10 12:19:47 +00003820 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003821
Tobias Grosser3012a0b2017-07-16 22:44:17 +00003822 // Remove read only statements only after invariant load hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003823 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003824 bool OnlyRead = true;
3825 for (MemoryAccess *MA : Stmt) {
3826 if (MA->isRead())
3827 continue;
3828
3829 OnlyRead = false;
3830 break;
3831 }
3832
3833 RemoveStmt = OnlyRead;
3834 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003835 return RemoveStmt;
3836 };
Johannes Doerferteca9e892015-11-03 16:54:49 +00003837
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003838 removeStmts(ShouldDelete);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003839}
3840
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003841InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003842 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3843 if (!LInst)
3844 return nullptr;
3845
3846 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3847 LInst = cast<LoadInst>(Rep);
3848
Johannes Doerfert96e54712016-02-07 17:30:13 +00003849 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003850 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003851 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003852 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003853 continue;
3854
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003855 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003856 for (auto *MA : MAs)
3857 if (MA->getAccessInstruction() == Val)
3858 return &IAClass;
3859 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003860
3861 return nullptr;
3862}
3863
Tobias Grosserc80d6972016-09-02 06:33:33 +00003864/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003865static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003866 bool MAInvalidCtxIsEmpty,
3867 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003868 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3869 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3870 // TODO: We can provide more information for better but more expensive
3871 // results.
3872 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3873 LInst->getAlignment(), DL))
3874 return false;
3875
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003876 // If the location might be overwritten we do not hoist it unconditionally.
3877 //
3878 // TODO: This is probably to conservative.
3879 if (!NonHoistableCtxIsEmpty)
3880 return false;
3881
Michael Krusea6d48f52017-06-08 12:06:15 +00003882 // If a dereferenceable load is in a statement that is modeled precisely we
3883 // can hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003884 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003885 return true;
3886
3887 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003888 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003889 // statement domain.
3890 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3891 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3892 return false;
3893 return true;
3894}
3895
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003896void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003897
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003898 if (InvMAs.empty())
3899 return;
3900
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003901 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003902 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003903
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003904 // Get the context under which the statement is executed but remove the error
3905 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003906 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003907 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003908
Tobias Grosser90411a92017-02-16 19:11:33 +00003909 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003910 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Eli Friedmane737fc12017-07-17 23:58:33 +00003911 invalidate(COMPLEXITY, AccInst->getDebugLoc(), AccInst->getParent());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003912 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003913 for (auto &InvMA : InvMAs)
3914 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003915 return;
3916 }
3917
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003918 // Project out all parameters that relate to loads in the statement. Otherwise
3919 // we could have cyclic dependences on the constraints under which the
3920 // hoisted loads are executed and we could not determine an order in which to
3921 // pre-load them. This happens because not only lower bounds are part of the
3922 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003923 for (auto &InvMA : InvMAs) {
3924 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003925 Instruction *AccInst = MA->getAccessInstruction();
3926 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003927 SetVector<Value *> Values;
3928 for (const SCEV *Parameter : Parameters) {
3929 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003930 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003931 if (!Values.count(AccInst))
3932 continue;
3933
3934 if (isl_id *ParamId = getIdForParam(Parameter)) {
3935 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003936 if (Dim >= 0)
3937 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003938 isl_id_free(ParamId);
3939 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003940 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003941 }
3942 }
3943
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003944 for (auto &InvMA : InvMAs) {
3945 auto *MA = InvMA.MA;
3946 auto *NHCtx = InvMA.NonHoistableCtx;
3947
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003948 // Check for another invariant access that accesses the same location as
3949 // MA and if found consolidate them. Otherwise create a new equivalence
3950 // class at the end of InvariantEquivClasses.
3951 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003952 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003953 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3954
Johannes Doerfert85676e32016-04-23 14:32:34 +00003955 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003956 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003957 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3958
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003959 isl_set *MACtx;
3960 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003961 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3962 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003963 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003964 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003965 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003966 } else {
3967 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003968 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003969 MACtx = isl_set_gist_params(MACtx, getContext());
3970 }
3971
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003972 bool Consolidated = false;
3973 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003974 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003975 continue;
3976
Johannes Doerfertdf880232016-03-03 12:26:58 +00003977 // If the pointer and the type is equal check if the access function wrt.
3978 // to the domain is equal too. It can happen that the domain fixes
3979 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003980 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003981 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003982 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003983 if (!MAs.empty()) {
3984 auto *LastMA = MAs.front();
3985
Tobias Grosser1515f6b2017-07-23 04:08:38 +00003986 auto *AR = isl_map_range(MA->getAccessRelation().release());
3987 auto *LastAR = isl_map_range(LastMA->getAccessRelation().release());
Johannes Doerfertdf880232016-03-03 12:26:58 +00003988 bool SameAR = isl_set_is_equal(AR, LastAR);
3989 isl_set_free(AR);
3990 isl_set_free(LastAR);
3991
3992 if (!SameAR)
3993 continue;
3994 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003995
3996 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003997 MAs.push_front(MA);
3998
Johannes Doerfertdf880232016-03-03 12:26:58 +00003999 Consolidated = true;
4000
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004001 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004002 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00004003 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00004004 IAClassDomainCtx =
4005 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00004006 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00004007 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004008 break;
4009 }
4010
4011 if (Consolidated)
4012 continue;
4013
4014 // If we did not consolidate MA, thus did not find an equivalence class
4015 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004016 InvariantEquivClasses.emplace_back(
4017 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004018 }
4019
4020 isl_set_free(DomainCtx);
4021}
4022
Tobias Grosser1eeedf42017-07-20 19:55:19 +00004023/// Check if an access range is too complex.
4024///
4025/// An access range is too complex, if it contains either many disjuncts or
4026/// very complex expressions. As a simple heuristic, we assume if a set to
4027/// be too complex if the sum of existentially quantified dimensions and
4028/// set dimensions is larger than a threshold. This reliably detects both
4029/// sets with many disjuncts as well as sets with many divisions as they
4030/// arise in h264.
4031///
4032/// @param AccessRange The range to check for complexity.
4033///
4034/// @returns True if the access range is too complex.
4035static bool isAccessRangeTooComplex(isl::set AccessRange) {
4036 unsigned NumTotalDims = 0;
4037
4038 auto CountDimensions = [&NumTotalDims](isl::basic_set BSet) -> isl::stat {
4039 NumTotalDims += BSet.dim(isl::dim::div);
4040 NumTotalDims += BSet.dim(isl::dim::set);
4041 return isl::stat::ok;
4042 };
4043
4044 AccessRange.foreach_basic_set(CountDimensions);
4045
4046 if (NumTotalDims > MaxDimensionsInAccessRange)
4047 return true;
4048
4049 return false;
4050}
4051
Tobias Grosser4071cb52017-06-06 23:13:02 +00004052isl::set Scop::getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004053 // TODO: Loads that are not loop carried, hence are in a statement with
4054 // zero iterators, are by construction invariant, though we
4055 // currently "hoist" them anyway. This is necessary because we allow
4056 // them to be treated as parameters (e.g., in conditions) and our code
4057 // generation would otherwise use the old value.
4058
4059 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00004060 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004061
Johannes Doerfertc9765462016-11-17 22:11:56 +00004062 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
4063 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004064 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004065
4066 // Skip accesses that have an invariant base pointer which is defined but
4067 // not loaded inside the SCoP. This can happened e.g., if a readnone call
4068 // returns a pointer that is used as a base address. However, as we want
4069 // to hoist indirect pointers, we allow the base pointer to be defined in
4070 // the region if it is also a memory access. Each ScopArrayInfo object
4071 // that has a base pointer origin has a base pointer that is loaded and
4072 // that it is invariant, thus it will be hoisted too. However, if there is
4073 // no base pointer origin we check that the base pointer is defined
4074 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004075 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00004076 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004077 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004078
Tobias Grosser1515f6b2017-07-23 04:08:38 +00004079 isl::map AccessRelation = give(Access->getAccessRelation().release());
Tobias Grosser4071cb52017-06-06 23:13:02 +00004080 assert(!AccessRelation.is_empty());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004081
Tobias Grosser4071cb52017-06-06 23:13:02 +00004082 if (AccessRelation.involves_dims(isl::dim::in, 0, Stmt.getNumIterators()))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004083 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004084
Tobias Grosser4071cb52017-06-06 23:13:02 +00004085 AccessRelation = AccessRelation.intersect_domain(give(Stmt.getDomain()));
4086 isl::set SafeToLoad;
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004087
4088 auto &DL = getFunction().getParent()->getDataLayout();
4089 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
4090 DL)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00004091 SafeToLoad = isl::set::universe(AccessRelation.get_space().range());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004092 } else if (BB != LI->getParent()) {
4093 // Skip accesses in non-affine subregions as they might not be executed
4094 // under the same condition as the entry of the non-affine subregion.
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004095 return nullptr;
4096 } else {
Tobias Grosser4071cb52017-06-06 23:13:02 +00004097 SafeToLoad = AccessRelation.range();
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004098 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004099
Tobias Grosser1eeedf42017-07-20 19:55:19 +00004100 if (isAccessRangeTooComplex(AccessRelation.range()))
4101 return nullptr;
4102
Tobias Grosser4071cb52017-06-06 23:13:02 +00004103 isl::union_map Written = Writes.intersect_range(SafeToLoad);
4104 isl::set WrittenCtx = Written.params();
4105 bool IsWritten = !WrittenCtx.is_empty();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004106
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004107 if (!IsWritten)
4108 return WrittenCtx;
4109
Tobias Grosser4071cb52017-06-06 23:13:02 +00004110 WrittenCtx = WrittenCtx.remove_divs();
4111 bool TooComplex =
4112 isl_set_n_basic_set(WrittenCtx.get()) >= MaxDisjunctsInDomain;
4113 if (TooComplex || !isRequiredInvariantLoad(LI))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004114 return nullptr;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004115
Tobias Grosser4071cb52017-06-06 23:13:02 +00004116 addAssumption(INVARIANTLOAD, WrittenCtx.copy(), LI->getDebugLoc(),
Eli Friedmane737fc12017-07-17 23:58:33 +00004117 AS_RESTRICTION, LI->getParent());
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004118 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004119}
4120
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004121void Scop::verifyInvariantLoads() {
4122 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004123 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00004124 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00004125 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00004126 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004127 invalidate(INVARIANTLOAD, LI->getDebugLoc(), LI->getParent());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004128 return;
4129 }
4130 }
4131}
4132
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004133void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00004134 if (!PollyInvariantLoadHoisting)
4135 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004136
Tobias Grosser4071cb52017-06-06 23:13:02 +00004137 isl::union_map Writes = give(getWrites());
Tobias Grosser0865e7752016-02-29 07:29:42 +00004138 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004139 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004140
Tobias Grosser0865e7752016-02-29 07:29:42 +00004141 for (MemoryAccess *Access : Stmt)
Tobias Grosser4071cb52017-06-06 23:13:02 +00004142 if (isl::set NHCtx = getNonHoistableCtx(Access, Writes))
4143 InvariantAccesses.push_back({Access, NHCtx.release()});
Tobias Grosser0865e7752016-02-29 07:29:42 +00004144
4145 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00004146 for (auto InvMA : InvariantAccesses)
4147 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00004148 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004149 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004150}
4151
Tobias Grosserf3adab42017-05-10 10:59:58 +00004152/// Find the canonical scop array info object for a set of invariant load
4153/// hoisted loads. The canonical array is the one that corresponds to the
4154/// first load in the list of accesses which is used as base pointer of a
4155/// scop array.
4156static const ScopArrayInfo *findCanonicalArray(Scop *S,
4157 MemoryAccessList &Accesses) {
4158 for (MemoryAccess *Access : Accesses) {
4159 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
4160 Access->getAccessInstruction(), MemoryKind::Array);
4161 if (CanonicalArray)
4162 return CanonicalArray;
4163 }
4164 return nullptr;
4165}
4166
4167/// Check if @p Array severs as base array in an invariant load.
4168static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
4169 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
4170 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
4171 if (Access2->getScopArrayInfo() == Array)
4172 return true;
4173 return false;
4174}
4175
4176/// Replace the base pointer arrays in all memory accesses referencing @p Old,
4177/// with a reference to @p New.
4178static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
4179 const ScopArrayInfo *New) {
4180 for (ScopStmt &Stmt : *S)
4181 for (MemoryAccess *Access : Stmt) {
4182 if (Access->getLatestScopArrayInfo() != Old)
4183 continue;
4184
Tobias Grosser77eef902017-07-21 23:07:56 +00004185 isl_id *Id = New->getBasePtrId().release();
Tobias Grosser1515f6b2017-07-23 04:08:38 +00004186 isl_map *Map = Access->getAccessRelation().release();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004187 Map = isl_map_set_tuple_id(Map, isl_dim_out, Id);
4188 Access->setAccessRelation(Map);
4189 }
4190}
4191
4192void Scop::canonicalizeDynamicBasePtrs() {
4193 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
4194 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
4195
4196 const ScopArrayInfo *CanonicalBasePtrSAI =
4197 findCanonicalArray(this, BasePtrAccesses);
4198
4199 if (!CanonicalBasePtrSAI)
4200 continue;
4201
4202 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
4203 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
4204 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
4205 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
4206 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
4207 continue;
4208
4209 // we currently do not canonicalize arrays where some accesses are
4210 // hoisted as invariant loads. If we would, we need to update the access
4211 // function of the invariant loads as well. However, as this is not a
4212 // very common situation, we leave this for now to avoid further
4213 // complexity increases.
4214 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
4215 continue;
4216
4217 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
4218 }
4219 }
4220}
4221
Michael Kruseb738ffa2017-06-28 13:02:43 +00004222ScopArrayInfo *Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
4223 ArrayRef<const SCEV *> Sizes,
4224 MemoryKind Kind,
4225 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004226 assert((BasePtr || BaseName) &&
4227 "BasePtr and BaseName can not be nullptr at the same time.");
4228 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
4229 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
4230 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004231 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004232 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00004233 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00004234 DL, this, BaseName));
4235 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004236 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004237 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00004238 // In case of mismatching array sizes, we bail out by setting the run-time
4239 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004240 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004241 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004242 }
Tobias Grosserab671442015-05-23 05:58:27 +00004243 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004244}
4245
Michael Kruseb738ffa2017-06-28 13:02:43 +00004246ScopArrayInfo *Scop::createScopArrayInfo(Type *ElementType,
4247 const std::string &BaseName,
4248 const std::vector<unsigned> &Sizes) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004249 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
4250 std::vector<const SCEV *> SCEVSizes;
4251
4252 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00004253 if (size)
4254 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
4255 else
4256 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00004257
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004258 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
4259 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00004260 return SAI;
4261}
4262
Tobias Grosserf3adab42017-05-10 10:59:58 +00004263const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
4264 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00004265 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004266 return SAI;
4267}
4268
4269const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
4270 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004271 assert(SAI && "No ScopArrayInfo available for this base pointer");
4272 return SAI;
4273}
4274
Tobias Grosser74394f02013-01-14 22:40:23 +00004275std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004276
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004277std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004278 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004279 return stringFromIslObj(AssumedContext);
4280}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004281
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004282std::string Scop::getInvalidContextStr() const {
4283 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004284}
Tobias Grosser75805372011-04-29 06:27:02 +00004285
4286std::string Scop::getNameStr() const {
4287 std::string ExitName, EntryName;
Siddharth Bhat07bee292017-06-02 08:01:22 +00004288 std::tie(EntryName, ExitName) = getEntryExitStr();
4289 return EntryName + "---" + ExitName;
4290}
4291
4292std::pair<std::string, std::string> Scop::getEntryExitStr() const {
4293 std::string ExitName, EntryName;
Tobias Grosser75805372011-04-29 06:27:02 +00004294 raw_string_ostream ExitStr(ExitName);
4295 raw_string_ostream EntryStr(EntryName);
4296
Tobias Grosserf240b482014-01-09 10:42:15 +00004297 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004298 EntryStr.str();
4299
4300 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00004301 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004302 ExitStr.str();
4303 } else
4304 ExitName = "FunctionExit";
4305
Siddharth Bhat07bee292017-06-02 08:01:22 +00004306 return std::make_pair(EntryName, ExitName);
Tobias Grosser75805372011-04-29 06:27:02 +00004307}
4308
Tobias Grosser74394f02013-01-14 22:40:23 +00004309__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00004310__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00004311 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00004312}
4313
Tobias Grossere86109f2013-10-29 21:05:49 +00004314__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004315 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00004316 return isl_set_copy(AssumedContext);
4317}
4318
Michael Krusef3091bf2017-03-17 13:09:52 +00004319bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004320 if (PollyProcessUnprofitable)
4321 return true;
4322
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004323 if (isEmpty())
4324 return false;
4325
4326 unsigned OptimizableStmtsOrLoops = 0;
4327 for (auto &Stmt : *this) {
4328 if (Stmt.getNumIterators() == 0)
4329 continue;
4330
4331 bool ContainsArrayAccs = false;
4332 bool ContainsScalarAccs = false;
4333 for (auto *MA : Stmt) {
4334 if (MA->isRead())
4335 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004336 ContainsArrayAccs |= MA->isLatestArrayKind();
4337 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004338 }
4339
Michael Krusef3091bf2017-03-17 13:09:52 +00004340 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004341 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4342 }
4343
4344 return OptimizableStmtsOrLoops > 1;
4345}
4346
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004347bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004348 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004349 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00004350 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4351 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4352 isl_set_is_subset(PositiveContext, NegativeContext));
4353 isl_set_free(PositiveContext);
4354 if (!IsFeasible) {
4355 isl_set_free(NegativeContext);
4356 return false;
4357 }
4358
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004359 auto *DomainContext = isl_union_set_params(getDomains());
4360 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00004361 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004362 isl_set_free(NegativeContext);
4363 isl_set_free(DomainContext);
4364
Johannes Doerfert43788c52015-08-20 05:58:56 +00004365 return IsFeasible;
4366}
4367
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004368static std::string toString(AssumptionKind Kind) {
4369 switch (Kind) {
4370 case ALIASING:
4371 return "No-aliasing";
4372 case INBOUNDS:
4373 return "Inbounds";
4374 case WRAPPING:
4375 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004376 case UNSIGNED:
4377 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004378 case COMPLEXITY:
4379 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004380 case PROFITABLE:
4381 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004382 case ERRORBLOCK:
4383 return "No-error";
4384 case INFINITELOOP:
4385 return "Finite loop";
4386 case INVARIANTLOAD:
4387 return "Invariant load";
4388 case DELINEARIZATION:
4389 return "Delinearization";
4390 }
4391 llvm_unreachable("Unknown AssumptionKind!");
4392}
4393
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004394bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4395 if (Sign == AS_ASSUMPTION) {
4396 if (isl_set_is_subset(Context, Set))
4397 return false;
4398
4399 if (isl_set_is_subset(AssumedContext, Set))
4400 return false;
4401 } else {
4402 if (isl_set_is_disjoint(Set, Context))
4403 return false;
4404
4405 if (isl_set_is_subset(Set, InvalidContext))
4406 return false;
4407 }
4408 return true;
4409}
4410
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004411bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004412 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004413 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4414 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004415
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004416 // Do never emit trivial assumptions as they only clutter the output.
4417 if (!PollyRemarksMinimal) {
4418 isl_set *Univ = nullptr;
4419 if (Sign == AS_ASSUMPTION)
4420 Univ = isl_set_universe(isl_set_get_space(Set));
4421
4422 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4423 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4424 isl_set_free(Univ);
4425
4426 if (IsTrivial)
4427 return false;
4428 }
4429
Johannes Doerfertcd195322016-11-17 21:41:08 +00004430 switch (Kind) {
4431 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004432 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004433 break;
4434 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004435 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004436 break;
4437 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004438 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004439 break;
4440 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004441 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004442 break;
4443 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004444 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004445 break;
4446 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004447 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004448 break;
4449 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004450 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004451 break;
4452 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004453 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004454 break;
4455 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004456 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004457 break;
4458 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004459 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004460 break;
4461 }
4462
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004463 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4464 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Eli Friedmane737fc12017-07-17 23:58:33 +00004465 if (BB)
4466 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc, BB)
4467 << Msg);
4468 else
4469 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc,
4470 R.getEntry())
4471 << Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004472 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004473}
4474
4475void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004476 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004477 // Simplify the assumptions/restrictions first.
4478 Set = isl_set_gist_params(Set, getContext());
4479
Eli Friedmane737fc12017-07-17 23:58:33 +00004480 if (!trackAssumption(Kind, Set, Loc, Sign, BB)) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004481 isl_set_free(Set);
4482 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004483 }
4484
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004485 if (Sign == AS_ASSUMPTION) {
4486 AssumedContext = isl_set_intersect(AssumedContext, Set);
4487 AssumedContext = isl_set_coalesce(AssumedContext);
4488 } else {
4489 InvalidContext = isl_set_union(InvalidContext, Set);
4490 InvalidContext = isl_set_coalesce(InvalidContext);
4491 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004492}
4493
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004494void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004495 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004496 assert((isl_set_is_params(Set) || BB) &&
4497 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004498 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004499}
4500
4501void Scop::addRecordedAssumptions() {
4502 while (!RecordedAssumptions.empty()) {
4503 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004504
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004505 if (!AS.BB) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004506 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign, nullptr /* BasicBlock */);
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004507 continue;
4508 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004509
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004510 // If the domain was deleted the assumptions are void.
4511 isl_set *Dom = getDomainConditions(AS.BB);
4512 if (!Dom) {
4513 isl_set_free(AS.Set);
4514 continue;
4515 }
4516
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004517 // If a basic block was given use its domain to simplify the assumption.
4518 // In case of restrictions we know they only have to hold on the domain,
4519 // thus we can intersect them with the domain of the block. However, for
4520 // assumptions the domain has to imply them, thus:
4521 // _ _____
4522 // Dom => S <==> A v B <==> A - B
4523 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004524 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004525 // assumption.
4526 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004527 if (AS.Sign == AS_RESTRICTION)
4528 S = isl_set_params(isl_set_intersect(S, Dom));
4529 else /* (AS.Sign == AS_ASSUMPTION) */
4530 S = isl_set_params(isl_set_subtract(Dom, S));
4531
Eli Friedmane737fc12017-07-17 23:58:33 +00004532 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION, AS.BB);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004533 }
4534}
4535
Eli Friedmane737fc12017-07-17 23:58:33 +00004536void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB) {
4537 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION, BB);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004538}
4539
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004540__isl_give isl_set *Scop::getInvalidContext() const {
4541 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004542}
4543
Tobias Grosser75805372011-04-29 06:27:02 +00004544void Scop::printContext(raw_ostream &OS) const {
4545 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004546 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004547
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004548 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004549 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004550
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004551 OS.indent(4) << "Invalid Context:\n";
4552 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004553
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004554 unsigned Dim = 0;
4555 for (const SCEV *Parameter : Parameters)
4556 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004557}
4558
Johannes Doerfertb164c792014-09-18 11:17:17 +00004559void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004560 int noOfGroups = 0;
4561 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004562 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004563 noOfGroups += 1;
4564 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004565 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004566 }
4567
Tobias Grosserbb853c22015-07-25 12:31:03 +00004568 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004569 if (MinMaxAliasGroups.empty()) {
4570 OS.indent(8) << "n/a\n";
4571 return;
4572 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004573
Tobias Grosserbb853c22015-07-25 12:31:03 +00004574 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004575
4576 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004577 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004578 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004579 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004580 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4581 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004582 }
4583 OS << " ]]\n";
4584 }
4585
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004586 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004587 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004588 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
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 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004595 }
4596}
4597
Michael Krusecd4c9772017-07-21 15:35:53 +00004598void Scop::printStatements(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00004599 OS << "Statements {\n";
4600
Michael Krusecd4c9772017-07-21 15:35:53 +00004601 for (const ScopStmt &Stmt : *this) {
4602 OS.indent(4);
4603 Stmt.print(OS, PrintInstructions);
4604 }
Tobias Grosser75805372011-04-29 06:27:02 +00004605
4606 OS.indent(4) << "}\n";
4607}
4608
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004609void Scop::printArrayInfo(raw_ostream &OS) const {
4610 OS << "Arrays {\n";
4611
Tobias Grosserab671442015-05-23 05:58:27 +00004612 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004613 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004614
4615 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004616
4617 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4618
4619 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004620 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004621
4622 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004623}
4624
Michael Krusecd4c9772017-07-21 15:35:53 +00004625void Scop::print(raw_ostream &OS, bool PrintInstructions) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004626 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004627 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004628 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004629 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004630 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004631 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004632 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004633 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004634 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004635 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004636 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4637 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004638 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004639 }
4640 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004641 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004642 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004643 printAliasAssumptions(OS);
Michael Krusecd4c9772017-07-21 15:35:53 +00004644 printStatements(OS.indent(4), PrintInstructions);
Tobias Grosser75805372011-04-29 06:27:02 +00004645}
4646
Michael Kruse5d518462017-07-21 15:54:07 +00004647#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00004648LLVM_DUMP_METHOD void Scop::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00004649#endif
Tobias Grosser75805372011-04-29 06:27:02 +00004650
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004651isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004652
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004653__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4654 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004655 // First try to use the SCEVAffinator to generate a piecewise defined
4656 // affine function from @p E in the context of @p BB. If that tasks becomes to
4657 // complex the affinator might return a nullptr. In such a case we invalidate
4658 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004659 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004660 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004661 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004662 // TODO: We could use a heuristic and either use:
4663 // SCEVAffinator::takeNonNegativeAssumption
4664 // or
4665 // SCEVAffinator::interpretAsUnsigned
4666 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004667 if (NonNegative)
4668 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004669 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004670 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004671
4672 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
Eli Friedmane737fc12017-07-17 23:58:33 +00004673 invalidate(COMPLEXITY, DL, BB);
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004674 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004675}
4676
Tobias Grosser808cd692015-07-14 09:33:13 +00004677__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004678 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4679 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004680
Tobias Grosser808cd692015-07-14 09:33:13 +00004681 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004682 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004683
4684 return Domain;
4685}
4686
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004687__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4688 PWACtx PWAC = getPwAff(E, BB);
4689 isl_set_free(PWAC.second);
4690 return PWAC.first;
4691}
4692
Tobias Grossere5a35142015-11-12 14:07:09 +00004693__isl_give isl_union_map *
4694Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4695 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004696
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004697 for (ScopStmt &Stmt : *this) {
4698 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004699 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004700 continue;
4701
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004702 isl_set *Domain = Stmt.getDomain();
Tobias Grosser1515f6b2017-07-23 04:08:38 +00004703 isl_map *AccessDomain = MA->getAccessRelation().release();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004704 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004705 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004706 }
4707 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004708 return isl_union_map_coalesce(Accesses);
4709}
4710
4711__isl_give isl_union_map *Scop::getMustWrites() {
4712 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004713}
4714
4715__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004716 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004717}
4718
Tobias Grosser37eb4222014-02-20 21:43:54 +00004719__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004720 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004721}
4722
4723__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004724 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004725}
4726
Tobias Grosser2ac23382015-11-12 14:07:13 +00004727__isl_give isl_union_map *Scop::getAccesses() {
4728 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4729}
4730
Roman Gareevb3224ad2016-09-14 06:26:09 +00004731// Check whether @p Node is an extension node.
4732//
4733// @return true if @p Node is an extension node.
4734isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4735 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4736 return isl_bool_error;
4737 else
4738 return isl_bool_true;
4739}
4740
4741bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4742 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4743 nullptr) == isl_stat_error;
4744}
4745
Tobias Grosser808cd692015-07-14 09:33:13 +00004746__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004747 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004748 if (containsExtensionNode(Tree)) {
4749 isl_schedule_free(Tree);
4750 return nullptr;
4751 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004752 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004753 isl_schedule_free(Tree);
4754 return S;
4755}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004756
Tobias Grosser808cd692015-07-14 09:33:13 +00004757__isl_give isl_schedule *Scop::getScheduleTree() const {
4758 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4759 getDomains());
4760}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004761
Tobias Grosser808cd692015-07-14 09:33:13 +00004762void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4763 auto *S = isl_schedule_from_domain(getDomains());
4764 S = isl_schedule_insert_partial_schedule(
4765 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4766 isl_schedule_free(Schedule);
4767 Schedule = S;
4768}
4769
4770void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4771 isl_schedule_free(Schedule);
4772 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004773}
4774
4775bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4776 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004777 for (ScopStmt &Stmt : *this) {
4778 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004779 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4780 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4781
4782 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4783 isl_union_set_free(StmtDomain);
4784 isl_union_set_free(NewStmtDomain);
4785 continue;
4786 }
4787
4788 Changed = true;
4789
4790 isl_union_set_free(StmtDomain);
4791 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4792
4793 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004794 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004795 isl_union_set_free(NewStmtDomain);
4796 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004797 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004798 }
4799 isl_union_set_free(Domain);
4800 return Changed;
4801}
4802
Tobias Grosser75805372011-04-29 06:27:02 +00004803ScalarEvolution *Scop::getSE() const { return SE; }
4804
Tobias Grosserc80d6972016-09-02 06:33:33 +00004805// Create an isl_multi_union_aff that defines an identity mapping from the
4806// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004807//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004808// # Example:
4809//
4810// Domain: { A[i,j]; B[i,j,k] }
4811// N: 1
4812//
4813// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4814//
4815// @param USet A union set describing the elements for which to generate a
4816// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004817// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004818// @returns A mapping from USet to its N-th dimension.
Tobias Grosser99320862017-05-26 17:22:03 +00004819static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) {
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004820 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004821 assert(USet);
Siddharth Bhat8bb436e2017-05-29 11:34:29 +00004822 assert(!USet.is_empty());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004823
Tobias Grosser99320862017-05-26 17:22:03 +00004824 auto Result = isl::union_pw_multi_aff::empty(USet.get_space());
Tobias Grosser808cd692015-07-14 09:33:13 +00004825
Tobias Grosser99320862017-05-26 17:22:03 +00004826 auto Lambda = [&Result, N](isl::set S) -> isl::stat {
4827 int Dim = S.dim(isl::dim::set);
4828 auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set,
4829 N, Dim - N);
4830 if (N > 1)
4831 PMA = PMA.drop_dims(isl::dim::out, 0, N - 1);
Tobias Grosser808cd692015-07-14 09:33:13 +00004832
Tobias Grosser99320862017-05-26 17:22:03 +00004833 Result = Result.add_pw_multi_aff(PMA);
4834 return isl::stat::ok;
4835 };
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004836
Tobias Grosser99320862017-05-26 17:22:03 +00004837 isl::stat Res = USet.foreach_set(Lambda);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004838 (void)Res;
4839
Tobias Grosser99320862017-05-26 17:22:03 +00004840 assert(Res == isl::stat::ok);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004841
Tobias Grosser99320862017-05-26 17:22:03 +00004842 return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result));
Tobias Grosser808cd692015-07-14 09:33:13 +00004843}
4844
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004845void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop,
4846 std::vector<Instruction *> Instructions) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004847 assert(BB && "Unexpected nullptr!");
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004848 Stmts.emplace_back(*this, *BB, SurroundingLoop, Instructions);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004849 auto *Stmt = &Stmts.back();
Michael Kruse4dfa7322017-07-18 15:41:49 +00004850 StmtMap[BB].push_back(Stmt);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004851}
4852
Michael Kruse55454072017-03-15 22:16:43 +00004853void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004854 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004855 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004856 auto *Stmt = &Stmts.back();
4857 for (BasicBlock *BB : R->blocks())
Michael Kruse4dfa7322017-07-18 15:41:49 +00004858 StmtMap[BB].push_back(Stmt);
Tobias Grosser808cd692015-07-14 09:33:13 +00004859}
4860
Roman Gareevb3224ad2016-09-14 06:26:09 +00004861ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4862 __isl_take isl_map *TargetRel,
4863 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004864#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004865 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4866 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4867 assert(isl_set_is_subset(Domain, TargetDomain) &&
4868 "Target access not defined for complete statement domain");
4869 assert(isl_set_is_subset(Domain, SourceDomain) &&
4870 "Source access not defined for complete statement domain");
4871 isl_set_free(SourceDomain);
4872 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004873#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004874 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4875 CopyStmtsNum++;
4876 return &(Stmts.back());
4877}
4878
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004879void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004880 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004881 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004882 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004883 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4884 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004885}
4886
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004887/// To generate a schedule for the elements in a Region we traverse the Region
4888/// in reverse-post-order and add the contained RegionNodes in traversal order
4889/// to the schedule of the loop that is currently at the top of the LoopStack.
4890/// For loop-free codes, this results in a correct sequential ordering.
4891///
4892/// Example:
4893/// bb1(0)
4894/// / \.
4895/// bb2(1) bb3(2)
4896/// \ / \.
4897/// bb4(3) bb5(4)
4898/// \ /
4899/// bb6(5)
4900///
4901/// Including loops requires additional processing. Whenever a loop header is
4902/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4903/// from an empty schedule, we first process all RegionNodes that are within
4904/// this loop and complete the sequential schedule at this loop-level before
4905/// processing about any other nodes. To implement this
4906/// loop-nodes-first-processing, the reverse post-order traversal is
4907/// insufficient. Hence, we additionally check if the traversal yields
4908/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4909/// These region-nodes are then queue and only traverse after the all nodes
4910/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004911void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004912 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004913
4914 ReversePostOrderTraversal<Region *> RTraversal(R);
4915 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4916 std::deque<RegionNode *> DelayList;
4917 bool LastRNWaiting = false;
4918
4919 // Iterate over the region @p R in reverse post-order but queue
4920 // sub-regions/blocks iff they are not part of the last encountered but not
4921 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4922 // that we queued the last sub-region/block from the reverse post-order
4923 // iterator. If it is set we have to explore the next sub-region/block from
4924 // the iterator (if any) to guarantee progress. If it is not set we first try
4925 // the next queued sub-region/blocks.
4926 while (!WorkList.empty() || !DelayList.empty()) {
4927 RegionNode *RN;
4928
4929 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4930 RN = WorkList.front();
4931 WorkList.pop_front();
4932 LastRNWaiting = false;
4933 } else {
4934 RN = DelayList.front();
4935 DelayList.pop_front();
4936 }
4937
4938 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004939 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004940 L = OuterScopLoop;
4941
Tobias Grosser151ae322016-04-03 19:36:52 +00004942 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004943 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004944 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004945 LastRNWaiting = true;
4946 DelayList.push_back(RN);
4947 continue;
4948 }
4949 LoopStack.push_back({L, nullptr, 0});
4950 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004951 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004952 }
4953
4954 return;
4955}
4956
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004957void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004958
Tobias Grosser8362c262016-01-06 15:30:06 +00004959 if (RN->isSubRegion()) {
4960 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004961 if (!isNonAffineSubRegion(LocalRegion)) {
4962 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004963 return;
4964 }
4965 }
Michael Kruse046dde42015-08-10 13:01:57 +00004966
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004967 auto &LoopData = LoopStack.back();
4968 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004969
Michael Kruse1ce67912017-07-20 17:18:58 +00004970 for (auto *Stmt : getStmtListFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004971 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4972 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004973 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004974 }
4975
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004976 // Check if we just processed the last node in this loop. If we did, finalize
4977 // the loop by:
4978 //
4979 // - adding new schedule dimensions
4980 // - folding the resulting schedule into the parent loop schedule
4981 // - dropping the loop schedule from the LoopStack.
4982 //
4983 // Then continue to check surrounding loops, which might also have been
4984 // completed by this node.
4985 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00004986 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004987 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004988 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004989
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004990 LoopStack.pop_back();
4991 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004992
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004993 if (Schedule) {
Tobias Grosser99320862017-05-26 17:22:03 +00004994 isl::union_set Domain = give(isl_schedule_get_domain(Schedule));
4995 isl::multi_union_pw_aff MUPA = mapToDimension(Domain, LoopStack.size());
4996 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA.release());
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004997 NextLoopData.Schedule =
4998 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004999 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00005000
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005001 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
5002 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00005003 }
Tobias Grosser75805372011-04-29 06:27:02 +00005004}
5005
Michael Kruse6f7721f2016-02-24 22:08:19 +00005006ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00005007 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00005008 if (StmtMapIt == StmtMap.end())
5009 return nullptr;
Michael Kruse4dfa7322017-07-18 15:41:49 +00005010 assert(StmtMapIt->second.size() == 1);
5011 return StmtMapIt->second.front();
Johannes Doerfert7c494212014-10-31 23:13:39 +00005012}
5013
Michael Kruse6eba4b12017-07-20 17:08:50 +00005014ArrayRef<ScopStmt *> Scop::getStmtListFor(BasicBlock *BB) const {
5015 auto StmtMapIt = StmtMap.find(BB);
5016 if (StmtMapIt == StmtMap.end())
5017 return {};
5018 assert(StmtMapIt->second.size() == 1 &&
5019 "Each statement corresponds to exactly one BB.");
5020 return StmtMapIt->second;
5021}
5022
5023ScopStmt *Scop::getLastStmtFor(BasicBlock *BB) const {
5024 ArrayRef<ScopStmt *> StmtList = getStmtListFor(BB);
5025 if (StmtList.size() > 0)
5026 return StmtList.back();
5027 return nullptr;
5028}
5029
Michael Kruse1ce67912017-07-20 17:18:58 +00005030ArrayRef<ScopStmt *> Scop::getStmtListFor(RegionNode *RN) const {
Michael Kruse6f7721f2016-02-24 22:08:19 +00005031 if (RN->isSubRegion())
Michael Kruse1ce67912017-07-20 17:18:58 +00005032 return getStmtListFor(RN->getNodeAs<Region>());
5033 return getStmtListFor(RN->getNodeAs<BasicBlock>());
Michael Kruse6f7721f2016-02-24 22:08:19 +00005034}
5035
Michael Kruse1ce67912017-07-20 17:18:58 +00005036ArrayRef<ScopStmt *> Scop::getStmtListFor(Region *R) const {
5037 return getStmtListFor(R->getEntry());
Michael Krusea902ba62015-12-13 19:21:45 +00005038}
5039
Johannes Doerfert96425c22015-08-30 21:13:53 +00005040int Scop::getRelativeLoopDepth(const Loop *L) const {
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00005041 if (!L || !R.contains(L))
Johannes Doerfert96425c22015-08-30 21:13:53 +00005042 return -1;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00005043 // outermostLoopInRegion always returns nullptr for top level regions
5044 if (R.isTopLevelRegion()) {
5045 // LoopInfo's depths start at 1, we start at 0
5046 return L->getLoopDepth() - 1;
5047 } else {
5048 Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
5049 assert(OuterLoop);
5050 return L->getLoopDepth() - OuterLoop->getLoopDepth();
5051 }
Johannes Doerfertd020b772015-08-27 06:53:52 +00005052}
5053
Roman Gareevd7754a12016-07-30 09:25:51 +00005054ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
5055 for (auto &SAI : arrays()) {
5056 if (SAI->getName() == BaseName)
5057 return SAI;
5058 }
5059 return nullptr;
5060}
5061
Michael Kruse8b805802017-07-19 17:11:25 +00005062void Scop::addAccessData(MemoryAccess *Access) {
5063 const ScopArrayInfo *SAI = Access->getOriginalScopArrayInfo();
5064 assert(SAI && "can only use after access relations have been constructed");
5065
5066 if (Access->isOriginalValueKind() && Access->isRead())
5067 ValueUseAccs[SAI].push_back(Access);
5068 else if (Access->isOriginalAnyPHIKind() && Access->isWrite())
5069 PHIIncomingAccs[SAI].push_back(Access);
5070}
5071
5072void Scop::removeAccessData(MemoryAccess *Access) {
5073 if (Access->isOriginalValueKind() && Access->isRead()) {
5074 auto &Uses = ValueUseAccs[Access->getScopArrayInfo()];
5075 std::remove(Uses.begin(), Uses.end(), Access);
5076 } else if (Access->isOriginalAnyPHIKind() && Access->isWrite()) {
5077 auto &Incomings = PHIIncomingAccs[Access->getScopArrayInfo()];
5078 std::remove(Incomings.begin(), Incomings.end(), Access);
5079 }
5080}
5081
5082MemoryAccess *Scop::getValueDef(const ScopArrayInfo *SAI) const {
5083 assert(SAI->isValueKind());
5084
5085 Instruction *Val = dyn_cast<Instruction>(SAI->getBasePtr());
5086 if (!Val)
5087 return nullptr;
5088
5089 ScopStmt *Stmt = getStmtFor(Val);
5090 if (!Stmt)
5091 return nullptr;
5092
5093 return Stmt->lookupValueWriteOf(Val);
5094}
5095
5096ArrayRef<MemoryAccess *> Scop::getValueUses(const ScopArrayInfo *SAI) const {
5097 assert(SAI->isValueKind());
5098 auto It = ValueUseAccs.find(SAI);
5099 if (It == ValueUseAccs.end())
5100 return {};
5101 return It->second;
5102}
5103
5104MemoryAccess *Scop::getPHIRead(const ScopArrayInfo *SAI) const {
5105 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
5106
5107 if (SAI->isExitPHIKind())
5108 return nullptr;
5109
5110 PHINode *PHI = cast<PHINode>(SAI->getBasePtr());
5111 ScopStmt *Stmt = getStmtFor(PHI);
5112 assert(Stmt && "PHINode must be within the SCoP");
5113
5114 return Stmt->lookupPHIReadOf(PHI);
5115}
5116
5117ArrayRef<MemoryAccess *> Scop::getPHIIncomings(const ScopArrayInfo *SAI) const {
5118 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
5119 auto It = PHIIncomingAccs.find(SAI);
5120 if (It == PHIIncomingAccs.end())
5121 return {};
5122 return It->second;
5123}
5124
Michael Krusecd4c9772017-07-21 15:35:53 +00005125raw_ostream &polly::operator<<(raw_ostream &O, const Scop &scop) {
5126 scop.print(O, PollyPrintInstructions);
5127 return O;
5128}
5129
Johannes Doerfert99191c72016-05-31 09:41:04 +00005130//===----------------------------------------------------------------------===//
5131void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
5132 AU.addRequired<LoopInfoWrapperPass>();
5133 AU.addRequired<RegionInfoPass>();
5134 AU.addRequired<DominatorTreeWrapperPass>();
5135 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005136 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005137 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005138 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005139 AU.setPreservesAll();
5140}
5141
Tobias Grossercd01a362017-02-17 08:12:36 +00005142void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
5143 NumLoopsInScop += Stats.NumLoops;
5144 MaxNumLoopsInScop =
5145 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
5146
Tobias Grossercd01a362017-02-17 08:12:36 +00005147 if (Stats.MaxDepth == 1)
5148 NumScopsDepthOne++;
5149 else if (Stats.MaxDepth == 2)
5150 NumScopsDepthTwo++;
5151 else if (Stats.MaxDepth == 3)
5152 NumScopsDepthThree++;
5153 else if (Stats.MaxDepth == 4)
5154 NumScopsDepthFour++;
5155 else if (Stats.MaxDepth == 5)
5156 NumScopsDepthFive++;
5157 else
5158 NumScopsDepthLarger++;
5159}
5160
Johannes Doerfert99191c72016-05-31 09:41:04 +00005161bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005162 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005163
5164 if (!SD.isMaxRegionInScop(*R))
5165 return false;
5166
5167 Function *F = R->getEntry()->getParent();
5168 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5169 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5170 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5171 auto const &DL = F->getParent()->getDataLayout();
5172 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005173 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005174
Michael Kruse89b1f942017-03-17 13:56:53 +00005175 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005176 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00005177
5178 if (S) {
5179 ScopDetection::LoopStats Stats =
5180 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
5181 updateLoopCountStatistic(Stats);
5182 }
5183
Tobias Grosser75805372011-04-29 06:27:02 +00005184 return false;
5185}
5186
Johannes Doerfert99191c72016-05-31 09:41:04 +00005187void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005188 if (S)
Michael Krusecd4c9772017-07-21 15:35:53 +00005189 S->print(OS, PollyPrintInstructions);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005190 else
5191 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00005192}
Tobias Grosser75805372011-04-29 06:27:02 +00005193
Johannes Doerfert99191c72016-05-31 09:41:04 +00005194char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005195
Johannes Doerfert99191c72016-05-31 09:41:04 +00005196Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
5197
5198INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005199 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005200 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00005201INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005202INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00005203INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00005204INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00005205INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005206INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00005207INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005208INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005209 "Polly - Create polyhedral description of Scops", false,
5210 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005211
5212//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00005213ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
5214 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
5215 AssumptionCache &AC) {
Michael Krusea6d48f52017-06-08 12:06:15 +00005216 /// Create polyhedral description of scops for all the valid regions of a
Philip Pfaffe838e0882017-05-15 12:55:14 +00005217 /// function.
5218 for (auto &It : SD) {
5219 Region *R = const_cast<Region *>(It);
5220 if (!SD.isMaxRegionInScop(*R))
5221 continue;
5222
5223 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
5224 std::unique_ptr<Scop> S = SB.getScop();
5225 if (!S)
5226 continue;
5227 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
5228 assert(Inserted && "Building Scop for the same region twice!");
5229 (void)Inserted;
5230 }
5231}
5232
5233AnalysisKey ScopInfoAnalysis::Key;
5234
5235ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
5236 FunctionAnalysisManager &FAM) {
5237 auto &SD = FAM.getResult<ScopAnalysis>(F);
5238 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
5239 auto &LI = FAM.getResult<LoopAnalysis>(F);
5240 auto &AA = FAM.getResult<AAManager>(F);
5241 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
5242 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
5243 auto &DL = F.getParent()->getDataLayout();
5244 return {DL, SD, SE, LI, AA, DT, AC};
5245}
5246
5247PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
5248 FunctionAnalysisManager &FAM) {
5249 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
5250 for (auto &It : SI) {
5251 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005252 It.second->print(Stream, PollyPrintInstructions);
Philip Pfaffe838e0882017-05-15 12:55:14 +00005253 else
5254 Stream << "Invalid Scop!\n";
5255 }
5256 return PreservedAnalyses::all();
5257}
5258
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005259void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
5260 AU.addRequired<LoopInfoWrapperPass>();
5261 AU.addRequired<RegionInfoPass>();
5262 AU.addRequired<DominatorTreeWrapperPass>();
5263 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005264 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005265 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005266 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005267 AU.setPreservesAll();
5268}
5269
5270bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005271 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005272 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5273 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5274 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5275 auto const &DL = F.getParent()->getDataLayout();
5276 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005277 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005278
Philip Pfaffe838e0882017-05-15 12:55:14 +00005279 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005280 return false;
5281}
5282
5283void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005284 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005285 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005286 It.second->print(OS, PollyPrintInstructions);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005287 else
5288 OS << "Invalid Scop!\n";
5289 }
5290}
5291
5292char ScopInfoWrapperPass::ID = 0;
5293
5294Pass *polly::createScopInfoWrapperPassPass() {
5295 return new ScopInfoWrapperPass();
5296}
5297
5298INITIALIZE_PASS_BEGIN(
5299 ScopInfoWrapperPass, "polly-function-scops",
5300 "Polly - Create polyhedral description of all Scops of a function", false,
5301 false);
5302INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005303INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005304INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5305INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5306INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005307INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005308INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5309INITIALIZE_PASS_END(
5310 ScopInfoWrapperPass, "polly-function-scops",
5311 "Polly - Create polyhedral description of all Scops of a function", false,
5312 false)