blob: 6defb4f1bb97058462f54c2d31acb8854b152368 [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 {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000646 isl::id ArrayId = getArrayId();
647 void *User = ArrayId.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000648 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000649 return SAI;
650}
651
Michael Kruse2fa35192016-09-01 19:53:31 +0000652const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000653 isl::id ArrayId = getLatestArrayId();
654 void *User = ArrayId.get_user();
Michael Kruse2fa35192016-09-01 19:53:31 +0000655 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Michael Kruse2fa35192016-09-01 19:53:31 +0000656 return SAI;
657}
658
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000659isl::id MemoryAccess::getOriginalArrayId() const {
660 return AccessRelation.get_tuple_id(isl::dim::out);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000661}
662
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000663isl::id MemoryAccess::getLatestArrayId() const {
Michael Kruse2fa35192016-09-01 19:53:31 +0000664 if (!hasNewAccessRelation())
665 return getOriginalArrayId();
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000666 return NewAccessRelation.get_tuple_id(isl::dim::out);
Michael Kruse2fa35192016-09-01 19:53:31 +0000667}
668
Tobias Grosser6a870362017-07-23 04:08:45 +0000669isl::map MemoryAccess::getAddressFunction() const {
670 return getAccessRelation().lexmin();
Tobias Grosserd840fc72016-02-04 13:18:42 +0000671}
672
Tobias Grosser3b196132017-07-23 04:08:52 +0000673isl::pw_multi_aff
674MemoryAccess::applyScheduleToAccessRelation(isl::union_map USchedule) const {
675 isl::map Schedule, ScheduledAccRel;
676 isl::union_set UDomain;
Johannes Doerferta99130f2014-10-13 12:58:03 +0000677
Tobias Grosser3b196132017-07-23 04:08:52 +0000678 UDomain = isl::manage(getStatement()->getDomain());
679 USchedule = USchedule.intersect_domain(UDomain);
680 Schedule = isl::map::from_union_map(USchedule);
681 ScheduledAccRel = getAddressFunction().apply_domain(Schedule);
682 return isl::pw_multi_aff::from_map(ScheduledAccRel);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000683}
684
Tobias Grosser22da5f02017-07-23 04:08:27 +0000685isl::map MemoryAccess::getOriginalAccessRelation() const {
686 return AccessRelation;
Tobias Grosser5d453812011-10-06 00:04:11 +0000687}
688
Johannes Doerferta99130f2014-10-13 12:58:03 +0000689std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000690 return stringFromIslObj(AccessRelation.get());
Tobias Grosser5d453812011-10-06 00:04:11 +0000691}
692
Tobias Grosser22da5f02017-07-23 04:08:27 +0000693isl::space MemoryAccess::getOriginalAccessRelationSpace() const {
694 return AccessRelation.get_space();
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000695}
696
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000697isl::map MemoryAccess::getNewAccessRelation() const {
698 return NewAccessRelation;
Tobias Grosser75805372011-04-29 06:27:02 +0000699}
700
Tobias Grosser6f730082015-09-05 07:46:47 +0000701std::string MemoryAccess::getNewAccessRelationStr() const {
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000702 return stringFromIslObj(NewAccessRelation.get());
Tobias Grosser6f730082015-09-05 07:46:47 +0000703}
704
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000705std::string MemoryAccess::getAccessRelationStr() const {
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000706 return isl::manage(getAccessRelation().get()).to_str();
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000707}
708
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000709isl::basic_map MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
710 isl::space Space = isl::space(Statement->getIslCtx(), 0, 1);
711 Space = Space.align_params(isl::manage(Statement->getDomainSpace()));
Tobias Grosser75805372011-04-29 06:27:02 +0000712
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000713 return isl::basic_map::from_domain_and_range(
714 isl::basic_set::universe(isl::manage(Statement->getDomainSpace())),
715 isl::basic_set::universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000716}
717
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000718// Formalize no out-of-bound access assumption
719//
720// When delinearizing array accesses we optimistically assume that the
721// delinearized accesses do not access out of bound locations (the subscript
722// expression of each array evaluates for each statement instance that is
723// executed to a value that is larger than zero and strictly smaller than the
724// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000725// dimension for which we do not need to assume any upper bound. At this point
726// we formalize this assumption to ensure that at code generation time the
727// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000728//
729// To find the set of constraints necessary to avoid out of bound accesses, we
730// first build the set of data locations that are not within array bounds. We
731// then apply the reverse access relation to obtain the set of iterations that
732// may contain invalid accesses and reduce this set of iterations to the ones
733// that are actually executed by intersecting them with the domain of the
734// statement. If we now project out all loop dimensions, we obtain a set of
735// parameters that may cause statement instances to be executed that may
736// possibly yield out of bound memory accesses. The complement of these
737// constraints is the set of constraints that needs to be assumed to ensure such
738// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000739void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000740 if (PollyIgnoreInbounds)
741 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000742 auto *SAI = getScopArrayInfo();
Tobias Grosser22da5f02017-07-23 04:08:27 +0000743 isl::space Space = getOriginalAccessRelationSpace().range();
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000744 isl::set Outside = isl::set::empty(Space);
745 for (int i = 1, Size = Space.dim(isl::dim::set); i < Size; ++i) {
746 isl::local_space LS(Space);
747 isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
748 isl::pw_aff Zero = isl::pw_aff(LS);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000749
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000750 isl::set DimOutside = Var.lt_set(Zero);
Tobias Grosser77eef902017-07-21 23:07:56 +0000751 isl::pw_aff SizeE = SAI->getDimensionSizePw(i);
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000752 SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set));
753 SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
754 DimOutside = DimOutside.unite(SizeE.le_set(Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000755
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000756 Outside = Outside.unite(DimOutside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000757 }
758
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000759 Outside = Outside.apply(getAccessRelation().reverse());
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000760 Outside = Outside.intersect(give(Statement->getDomain()));
761 Outside = Outside.params();
Tobias Grosserf54bb772015-06-26 12:09:28 +0000762
763 // Remove divs to avoid the construction of overly complicated assumptions.
764 // Doing so increases the set of parameter combinations that are assumed to
765 // not appear. This is always save, but may make the resulting run-time check
766 // bail out more often than strictly necessary.
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000767 Outside = Outside.remove_divs();
768 Outside = Outside.complement();
Michael Kruse7071e8b2016-04-11 13:24:29 +0000769 const auto &Loc = getAccessInstruction()
770 ? getAccessInstruction()->getDebugLoc()
771 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000772 if (!PollyPreciseInbounds)
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000773 Outside = Outside.gist_params(give(Statement->getDomain()).params());
774 Statement->getParent()->recordAssumption(INBOUNDS, Outside.release(), Loc,
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000775 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000776}
777
Johannes Doerfertcea61932016-02-21 19:13:19 +0000778void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000779 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000780 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000781
Tobias Grosser53fc3552017-05-23 07:07:09 +0000782 isl::pw_aff SubscriptPWA = give(getPwAff(Subscripts[0]));
783 isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000784
Tobias Grosser53fc3552017-05-23 07:07:09 +0000785 isl::map LengthMap;
Johannes Doerferta7920982016-02-25 14:08:48 +0000786 if (Subscripts[1] == nullptr) {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000787 LengthMap = isl::map::universe(SubscriptMap.get_space());
Johannes Doerferta7920982016-02-25 14:08:48 +0000788 } else {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000789 isl::pw_aff LengthPWA = give(getPwAff(Subscripts[1]));
790 LengthMap = isl::map::from_pw_aff(LengthPWA);
791 isl::space RangeSpace = LengthMap.get_space().range();
792 LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
Johannes Doerferta7920982016-02-25 14:08:48 +0000793 }
Tobias Grosser53fc3552017-05-23 07:07:09 +0000794 LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
795 LengthMap = LengthMap.align_params(SubscriptMap.get_space());
796 SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
797 LengthMap = LengthMap.sum(SubscriptMap);
798 AccessRelation =
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000799 LengthMap.set_tuple_id(isl::dim::in, give(getStatement()->getDomainId()));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000800}
801
Johannes Doerferte7044942015-02-24 11:58:30 +0000802void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
803 ScalarEvolution *SE = Statement->getParent()->getSE();
804
Johannes Doerfertcea61932016-02-21 19:13:19 +0000805 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000806 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000807 return;
808
809 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000810 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
811 return;
812
813 auto *PtrSCEV = SE->getSCEV(Ptr);
814 if (isa<SCEVCouldNotCompute>(PtrSCEV))
815 return;
816
817 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
818 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
819 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
820
821 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
822 if (Range.isFullSet())
823 return;
824
Michael Kruse960c0d02017-05-18 21:55:36 +0000825 if (Range.isWrappedSet() || Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000826 return;
827
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000828 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000829
Johannes Doerferte7044942015-02-24 11:58:30 +0000830 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000831 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000832 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000833 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000834
835 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000836 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000837
Tobias Grosserb3a85882017-02-12 08:11:12 +0000838 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
839
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000840 isl::map Relation = AccessRelation;
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000841 isl::set AccessRange = Relation.range();
842 AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
843 isl::dim::set);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000844 AccessRelation = Relation.intersect_range(AccessRange);
Johannes Doerferte7044942015-02-24 11:58:30 +0000845}
846
Tobias Grosser491b7992016-12-02 05:21:22 +0000847void MemoryAccess::foldAccessRelation() {
848 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
849 return;
850
Michael Krusee2bccbb2015-09-18 19:59:43 +0000851 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000852
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000853 isl::map NewAccessRelation = AccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000854
Tobias Grosser619190d2015-03-30 17:22:28 +0000855 for (int i = Size - 2; i >= 0; --i) {
Tobias Grossera32de132017-05-23 07:22:56 +0000856 isl::space Space;
857 isl::map MapOne, MapTwo;
858 isl::pw_aff DimSize = give(getPwAff(Sizes[i + 1]));
Tobias Grosser619190d2015-03-30 17:22:28 +0000859
Tobias Grossera32de132017-05-23 07:22:56 +0000860 isl::space SpaceSize = DimSize.get_space();
861 isl::id ParamId =
862 give(isl_space_get_dim_id(SpaceSize.get(), isl_dim_param, 0));
Tobias Grosser619190d2015-03-30 17:22:28 +0000863
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000864 Space = AccessRelation.get_space();
Tobias Grossera32de132017-05-23 07:22:56 +0000865 Space = Space.range().map_from_set();
866 Space = Space.align_params(SpaceSize);
Tobias Grosser619190d2015-03-30 17:22:28 +0000867
Tobias Grossera32de132017-05-23 07:22:56 +0000868 int ParamLocation = Space.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosser619190d2015-03-30 17:22:28 +0000869
Tobias Grossera32de132017-05-23 07:22:56 +0000870 MapOne = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000871 for (int j = 0; j < Size; ++j)
Tobias Grossera32de132017-05-23 07:22:56 +0000872 MapOne = MapOne.equate(isl::dim::in, j, isl::dim::out, j);
873 MapOne = MapOne.lower_bound_si(isl::dim::in, i + 1, 0);
Tobias Grosser619190d2015-03-30 17:22:28 +0000874
Tobias Grossera32de132017-05-23 07:22:56 +0000875 MapTwo = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000876 for (int j = 0; j < Size; ++j)
877 if (j < i || j > i + 1)
Tobias Grossera32de132017-05-23 07:22:56 +0000878 MapTwo = MapTwo.equate(isl::dim::in, j, isl::dim::out, j);
Tobias Grosser619190d2015-03-30 17:22:28 +0000879
Tobias Grossera32de132017-05-23 07:22:56 +0000880 isl::local_space LS(Space);
881 isl::constraint C;
882 C = isl::constraint::alloc_equality(LS);
883 C = C.set_constant_si(-1);
884 C = C.set_coefficient_si(isl::dim::in, i, 1);
885 C = C.set_coefficient_si(isl::dim::out, i, -1);
886 MapTwo = MapTwo.add_constraint(C);
887 C = isl::constraint::alloc_equality(LS);
888 C = C.set_coefficient_si(isl::dim::in, i + 1, 1);
889 C = C.set_coefficient_si(isl::dim::out, i + 1, -1);
890 C = C.set_coefficient_si(isl::dim::param, ParamLocation, 1);
891 MapTwo = MapTwo.add_constraint(C);
892 MapTwo = MapTwo.upper_bound_si(isl::dim::in, i + 1, -1);
Tobias Grosser619190d2015-03-30 17:22:28 +0000893
Tobias Grossera32de132017-05-23 07:22:56 +0000894 MapOne = MapOne.unite(MapTwo);
895 NewAccessRelation = NewAccessRelation.apply_range(MapOne);
Tobias Grosser619190d2015-03-30 17:22:28 +0000896 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000897
Tobias Grosser77eef902017-07-21 23:07:56 +0000898 isl::id BaseAddrId = getScopArrayInfo()->getBasePtrId();
Tobias Grossera32de132017-05-23 07:22:56 +0000899 isl::space Space = give(Statement->getDomainSpace());
900 NewAccessRelation = NewAccessRelation.set_tuple_id(
901 isl::dim::in, Space.get_tuple_id(isl::dim::set));
902 NewAccessRelation = NewAccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
903 NewAccessRelation =
904 NewAccessRelation.gist_domain(give(Statement->getDomain()));
Tobias Grosserc2f15102017-03-01 21:11:27 +0000905
906 // Access dimension folding might in certain cases increase the number of
907 // disjuncts in the memory access, which can possibly complicate the generated
908 // run-time checks and can lead to costly compilation.
Tobias Grossera32de132017-05-23 07:22:56 +0000909 if (!PollyPreciseFoldAccesses &&
910 isl_map_n_basic_map(NewAccessRelation.get()) >
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000911 isl_map_n_basic_map(AccessRelation.get())) {
Tobias Grosserc2f15102017-03-01 21:11:27 +0000912 } else {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000913 AccessRelation = NewAccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000914 }
Tobias Grosser619190d2015-03-30 17:22:28 +0000915}
916
Tobias Grosserc80d6972016-09-02 06:33:33 +0000917/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000918static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000919 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000920 if (Size == 1)
921 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000922
923 // Only one factor needs to be divisible.
924 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
925 for (auto *FactorExpr : MulExpr->operands())
926 if (isDivisible(FactorExpr, Size, SE))
927 return true;
928 return false;
929 }
930
931 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
Michael Krusea6d48f52017-06-08 12:06:15 +0000932 // to be divisible.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000933 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
934 for (auto *OpExpr : NAryExpr->operands())
935 if (!isDivisible(OpExpr, Size, SE))
936 return false;
937 return true;
938 }
939
940 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
941 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
942 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
943 return MulSCEV == Expr;
944}
945
Michael Krusee2bccbb2015-09-18 19:59:43 +0000946void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000947 assert(AccessRelation.is_null() && "AccessRelation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000948
Johannes Doerfert85676e32016-04-23 14:32:34 +0000949 // Initialize the invalid domain which describes all iterations for which the
950 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000951 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
952 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
953 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000954
Tobias Grosserfe46c3f2017-07-23 04:08:11 +0000955 isl_ctx *Ctx = Id.get_ctx().release();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000956 isl::id BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000957
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000958 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
959 buildMemIntrinsicAccessRelation();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000960 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000961 return;
962 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000963
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000964 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000965 // We overapproximate non-affine accesses with a possible access to the
966 // whole array. For read accesses it does not make a difference, if an
967 // access must or may happen. However, for write accesses it is important to
968 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000969 if (AccessRelation.is_null())
970 AccessRelation = createBasicAccessMap(Statement);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000971
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000972 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000973 return;
974 }
975
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000976 isl::space Space = isl::space(Ctx, 0, Statement->getNumIterators(), 0);
977 AccessRelation = isl::map::universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000978
Michael Krusee2bccbb2015-09-18 19:59:43 +0000979 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000980 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000981 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000982 AccessRelation =
983 AccessRelation.flat_range_product(isl::manage(SubscriptMap));
Sebastian Pop18016682014-04-08 21:20:44 +0000984 }
985
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000986 Space = isl::manage(Statement->getDomainSpace());
987 AccessRelation = AccessRelation.set_tuple_id(
988 isl::dim::in, Space.get_tuple_id(isl::dim::set));
989 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000990
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000991 AccessRelation =
992 AccessRelation.gist_domain(isl::manage(Statement->getDomain()));
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000993}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000994
Michael Krusecac948e2015-10-02 13:53:07 +0000995MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000996 AccessType AccType, Value *BaseAddress,
997 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000998 ArrayRef<const SCEV *> Subscripts,
999 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +00001000 MemoryKind Kind)
Johannes Doerfertcea61932016-02-21 19:13:19 +00001001 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Tobias Grosser81331282017-05-03 07:57:35 +00001002 InvalidDomain(nullptr), BaseAddr(BaseAddress), ElementType(ElementType),
1003 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
1004 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +00001005 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001006 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +00001007 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001008 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001009
Tobias Grosser81331282017-05-03 07:57:35 +00001010 std::string IdName = Stmt->getBaseName() + Access;
Tobias Grosserfe46c3f2017-07-23 04:08:11 +00001011 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001012}
Michael Krusee2bccbb2015-09-18 19:59:43 +00001013
Roman Gareevb3224ad2016-09-14 06:26:09 +00001014MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
1015 __isl_take isl_map *AccRel)
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001016 : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
1017 Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001018 IsAffine(true), AccessRelation(nullptr),
1019 NewAccessRelation(isl::manage(AccRel)), FAD(nullptr) {
1020 auto *ArrayInfoId = NewAccessRelation.get_tuple_id(isl::dim::out).release();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001021 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1022 Sizes.push_back(nullptr);
1023 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1024 Sizes.push_back(SAI->getDimensionSize(i));
1025 ElementType = SAI->getElementType();
1026 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001027 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001028 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001029
Tobias Grosser81331282017-05-03 07:57:35 +00001030 std::string IdName = Stmt->getBaseName() + Access;
Tobias Grosserfe46c3f2017-07-23 04:08:11 +00001031 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001032}
1033
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001034void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +00001035 auto *Ctx = Statement->getParent()->getContext();
1036 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001037 AccessRelation = AccessRelation.gist_params(isl::manage(Ctx));
Tobias Grosser75805372011-04-29 06:27:02 +00001038}
1039
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001040const std::string MemoryAccess::getReductionOperatorStr() const {
1041 return MemoryAccess::getReductionOperatorStr(getReductionType());
1042}
1043
Tobias Grosserfe46c3f2017-07-23 04:08:11 +00001044isl::id MemoryAccess::getId() const { return Id; }
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001045
Johannes Doerfertf6183392014-07-01 20:52:51 +00001046raw_ostream &polly::operator<<(raw_ostream &OS,
1047 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001048 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001049 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001050 else
1051 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001052 return OS;
1053}
1054
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001055void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001056
Tobias Grosser75805372011-04-29 06:27:02 +00001057void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001058 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001059 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001060 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001061 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001062 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001063 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001064 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001065 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001066 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001067 break;
1068 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001069
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001070 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001071
1072 if (FAD) {
1073 OS << "[Fortran array descriptor: " << FAD->getName();
1074 OS << "] ";
1075 };
1076
Tobias Grossera535dff2015-12-13 19:59:01 +00001077 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001078 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001079 if (hasNewAccessRelation())
1080 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001081}
1082
Michael Kruse5d518462017-07-21 15:54:07 +00001083#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001084LLVM_DUMP_METHOD void MemoryAccess::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +00001085#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001086
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001087__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
1088 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001089 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +00001090 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
1091 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
1092 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +00001093 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001094}
1095
Tobias Grosser75805372011-04-29 06:27:02 +00001096// Create a map in the size of the provided set domain, that maps from the
1097// one element of the provided set domain to another element of the provided
1098// set domain.
1099// The mapping is limited to all points that are equal in all but the last
1100// dimension and for which the last dimension of the input is strict smaller
1101// than the last dimension of the output.
1102//
1103// getEqualAndLarger(set[i0, i1, ..., iX]):
1104//
1105// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1106// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1107//
Tobias Grosser2a526fe2016-09-08 11:18:56 +00001108static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +00001109 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001110 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +00001111 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001112
1113 // Set all but the last dimension to be equal for the input and output
1114 //
1115 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1116 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001117 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +00001118 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001119
1120 // Set the last dimension of the input to be strict smaller than the
1121 // last dimension of the output.
1122 //
1123 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001124 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1125 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001126 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001127}
1128
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001129__isl_give isl_set *
1130MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001131 isl_map *S = const_cast<isl_map *>(Schedule);
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001132 isl_map *AccessRelation = getAccessRelation().release();
Sebastian Popa00a0292012-12-18 07:46:06 +00001133 isl_space *Space = isl_space_range(isl_map_get_space(S));
1134 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001135
Sebastian Popa00a0292012-12-18 07:46:06 +00001136 S = isl_map_reverse(S);
1137 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001138
Sebastian Popa00a0292012-12-18 07:46:06 +00001139 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1140 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1141 NextScatt = isl_map_apply_domain(NextScatt, S);
1142 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001143
Sebastian Popa00a0292012-12-18 07:46:06 +00001144 isl_set *Deltas = isl_map_deltas(NextScatt);
1145 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001146}
1147
Sebastian Popa00a0292012-12-18 07:46:06 +00001148bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001149 int StrideWidth) const {
1150 isl_set *Stride, *StrideX;
1151 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001152
Sebastian Popa00a0292012-12-18 07:46:06 +00001153 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001154 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001155 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1156 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1157 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1158 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001159 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001160
Tobias Grosser28dd4862012-01-24 16:42:16 +00001161 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001162 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001163
Tobias Grosser28dd4862012-01-24 16:42:16 +00001164 return IsStrideX;
1165}
1166
Michael Krused56b90a2016-09-01 09:03:27 +00001167bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001168 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001169}
1170
Michael Krused56b90a2016-09-01 09:03:27 +00001171bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001172 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001173}
1174
Tobias Grosserbedef002016-12-02 08:10:56 +00001175void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001176 AccessRelation = isl::manage(NewAccess);
Tobias Grosserbedef002016-12-02 08:10:56 +00001177}
1178
Michael Krused56b90a2016-09-01 09:03:27 +00001179void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001180 assert(NewAccess);
1181
1182#ifndef NDEBUG
1183 // Check domain space compatibility.
1184 auto *NewSpace = isl_map_get_space(NewAccess);
1185 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1186 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1187 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1188 isl_space_free(NewDomainSpace);
1189 isl_space_free(OriginalDomainSpace);
1190
Michael Kruse706f79a2017-05-21 22:46:57 +00001191 // Reads must be executed unconditionally. Writes might be executed in a
1192 // subdomain only.
1193 if (isRead()) {
1194 // Check whether there is an access for every statement instance.
1195 auto *StmtDomain = getStatement()->getDomain();
1196 StmtDomain = isl_set_intersect_params(
1197 StmtDomain, getStatement()->getParent()->getContext());
1198 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1199 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1200 "Partial READ accesses not supported");
1201 isl_set_free(NewDomain);
1202 isl_set_free(StmtDomain);
1203 }
Michael Kruse772ce722016-09-01 19:16:58 +00001204
Michael Kruse772ce722016-09-01 19:16:58 +00001205 auto *NewAccessSpace = isl_space_range(NewSpace);
1206 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1207 "Must specify the array that is accessed");
1208 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1209 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1210 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001211
1212 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1213 InvariantEquivClassTy *EqClass =
1214 getStatement()->getParent()->lookupInvariantEquivClass(
1215 SAI->getBasePtr());
1216 assert(EqClass &&
1217 "Access functions to indirect arrays must have an invariant and "
1218 "hoisted base pointer");
1219 }
1220
1221 // Check whether access dimensions correspond to number of dimensions of the
1222 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001223 auto Dims = SAI->getNumberOfDimensions();
1224 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1225 "Access dims must match array dims");
1226 isl_space_free(NewAccessSpace);
1227 isl_id_free(NewArrayId);
1228#endif
1229
Tobias Grosser4556c9b2017-07-17 20:47:10 +00001230 NewAccess = isl_map_gist_domain(NewAccess, getStatement()->getDomain());
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001231 NewAccessRelation = isl::manage(NewAccess);
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001232}
Tobias Grosser75805372011-04-29 06:27:02 +00001233
Michael Kruse706f79a2017-05-21 22:46:57 +00001234bool MemoryAccess::isLatestPartialAccess() const {
1235 isl::set StmtDom = give(getStatement()->getDomain());
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001236 isl::set AccDom = getLatestAccessRelation().domain();
Michael Kruse706f79a2017-05-21 22:46:57 +00001237
1238 return isl_set_is_subset(StmtDom.keep(), AccDom.keep()) == isl_bool_false;
1239}
1240
Tobias Grosser75805372011-04-29 06:27:02 +00001241//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001242
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001243__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001244 isl_set *Domain = getDomain();
1245 if (isl_set_is_empty(Domain)) {
1246 isl_set_free(Domain);
1247 return isl_map_from_aff(
1248 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1249 }
1250 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001251 if (!Schedule) {
1252 isl_set_free(Domain);
1253 return nullptr;
1254 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001255 Schedule = isl_union_map_intersect_domain(
1256 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1257 if (isl_union_map_is_empty(Schedule)) {
1258 isl_set_free(Domain);
1259 isl_union_map_free(Schedule);
1260 return isl_map_from_aff(
1261 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1262 }
1263 auto *M = isl_map_from_union_map(Schedule);
1264 M = isl_map_coalesce(M);
1265 M = isl_map_gist_domain(M, Domain);
1266 M = isl_map_coalesce(M);
1267 return M;
1268}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001269
Tobias Grosser37eb4222014-02-20 21:43:54 +00001270void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1271 assert(isl_set_is_subset(NewDomain, Domain) &&
1272 "New domain is not a subset of old domain!");
1273 isl_set_free(Domain);
1274 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001275}
1276
Michael Krusecac948e2015-10-02 13:53:07 +00001277void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001278 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001279 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001280 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001281
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001282 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001283 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001284 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001285 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001286 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001287 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001288 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001289 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001290 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001291
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001292 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1293 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001294 Access->buildAccessRelation(SAI);
Michael Kruse8b805802017-07-19 17:11:25 +00001295 S.addAccessData(Access);
Tobias Grosser75805372011-04-29 06:27:02 +00001296 }
1297}
1298
Michael Krusecac948e2015-10-02 13:53:07 +00001299void ScopStmt::addAccess(MemoryAccess *Access) {
1300 Instruction *AccessInst = Access->getAccessInstruction();
1301
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001302 if (Access->isArrayKind()) {
1303 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1304 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001305 } else if (Access->isValueKind() && Access->isWrite()) {
1306 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001307 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001308 assert(!ValueWrites.lookup(AccessVal));
1309
1310 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001311 } else if (Access->isValueKind() && Access->isRead()) {
1312 Value *AccessVal = Access->getAccessValue();
1313 assert(!ValueReads.lookup(AccessVal));
1314
1315 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001316 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001317 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001318 assert(!PHIWrites.lookup(PHI));
1319
1320 PHIWrites[PHI] = Access;
Michael Kruse3562f272017-07-20 16:47:57 +00001321 } else if (Access->isAnyPHIKind() && Access->isRead()) {
1322 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1323 assert(!PHIReads.lookup(PHI));
1324
1325 PHIReads[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001326 }
1327
1328 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001329}
1330
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001331void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001332 for (MemoryAccess *MA : *this)
1333 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001334
Johannes Doerferta60ad842016-05-10 12:18:22 +00001335 auto *Ctx = Parent.getContext();
1336 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1337 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001338}
1339
Tobias Grosserc80d6972016-09-02 06:33:33 +00001340/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001341static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1342 void *User) {
1343 isl_set **BoundedParts = static_cast<isl_set **>(User);
1344 if (isl_basic_set_is_bounded(BSet))
1345 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1346 else
1347 isl_basic_set_free(BSet);
1348 return isl_stat_ok;
1349}
1350
Tobias Grosserc80d6972016-09-02 06:33:33 +00001351/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001352static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1353 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1354 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1355 isl_set_free(S);
1356 return BoundedParts;
1357}
1358
Tobias Grosserc80d6972016-09-02 06:33:33 +00001359/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001360///
1361/// @returns A separation of @p S into first an unbounded then a bounded subset,
1362/// both with regards to the dimension @p Dim.
1363static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1364partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1365
1366 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001367 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001368
1369 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001370 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001371
1372 // Remove dimensions that are greater than Dim as they are not interesting.
1373 assert(NumDimsS >= Dim + 1);
1374 OnlyDimS =
1375 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1376
1377 // Create artificial parametric upper bounds for dimensions smaller than Dim
1378 // as we are not interested in them.
1379 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1380 for (unsigned u = 0; u < Dim; u++) {
1381 isl_constraint *C = isl_inequality_alloc(
1382 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1383 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1384 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1385 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1386 }
1387
1388 // Collect all bounded parts of OnlyDimS.
1389 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1390
1391 // Create the dimensions greater than Dim again.
1392 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1393 NumDimsS - Dim - 1);
1394
1395 // Remove the artificial upper bound parameters again.
1396 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1397
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001398 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001399 return std::make_pair(UnboundedParts, BoundedParts);
1400}
1401
Tobias Grosserc80d6972016-09-02 06:33:33 +00001402/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001403static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1404 __isl_take isl_set *To) {
1405 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1406 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1407 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1408 }
1409 return To;
1410}
1411
Tobias Grosserc80d6972016-09-02 06:33:33 +00001412/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001413static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001414 __isl_take isl_pw_aff *L,
1415 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001416 switch (Pred) {
1417 case ICmpInst::ICMP_EQ:
1418 return isl_pw_aff_eq_set(L, R);
1419 case ICmpInst::ICMP_NE:
1420 return isl_pw_aff_ne_set(L, R);
1421 case ICmpInst::ICMP_SLT:
1422 return isl_pw_aff_lt_set(L, R);
1423 case ICmpInst::ICMP_SLE:
1424 return isl_pw_aff_le_set(L, R);
1425 case ICmpInst::ICMP_SGT:
1426 return isl_pw_aff_gt_set(L, R);
1427 case ICmpInst::ICMP_SGE:
1428 return isl_pw_aff_ge_set(L, R);
1429 case ICmpInst::ICMP_ULT:
1430 return isl_pw_aff_lt_set(L, R);
1431 case ICmpInst::ICMP_UGT:
1432 return isl_pw_aff_gt_set(L, R);
1433 case ICmpInst::ICMP_ULE:
1434 return isl_pw_aff_le_set(L, R);
1435 case ICmpInst::ICMP_UGE:
1436 return isl_pw_aff_ge_set(L, R);
1437 default:
1438 llvm_unreachable("Non integer predicate not supported");
1439 }
1440}
1441
Tobias Grosserc80d6972016-09-02 06:33:33 +00001442/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001443///
1444/// Helper function that will make sure the dimensions of the result have the
1445/// same isl_id's as the @p Domain.
1446static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1447 __isl_take isl_pw_aff *L,
1448 __isl_take isl_pw_aff *R,
1449 __isl_keep isl_set *Domain) {
1450 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1451 return setDimensionIds(Domain, ConsequenceCondSet);
1452}
1453
Michael Kruse476f8552017-06-29 12:47:41 +00001454/// Compute the isl representation for the SCEV @p E in this BB.
1455///
1456/// @param S The Scop in which @p BB resides in.
1457/// @param BB The BB for which isl representation is to be
1458/// computed.
1459/// @param InvalidDomainMap A map of BB to their invalid domains.
1460/// @param E The SCEV that should be translated.
1461/// @param NonNegative Flag to indicate the @p E has to be non-negative.
1462///
1463/// Note that this function will also adjust the invalid context accordingly.
1464
1465__isl_give isl_pw_aff *
1466getPwAff(Scop &S, BasicBlock *BB,
Tobias Grosser13acbb92017-07-15 09:01:31 +00001467 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, const SCEV *E,
1468 bool NonNegative = false) {
Michael Kruse476f8552017-06-29 12:47:41 +00001469 PWACtx PWAC = S.getPwAff(E, BB, NonNegative);
Tobias Grosser13acbb92017-07-15 09:01:31 +00001470 InvalidDomainMap[BB] = InvalidDomainMap[BB].unite(isl::manage(PWAC.second));
Michael Kruse476f8552017-06-29 12:47:41 +00001471 return PWAC.first;
1472}
1473
Tobias Grosserc80d6972016-09-02 06:33:33 +00001474/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001475///
1476/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001477/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1478/// have as many elements as @p SI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001479static bool
1480buildConditionSets(Scop &S, BasicBlock *BB, SwitchInst *SI, Loop *L,
1481 __isl_keep isl_set *Domain,
1482 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1483 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001484
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001485 Value *Condition = getConditionFromTerminator(SI);
1486 assert(Condition && "No condition for switch");
1487
1488 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001489 isl_pw_aff *LHS, *RHS;
Michael Kruse476f8552017-06-29 12:47:41 +00001490 LHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001491
1492 unsigned NumSuccessors = SI->getNumSuccessors();
1493 ConditionSets.resize(NumSuccessors);
1494 for (auto &Case : SI->cases()) {
1495 unsigned Idx = Case.getSuccessorIndex();
1496 ConstantInt *CaseValue = Case.getCaseValue();
1497
Michael Kruse476f8552017-06-29 12:47:41 +00001498 RHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001499 isl_set *CaseConditionSet =
1500 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1501 ConditionSets[Idx] = isl_set_coalesce(
1502 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1503 }
1504
1505 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1506 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1507 for (unsigned u = 2; u < NumSuccessors; u++)
1508 ConditionSetUnion =
1509 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1510 ConditionSets[0] = setDimensionIds(
1511 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1512
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001513 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001514
1515 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001516}
1517
Michael Kruse08655852017-07-20 12:37:02 +00001518/// Build condition sets for unsigned ICmpInst(s).
1519/// Special handling is required for unsigned operands to ensure that if
1520/// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst
1521/// it should wrap around.
1522///
1523/// @param IsStrictUpperBound holds information on the predicate relation
1524/// between TestVal and UpperBound, i.e,
1525/// TestVal < UpperBound OR TestVal <= UpperBound
1526static __isl_give isl_set *
1527buildUnsignedConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1528 __isl_keep isl_set *Domain, const SCEV *SCEV_TestVal,
1529 const SCEV *SCEV_UpperBound,
1530 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1531 bool IsStrictUpperBound) {
1532
1533 // Do not take NonNeg assumption on TestVal
1534 // as it might have MSB (Sign bit) set.
1535 isl_pw_aff *TestVal = getPwAff(S, BB, InvalidDomainMap, SCEV_TestVal, false);
1536 // Take NonNeg assumption on UpperBound.
1537 isl_pw_aff *UpperBound =
1538 getPwAff(S, BB, InvalidDomainMap, SCEV_UpperBound, true);
1539
1540 // 0 <= TestVal
1541 isl_set *First =
1542 isl_pw_aff_le_set(isl_pw_aff_zero_on_domain(isl_local_space_from_space(
1543 isl_pw_aff_get_domain_space(TestVal))),
1544 isl_pw_aff_copy(TestVal));
1545
1546 isl_set *Second;
1547 if (IsStrictUpperBound)
1548 // TestVal < UpperBound
1549 Second = isl_pw_aff_lt_set(TestVal, UpperBound);
1550 else
1551 // TestVal <= UpperBound
1552 Second = isl_pw_aff_le_set(TestVal, UpperBound);
1553
1554 isl_set *ConsequenceCondSet = isl_set_intersect(First, Second);
1555 ConsequenceCondSet = setDimensionIds(Domain, ConsequenceCondSet);
1556 return ConsequenceCondSet;
1557}
1558
Tobias Grosserc80d6972016-09-02 06:33:33 +00001559/// Build the conditions sets for the branch condition @p Condition in
1560/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001561///
1562/// This will fill @p ConditionSets with the conditions under which control
1563/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001564/// have as many elements as @p TI has successors. If @p TI is nullptr the
1565/// context under which @p Condition is true/false will be returned as the
1566/// new elements of @p ConditionSets.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001567static bool
1568buildConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1569 TerminatorInst *TI, Loop *L, __isl_keep isl_set *Domain,
1570 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1571 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001572
1573 isl_set *ConsequenceCondSet = nullptr;
1574 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1575 if (CCond->isZero())
1576 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1577 else
1578 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1579 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1580 auto Opcode = BinOp->getOpcode();
1581 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1582
Michael Kruse476f8552017-06-29 12:47:41 +00001583 bool Valid = buildConditionSets(S, BB, BinOp->getOperand(0), TI, L, Domain,
1584 InvalidDomainMap, ConditionSets) &&
1585 buildConditionSets(S, BB, BinOp->getOperand(1), TI, L, Domain,
1586 InvalidDomainMap, ConditionSets);
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001587 if (!Valid) {
1588 while (!ConditionSets.empty())
1589 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001590 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001591 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001592
1593 isl_set_free(ConditionSets.pop_back_val());
1594 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1595 isl_set_free(ConditionSets.pop_back_val());
1596 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1597
1598 if (Opcode == Instruction::And)
1599 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1600 else
1601 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1602 } else {
1603 auto *ICond = dyn_cast<ICmpInst>(Condition);
1604 assert(ICond &&
1605 "Condition of exiting branch was neither constant nor ICmp!");
1606
1607 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001608 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001609 // For unsigned comparisons we assumed the signed bit of neither operand
1610 // to be set. The comparison is equal to a signed comparison under this
1611 // assumption.
1612 bool NonNeg = ICond->isUnsigned();
Michael Kruse08655852017-07-20 12:37:02 +00001613 const SCEV *LeftOperand = SE.getSCEVAtScope(ICond->getOperand(0), L),
1614 *RightOperand = SE.getSCEVAtScope(ICond->getOperand(1), L);
1615
1616 switch (ICond->getPredicate()) {
1617 case ICmpInst::ICMP_ULT:
1618 ConsequenceCondSet =
1619 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1620 RightOperand, InvalidDomainMap, true);
1621 break;
1622 case ICmpInst::ICMP_ULE:
1623 ConsequenceCondSet =
1624 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1625 RightOperand, InvalidDomainMap, false);
1626 break;
1627 case ICmpInst::ICMP_UGT:
1628 ConsequenceCondSet =
1629 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1630 LeftOperand, InvalidDomainMap, true);
1631 break;
1632 case ICmpInst::ICMP_UGE:
1633 ConsequenceCondSet =
1634 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1635 LeftOperand, InvalidDomainMap, false);
1636 break;
1637 default:
1638 LHS = getPwAff(S, BB, InvalidDomainMap, LeftOperand, NonNeg);
1639 RHS = getPwAff(S, BB, InvalidDomainMap, RightOperand, NonNeg);
1640 ConsequenceCondSet =
1641 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1642 break;
1643 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001644 }
1645
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001646 // If no terminator was given we are only looking for parameter constraints
1647 // under which @p Condition is true/false.
1648 if (!TI)
1649 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001650 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001651 ConsequenceCondSet = isl_set_coalesce(
1652 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001653
Johannes Doerfertb2885792016-04-26 09:20:41 +00001654 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001655 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001656 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001657
Michael Krusef7a4a942016-05-02 12:25:36 +00001658 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001659 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1660 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001661 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001662 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001663 }
1664
Michael Krusef7a4a942016-05-02 12:25:36 +00001665 if (TooComplex) {
Eli Friedmane737fc12017-07-17 23:58:33 +00001666 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc(),
1667 TI ? TI->getParent() : nullptr /* BasicBlock */);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001668 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001669 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001670 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001671 }
1672
1673 ConditionSets.push_back(ConsequenceCondSet);
1674 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001675
1676 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001677}
1678
Tobias Grosserc80d6972016-09-02 06:33:33 +00001679/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001680///
1681/// This will fill @p ConditionSets with the conditions under which control
1682/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1683/// have as many elements as @p TI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001684static bool
1685buildConditionSets(Scop &S, BasicBlock *BB, TerminatorInst *TI, Loop *L,
1686 __isl_keep isl_set *Domain,
1687 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1688 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001689
1690 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Michael Kruse476f8552017-06-29 12:47:41 +00001691 return buildConditionSets(S, BB, SI, L, Domain, InvalidDomainMap,
1692 ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001693
1694 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1695
1696 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001697 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001698 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001699 }
1700
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001701 Value *Condition = getConditionFromTerminator(TI);
1702 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001703
Michael Kruse476f8552017-06-29 12:47:41 +00001704 return buildConditionSets(S, BB, Condition, TI, L, Domain, InvalidDomainMap,
1705 ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001706}
1707
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001708void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001709 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001710
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001711 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001712 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001713}
1714
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001715void ScopStmt::collectSurroundingLoops() {
1716 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1717 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1718 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1719 isl_id_free(DimId);
1720 }
1721}
1722
Michael Kruse55454072017-03-15 22:16:43 +00001723ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001724 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
Michael Kruse55454072017-03-15 22:16:43 +00001725 R(&R), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001726
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001727 BaseName = getIslCompatibleName(
1728 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001729}
1730
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001731ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop,
1732 std::vector<Instruction *> Instructions)
Johannes Doerferta3519512016-04-23 13:02:23 +00001733 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001734 R(nullptr), Build(nullptr), SurroundingLoop(SurroundingLoop),
1735 Instructions(Instructions) {
Tobias Grosser75805372011-04-29 06:27:02 +00001736
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001737 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), "",
1738 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001739}
1740
Roman Gareevb3224ad2016-09-14 06:26:09 +00001741ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1742 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1743 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1744 R(nullptr), Build(nullptr) {
1745 BaseName = getIslCompatibleName("CopyStmt_", "",
1746 std::to_string(parent.getCopyStmtsNum()));
1747 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1748 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1749 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1750 auto *Access =
1751 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1752 parent.addAccessFunction(Access);
1753 addAccess(Access);
1754 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1755 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1756 parent.addAccessFunction(Access);
1757 addAccess(Access);
1758}
1759
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001760void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001761 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001762
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001763 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001764 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001765 buildAccessRelations();
1766
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001767 if (DetectReductions)
1768 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001769}
1770
Tobias Grosserc80d6972016-09-02 06:33:33 +00001771/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001772///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001773/// Check if the stored value for @p StoreMA is a binary operator with one or
1774/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001775/// used only once (by @p StoreMA) and its load operands are also used only
1776/// once, we have found a possible reduction chain. It starts at an operand
1777/// load and includes the binary operator and @p StoreMA.
1778///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001779/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001780/// escape this block or into any other store except @p StoreMA.
1781void ScopStmt::collectCandiateReductionLoads(
1782 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1783 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1784 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001785 return;
1786
1787 // Skip if there is not one binary operator between the load and the store
1788 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001789 if (!BinOp)
1790 return;
1791
1792 // Skip if the binary operators has multiple uses
1793 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001794 return;
1795
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001796 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001797 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1798 return;
1799
Johannes Doerfert9890a052014-07-01 00:32:29 +00001800 // Skip if the binary operator is outside the current SCoP
1801 if (BinOp->getParent() != Store->getParent())
1802 return;
1803
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001804 // Skip if it is a multiplicative reduction and we disabled them
1805 if (DisableMultiplicativeReductions &&
1806 (BinOp->getOpcode() == Instruction::Mul ||
1807 BinOp->getOpcode() == Instruction::FMul))
1808 return;
1809
Johannes Doerferte58a0122014-06-27 20:31:28 +00001810 // Check the binary operator operands for a candidate load
1811 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1812 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1813 if (!PossibleLoad0 && !PossibleLoad1)
1814 return;
1815
1816 // A load is only a candidate if it cannot escape (thus has only this use)
1817 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001818 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001819 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001820 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001821 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001822 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001823}
1824
Tobias Grosserc80d6972016-09-02 06:33:33 +00001825/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001826///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001827/// Iterate over all store memory accesses and check for valid binary reduction
1828/// like chains. For all candidates we check if they have the same base address
1829/// and there are no other accesses which overlap with them. The base address
1830/// check rules out impossible reductions candidates early. The overlap check,
1831/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001832/// guarantees that none of the intermediate results will escape during
1833/// execution of the loop nest. We basically check here that no other memory
1834/// access can access the same memory as the potential reduction.
1835void ScopStmt::checkForReductions() {
1836 SmallVector<MemoryAccess *, 2> Loads;
1837 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1838
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001839 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001840 // stores and collecting possible reduction loads.
1841 for (MemoryAccess *StoreMA : MemAccs) {
1842 if (StoreMA->isRead())
1843 continue;
1844
1845 Loads.clear();
1846 collectCandiateReductionLoads(StoreMA, Loads);
1847 for (MemoryAccess *LoadMA : Loads)
1848 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1849 }
1850
1851 // Then check each possible candidate pair.
1852 for (const auto &CandidatePair : Candidates) {
1853 bool Valid = true;
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001854 isl_map *LoadAccs = CandidatePair.first->getAccessRelation().release();
1855 isl_map *StoreAccs = CandidatePair.second->getAccessRelation().release();
Johannes Doerferte58a0122014-06-27 20:31:28 +00001856
1857 // Skip those with obviously unequal base addresses.
1858 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1859 isl_map_free(LoadAccs);
1860 isl_map_free(StoreAccs);
1861 continue;
1862 }
1863
1864 // And check if the remaining for overlap with other memory accesses.
1865 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1866 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1867 isl_set *AllAccs = isl_map_range(AllAccsRel);
1868
1869 for (MemoryAccess *MA : MemAccs) {
1870 if (MA == CandidatePair.first || MA == CandidatePair.second)
1871 continue;
1872
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001873 isl_map *AccRel = isl_map_intersect_domain(
1874 MA->getAccessRelation().release(), getDomain());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001875 isl_set *Accs = isl_map_range(AccRel);
1876
Tobias Grosser55a7af72016-09-08 14:08:07 +00001877 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001878 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1879 Valid = Valid && isl_set_is_empty(OverlapAccs);
1880 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001881 } else {
1882 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001883 }
1884 }
1885
1886 isl_set_free(AllAccs);
1887 if (!Valid)
1888 continue;
1889
Johannes Doerfertf6183392014-07-01 20:52:51 +00001890 const LoadInst *Load =
1891 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1892 MemoryAccess::ReductionType RT =
1893 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1894
Johannes Doerferte58a0122014-06-27 20:31:28 +00001895 // If no overlapping access was found we mark the load and store as
1896 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001897 CandidatePair.first->markAsReductionLike(RT);
1898 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001899 }
Tobias Grosser75805372011-04-29 06:27:02 +00001900}
1901
Tobias Grosser74394f02013-01-14 22:40:23 +00001902std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001903
Tobias Grosser54839312015-04-21 11:37:25 +00001904std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001905 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001906 if (!S)
1907 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001908 auto Str = stringFromIslObj(S);
1909 isl_map_free(S);
1910 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001911}
1912
Johannes Doerferta3519512016-04-23 13:02:23 +00001913void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1914 isl_set_free(InvalidDomain);
1915 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001916}
1917
Michael Kruse375cb5f2016-02-24 22:08:24 +00001918BasicBlock *ScopStmt::getEntryBlock() const {
1919 if (isBlockStmt())
1920 return getBasicBlock();
1921 return getRegion()->getEntry();
1922}
1923
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001924unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001925
Tobias Grosser75805372011-04-29 06:27:02 +00001926const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1927
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001928Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001929 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001930}
1931
Tobias Grosser74394f02013-01-14 22:40:23 +00001932isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001933
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001934__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001935
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001936__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001937 return isl_set_get_space(Domain);
1938}
1939
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001940__isl_give isl_id *ScopStmt::getDomainId() const {
1941 return isl_set_get_tuple_id(Domain);
1942}
Tobias Grossercd95b772012-08-30 11:49:38 +00001943
Johannes Doerfert7c013572016-04-12 09:57:34 +00001944ScopStmt::~ScopStmt() {
1945 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001946 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001947}
Tobias Grosser75805372011-04-29 06:27:02 +00001948
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001949void ScopStmt::printInstructions(raw_ostream &OS) const {
1950 OS << "Instructions {\n";
1951
1952 for (Instruction *Inst : Instructions)
1953 OS.indent(16) << *Inst << "\n";
1954
Michael Krusee52ebd12017-07-22 16:44:39 +00001955 OS.indent(12) << "}\n";
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001956}
1957
Michael Krusecd4c9772017-07-21 15:35:53 +00001958void ScopStmt::print(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00001959 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001960 OS.indent(12) << "Domain :=\n";
1961
1962 if (Domain) {
1963 OS.indent(16) << getDomainStr() << ";\n";
1964 } else
1965 OS.indent(16) << "n/a\n";
1966
Tobias Grosser54839312015-04-21 11:37:25 +00001967 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001968
1969 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001970 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001971 } else
1972 OS.indent(16) << "n/a\n";
1973
Tobias Grosser083d3d32014-06-28 08:59:45 +00001974 for (MemoryAccess *Access : MemAccs)
1975 Access->print(OS);
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001976
Michael Krusecd4c9772017-07-21 15:35:53 +00001977 if (PrintInstructions)
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001978 printInstructions(OS.indent(12));
Tobias Grosser75805372011-04-29 06:27:02 +00001979}
1980
Michael Kruse5d518462017-07-21 15:54:07 +00001981#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001982LLVM_DUMP_METHOD void ScopStmt::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00001983#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001984
Michael Krusee60eca72017-05-11 22:56:12 +00001985void ScopStmt::removeAccessData(MemoryAccess *MA) {
1986 if (MA->isRead() && MA->isOriginalValueKind()) {
1987 bool Found = ValueReads.erase(MA->getAccessValue());
1988 (void)Found;
1989 assert(Found && "Expected access data not found");
1990 }
1991 if (MA->isWrite() && MA->isOriginalValueKind()) {
1992 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1993 (void)Found;
1994 assert(Found && "Expected access data not found");
1995 }
1996 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1997 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1998 (void)Found;
1999 assert(Found && "Expected access data not found");
2000 }
Michael Kruse3562f272017-07-20 16:47:57 +00002001 if (MA->isRead() && MA->isOriginalAnyPHIKind()) {
2002 bool Found = PHIReads.erase(cast<PHINode>(MA->getAccessInstruction()));
2003 (void)Found;
2004 assert(Found && "Expected access data not found");
2005 }
Michael Krusee60eca72017-05-11 22:56:12 +00002006}
2007
Michael Kruse10071822016-05-23 14:45:58 +00002008void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00002009 // Remove the memory accesses from this statement together with all scalar
2010 // accesses that were caused by it. MemoryKind::Value READs have no access
2011 // instruction, hence would not be removed by this function. However, it is
2012 // only used for invariant LoadInst accesses, its arguments are always affine,
2013 // hence synthesizable, and therefore there are no MemoryKind::Value READ
2014 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00002015 auto Predicate = [&](MemoryAccess *Acc) {
2016 return Acc->getAccessInstruction() == MA->getAccessInstruction();
2017 };
Michael Krusee60eca72017-05-11 22:56:12 +00002018 for (auto *MA : MemAccs) {
Michael Kruse8b805802017-07-19 17:11:25 +00002019 if (Predicate(MA)) {
Michael Krusee60eca72017-05-11 22:56:12 +00002020 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00002021 Parent.removeAccessData(MA);
2022 }
Michael Krusee60eca72017-05-11 22:56:12 +00002023 }
Michael Kruse10071822016-05-23 14:45:58 +00002024 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
2025 MemAccs.end());
2026 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002027}
2028
Michael Kruse0446d812017-03-10 16:05:24 +00002029void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
2030 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
2031 assert(MAIt != MemAccs.end());
2032 MemAccs.erase(MAIt);
2033
Michael Krusee60eca72017-05-11 22:56:12 +00002034 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00002035 Parent.removeAccessData(MA);
Michael Krusee60eca72017-05-11 22:56:12 +00002036
Michael Kruse0446d812017-03-10 16:05:24 +00002037 auto It = InstructionToAccess.find(MA->getAccessInstruction());
2038 if (It != InstructionToAccess.end()) {
2039 It->second.remove(MA);
2040 if (It->second.empty())
2041 InstructionToAccess.erase(MA->getAccessInstruction());
2042 }
2043}
2044
Michael Krusecd4c9772017-07-21 15:35:53 +00002045raw_ostream &polly::operator<<(raw_ostream &O, const ScopStmt &S) {
2046 S.print(O, PollyPrintInstructions);
2047 return O;
2048}
2049
Tobias Grosser75805372011-04-29 06:27:02 +00002050//===----------------------------------------------------------------------===//
2051/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00002052
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00002053void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00002054 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
2055 isl_set_free(Context);
2056 Context = NewContext;
2057}
2058
Eli Friedman5e589ea2017-06-20 22:53:02 +00002059namespace {
Tobias Grosserc80d6972016-09-02 06:33:33 +00002060/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002061struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00002062 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002063 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002064
2065public:
2066 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00002067 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002068
2069 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
2070 ValueToValueMap &VMap) {
2071 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
2072 return SSPR.visit(E);
2073 }
2074
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002075 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
2076 auto *Start = visit(E->getStart());
2077 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
2078 visit(E->getStepRecurrence(SE)),
2079 E->getLoop(), SCEV::FlagAnyWrap);
2080 return SE.getAddExpr(Start, AddRec);
2081 }
2082
2083 const SCEV *visitUnknown(const SCEVUnknown *E) {
2084 if (auto *NewValue = VMap.lookup(E->getValue()))
2085 return SE.getUnknown(NewValue);
2086 return E;
2087 }
2088};
2089
Eli Friedman5e589ea2017-06-20 22:53:02 +00002090/// Check whether we should remap a SCEV expression.
2091struct SCEVFindInsideScop : public SCEVTraversal<SCEVFindInsideScop> {
2092 ValueToValueMap &VMap;
2093 bool FoundInside = false;
2094 Scop *S;
2095
2096public:
2097 SCEVFindInsideScop(ValueToValueMap &VMap, ScalarEvolution &SE, Scop *S)
2098 : SCEVTraversal(*this), VMap(VMap), S(S) {}
2099
2100 static bool hasVariant(const SCEV *E, ScalarEvolution &SE,
2101 ValueToValueMap &VMap, Scop *S) {
2102 SCEVFindInsideScop SFIS(VMap, SE, S);
2103 SFIS.visitAll(E);
2104 return SFIS.FoundInside;
2105 }
2106
2107 bool follow(const SCEV *E) {
2108 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(E)) {
2109 FoundInside |= S->getRegion().contains(AddRec->getLoop());
2110 } else if (auto *Unknown = dyn_cast<SCEVUnknown>(E)) {
2111 if (Instruction *I = dyn_cast<Instruction>(Unknown->getValue()))
2112 FoundInside |= S->getRegion().contains(I) && !VMap.count(I);
2113 }
2114 return !FoundInside;
2115 }
2116 bool isDone() { return FoundInside; }
2117};
2118} // namespace
2119
2120const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *E) {
2121 // Check whether it makes sense to rewrite the SCEV. (ScalarEvolution
2122 // doesn't like addition between an AddRec and an expression that
2123 // doesn't have a dominance relationship with it.)
2124 if (SCEVFindInsideScop::hasVariant(E, *SE, InvEquivClassVMap, this))
2125 return E;
2126
2127 // Rewrite SCEV.
2128 return SCEVSensitiveParameterRewriter::rewrite(E, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002129}
2130
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002131// This table of function names is used to translate parameter names in more
2132// human-readable names. This makes it easier to interpret Polly analysis
2133// results.
2134StringMap<std::string> KnownNames = {
2135 {"_Z13get_global_idj", "global_id"},
2136 {"_Z12get_local_idj", "local_id"},
2137 {"_Z15get_global_sizej", "global_size"},
2138 {"_Z14get_local_sizej", "local_size"},
2139 {"_Z12get_work_dimv", "work_dim"},
2140 {"_Z17get_global_offsetj", "global_offset"},
2141 {"_Z12get_group_idj", "group_id"},
2142 {"_Z14get_num_groupsj", "num_groups"},
2143};
2144
2145static std::string getCallParamName(CallInst *Call) {
2146 std::string Result;
2147 raw_string_ostream OS(Result);
2148 std::string Name = Call->getCalledFunction()->getName();
2149
2150 auto Iterator = KnownNames.find(Name);
2151 if (Iterator != KnownNames.end())
Tobias Grosserdff902f2017-06-01 12:46:51 +00002152 Name = "__" + Iterator->getValue();
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002153 OS << Name;
2154 for (auto &Operand : Call->arg_operands()) {
2155 ConstantInt *Op = cast<ConstantInt>(&Operand);
2156 OS << "_" << Op->getValue();
2157 }
2158 OS.flush();
2159 return Result;
2160}
2161
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002162void Scop::createParameterId(const SCEV *Parameter) {
2163 assert(Parameters.count(Parameter));
2164 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002165
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002166 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002167
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002168 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
2169 Value *Val = ValueParameter->getValue();
2170 CallInst *Call = dyn_cast<CallInst>(Val);
Tobias Grosser8f99c162011-11-15 11:38:55 +00002171
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002172 if (Call && isConstCall(Call)) {
2173 ParameterName = getCallParamName(Call);
2174 } else if (UseInstructionNames) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002175 // If this parameter references a specific Value and this value has a name
2176 // we use this name as it is likely to be unique and more useful than just
2177 // a number.
2178 if (Val->hasName())
2179 ParameterName = Val->getName();
2180 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
2181 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
2182 if (LoadOrigin->hasName()) {
2183 ParameterName += "_loaded_from_";
2184 ParameterName +=
2185 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
2186 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002187 }
2188 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00002189
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002190 ParameterName = getIslCompatibleName("", ParameterName, "");
2191 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00002192
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002193 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
2194 const_cast<void *>((const void *)Parameter));
2195 ParameterIds[Parameter] = Id;
2196}
2197
2198void Scop::addParams(const ParameterSetTy &NewParameters) {
2199 for (const SCEV *Parameter : NewParameters) {
2200 // Normalize the SCEV to get the representing element for an invariant load.
2201 Parameter = extractConstantFactor(Parameter, *SE).second;
2202 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2203
2204 if (Parameters.insert(Parameter))
2205 createParameterId(Parameter);
2206 }
2207}
2208
2209__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
2210 // Normalize the SCEV to get the representing element for an invariant load.
2211 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2212 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00002213}
Tobias Grosser75805372011-04-29 06:27:02 +00002214
Michael Krused56b90a2016-09-01 09:03:27 +00002215__isl_give isl_set *
2216Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002217 isl_set *DomainContext = isl_union_set_params(getDomains());
2218 return isl_set_intersect_params(C, DomainContext);
2219}
2220
Johannes Doerferte0b08072016-05-23 12:43:44 +00002221bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2222 return DT.dominates(BB, getEntry());
2223}
2224
Michael Kruse476f8552017-06-29 12:47:41 +00002225void Scop::addUserAssumptions(
2226 AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002227 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse89b1f942017-03-17 13:56:53 +00002228 for (auto &Assumption : AC.assumptions()) {
2229 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2230 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002231 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002232
Michael Kruse89b1f942017-03-17 13:56:53 +00002233 bool InScop = contains(CI);
2234 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2235 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002236
Michael Kruse89b1f942017-03-17 13:56:53 +00002237 auto *L = LI.getLoopFor(CI->getParent());
2238 auto *Val = CI->getArgOperand(0);
2239 ParameterSetTy DetectedParams;
2240 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00002241 ORE.emit(
2242 OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreUserAssumption", CI)
2243 << "Non-affine user assumption ignored.");
Michael Kruse89b1f942017-03-17 13:56:53 +00002244 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002245 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002246
2247 // Collect all newly introduced parameters.
2248 ParameterSetTy NewParams;
2249 for (auto *Param : DetectedParams) {
2250 Param = extractConstantFactor(Param, *SE).second;
2251 Param = getRepresentingInvariantLoadSCEV(Param);
2252 if (Parameters.count(Param))
2253 continue;
2254 NewParams.insert(Param);
2255 }
2256
2257 SmallVector<isl_set *, 2> ConditionSets;
2258 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
2259 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
2260 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
Michael Kruse476f8552017-06-29 12:47:41 +00002261 bool Valid = buildConditionSets(*this, Stmt.getEntryBlock(), Val, TI, L,
2262 Dom, InvalidDomainMap, ConditionSets);
Michael Kruse89b1f942017-03-17 13:56:53 +00002263 isl_set_free(Dom);
2264
2265 if (!Valid)
2266 continue;
2267
2268 isl_set *AssumptionCtx = nullptr;
2269 if (InScop) {
2270 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2271 isl_set_free(ConditionSets[0]);
2272 } else {
2273 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2274 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2275 }
2276
2277 // Project out newly introduced parameters as they are not otherwise useful.
2278 if (!NewParams.empty()) {
2279 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2280 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2281 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2282 isl_id_free(Id);
2283
2284 if (!NewParams.count(Param))
2285 continue;
2286
2287 AssumptionCtx =
2288 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2289 }
2290 }
Eli Friedmane737fc12017-07-17 23:58:33 +00002291 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "UserAssumption", CI)
2292 << "Use user assumption: " << stringFromIslObj(AssumptionCtx));
Michael Kruse89b1f942017-03-17 13:56:53 +00002293 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002294 }
2295}
2296
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002297void Scop::addUserContext() {
2298 if (UserContextStr.empty())
2299 return;
2300
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002301 isl_set *UserContext =
2302 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002303 isl_space *Space = getParamSpace();
2304 if (isl_space_dim(Space, isl_dim_param) !=
2305 isl_set_dim(UserContext, isl_dim_param)) {
2306 auto SpaceStr = isl_space_to_str(Space);
2307 errs() << "Error: the context provided in -polly-context has not the same "
2308 << "number of dimensions than the computed context. Due to this "
2309 << "mismatch, the -polly-context option is ignored. Please provide "
2310 << "the context in the parameter space: " << SpaceStr << ".\n";
2311 free(SpaceStr);
2312 isl_set_free(UserContext);
2313 isl_space_free(Space);
2314 return;
2315 }
2316
2317 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002318 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2319 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002320
2321 if (strcmp(NameContext, NameUserContext) != 0) {
2322 auto SpaceStr = isl_space_to_str(Space);
2323 errs() << "Error: the name of dimension " << i
2324 << " provided in -polly-context "
2325 << "is '" << NameUserContext << "', but the name in the computed "
2326 << "context is '" << NameContext
2327 << "'. Due to this name mismatch, "
2328 << "the -polly-context option is ignored. Please provide "
2329 << "the context in the parameter space: " << SpaceStr << ".\n";
2330 free(SpaceStr);
2331 isl_set_free(UserContext);
2332 isl_space_free(Space);
2333 return;
2334 }
2335
2336 UserContext =
2337 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2338 isl_space_get_dim_id(Space, isl_dim_param, i));
2339 }
2340
2341 Context = isl_set_intersect(Context, UserContext);
2342 isl_space_free(Space);
2343}
2344
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002345void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002346 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002347
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002348 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002349 for (LoadInst *LInst : RIL) {
2350 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2351
Johannes Doerfert96e54712016-02-07 17:30:13 +00002352 Type *Ty = LInst->getType();
2353 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002354 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002355 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002356 continue;
2357 }
2358
2359 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002360 InvariantEquivClasses.emplace_back(
2361 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002362 }
2363}
2364
Tobias Grosser6be480c2011-11-08 15:41:13 +00002365void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002366 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002367 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002368 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002369 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002370}
2371
Tobias Grosser18daaca2012-05-22 10:47:27 +00002372void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002373 unsigned PDim = 0;
2374 for (auto *Parameter : Parameters) {
2375 ConstantRange SRange = SE->getSignedRange(Parameter);
Tobias Grosser99ea1d02017-05-21 20:23:20 +00002376 Context =
2377 addRangeBoundsToSet(give(Context), SRange, PDim++, isl::dim::param)
2378 .release();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002379 }
2380}
2381
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002382// We use the outermost dimension to generate GPU transfers for Fortran arrays
2383// even when the array bounds are not known statically. To do so, we need the
2384// outermost dimension information. We add this into the context so that the
2385// outermost dimension is available during codegen.
2386// We currently do not care about dimensions other than the outermost
2387// dimension since it doesn't affect transfers.
2388static isl_set *addFortranArrayOutermostDimParams(__isl_give isl_set *Context,
2389 Scop::array_range Arrays) {
2390
2391 std::vector<isl_id *> OutermostSizeIds;
2392 for (auto Array : Arrays) {
2393 // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2394 // for its outermost dimension. Fortran arrays will have this since the
2395 // outermost dimension size can be picked up from their runtime description.
2396 // TODO: actually need to check if it has a FAD, but for now this works.
2397 if (Array->getNumberOfDimensions() > 0) {
Tobias Grosser77eef902017-07-21 23:07:56 +00002398 isl_pw_aff *PwAff = Array->getDimensionSizePw(0).release();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002399 if (!PwAff)
2400 continue;
2401
2402 isl_id *Id = isl_pw_aff_get_dim_id(PwAff, isl_dim_param, 0);
2403 isl_pw_aff_free(PwAff);
2404 assert(Id && "Invalid Id for PwAff expression in Fortran array");
2405 OutermostSizeIds.push_back(Id);
2406 }
2407 }
2408
2409 const int NumTrueParams = isl_set_dim(Context, isl_dim_param);
2410 Context = isl_set_add_dims(Context, isl_dim_param, OutermostSizeIds.size());
2411
2412 for (size_t i = 0; i < OutermostSizeIds.size(); i++) {
2413 Context = isl_set_set_dim_id(Context, isl_dim_param, NumTrueParams + i,
2414 OutermostSizeIds[i]);
2415 Context =
2416 isl_set_lower_bound_si(Context, isl_dim_param, NumTrueParams + i, 0);
2417 }
2418
2419 return Context;
2420}
2421
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002422void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002423 if (PollyIgnoreParamBounds)
2424 return;
2425
Tobias Grosser6be480c2011-11-08 15:41:13 +00002426 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002427 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002428
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002429 unsigned PDim = 0;
2430 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002431 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002432 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002433 }
2434
2435 // Align the parameters of all data structures to the model.
2436 Context = isl_set_align_params(Context, Space);
2437
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002438 // Add the outermost dimension of the Fortran arrays into the Context.
2439 // See the description of the function for more information.
2440 Context = addFortranArrayOutermostDimParams(Context, arrays());
2441
Johannes Doerferta60ad842016-05-10 12:18:22 +00002442 // As all parameters are known add bounds to them.
2443 addParameterBounds();
2444
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002445 for (ScopStmt &Stmt : *this)
2446 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002447 // Simplify the schedule according to the context too.
2448 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002449}
2450
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002451static __isl_give isl_set *
2452simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2453 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002454 // If we have modeled all blocks in the SCoP that have side effects we can
2455 // simplify the context with the constraints that are needed for anything to
2456 // be executed at all. However, if we have error blocks in the SCoP we already
2457 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002458 // domains, thus we cannot use the remaining domain to simplify the
2459 // assumptions.
2460 if (!S.hasErrorBlock()) {
2461 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2462 AssumptionContext =
2463 isl_set_gist_params(AssumptionContext, DomainParameters);
2464 }
2465
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002466 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2467 return AssumptionContext;
2468}
2469
2470void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002471 // The parameter constraints of the iteration domains give us a set of
2472 // constraints that need to hold for all cases where at least a single
2473 // statement iteration is executed in the whole scop. We now simplify the
2474 // assumed context under the assumption that such constraints hold and at
2475 // least a single statement iteration is executed. For cases where no
2476 // statement instances are executed, the assumptions we have taken about
2477 // the executed code do not matter and can be changed.
2478 //
2479 // WARNING: This only holds if the assumptions we have taken do not reduce
2480 // the set of statement instances that are executed. Otherwise we
2481 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002482 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002483 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002484 // performed. In such a case, modifying the run-time conditions and
2485 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002486 // to not be executed.
2487 //
2488 // Example:
2489 //
2490 // When delinearizing the following code:
2491 //
2492 // for (long i = 0; i < 100; i++)
2493 // for (long j = 0; j < m; j++)
2494 // A[i+p][j] = 1.0;
2495 //
2496 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002497 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002498 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002499 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002500 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002501}
2502
Tobias Grosserc80d6972016-09-02 06:33:33 +00002503/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002504static isl::stat
2505buildMinMaxAccess(isl::set Set, Scop::MinMaxVectorTy &MinMaxAccesses, Scop &S) {
2506 isl::pw_multi_aff MinPMA, MaxPMA;
2507 isl::pw_aff LastDimAff;
2508 isl::aff OneAff;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002509 unsigned Pos;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002510 isl::ctx Ctx = Set.get_ctx();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002511
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002512 Set = Set.remove_divs();
Johannes Doerfert6296d952016-04-22 11:38:19 +00002513
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002514 if (isl_set_n_basic_set(Set.get()) >= MaxDisjunctsInDomain)
2515 return isl::stat::error;
Johannes Doerfert6296d952016-04-22 11:38:19 +00002516
Johannes Doerfert9143d672014-09-27 11:02:39 +00002517 // Restrict the number of parameters involved in the access as the lexmin/
2518 // lexmax computation will take too long if this number is high.
2519 //
2520 // Experiments with a simple test case using an i7 4800MQ:
2521 //
2522 // #Parameters involved | Time (in sec)
2523 // 6 | 0.01
2524 // 7 | 0.04
2525 // 8 | 0.12
2526 // 9 | 0.40
2527 // 10 | 1.54
2528 // 11 | 6.78
2529 // 12 | 30.38
2530 //
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002531 if (isl_set_n_param(Set.get()) > RunTimeChecksMaxParameters) {
Johannes Doerfert9143d672014-09-27 11:02:39 +00002532 unsigned InvolvedParams = 0;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002533 for (unsigned u = 0, e = isl_set_n_param(Set.get()); u < e; u++)
2534 if (Set.involves_dims(isl::dim::param, u, 1))
Johannes Doerfert9143d672014-09-27 11:02:39 +00002535 InvolvedParams++;
2536
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002537 if (InvolvedParams > RunTimeChecksMaxParameters)
2538 return isl::stat::error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002539 }
2540
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +00002541 if (isl_set_n_basic_set(Set.get()) > RunTimeChecksMaxAccessDisjuncts)
2542 return isl::stat::error;
2543
Tobias Grosser57a1d362017-06-23 08:05:27 +00002544 MinPMA = Set.lexmin_pw_multi_aff();
2545 MaxPMA = Set.lexmax_pw_multi_aff();
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002546
Tobias Grosser57a1d362017-06-23 08:05:27 +00002547 if (isl_ctx_last_error(Ctx.get()) == isl_error_quota)
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002548 return isl::stat::error;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002549
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002550 MinPMA = MinPMA.coalesce();
2551 MaxPMA = MaxPMA.coalesce();
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002552
Johannes Doerfertb164c792014-09-18 11:17:17 +00002553 // Adjust the last dimension of the maximal access by one as we want to
2554 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2555 // we test during code generation might now point after the end of the
2556 // allocated array but we will never dereference it anyway.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002557 assert(MaxPMA.dim(isl::dim::out) && "Assumed at least one output dimension");
2558 Pos = MaxPMA.dim(isl::dim::out) - 1;
2559 LastDimAff = MaxPMA.get_pw_aff(Pos);
2560 OneAff = isl::aff(isl::local_space(LastDimAff.get_domain_space()));
2561 OneAff = OneAff.add_constant_si(1);
2562 LastDimAff = LastDimAff.add(OneAff);
2563 MaxPMA = MaxPMA.set_pw_aff(Pos, LastDimAff);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002564
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002565 MinMaxAccesses.push_back(std::make_pair(MinPMA.copy(), MaxPMA.copy()));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002566
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002567 return isl::stat::ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002568}
2569
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002570static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2571 isl_set *Domain = MA->getStatement()->getDomain();
2572 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2573 return isl_set_reset_tuple_id(Domain);
2574}
2575
Tobias Grosserc80d6972016-09-02 06:33:33 +00002576/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002577static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002578 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002579
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002580 MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002581
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002582 isl::union_set Domains = give(S.getDomains());
2583 isl::union_map Accesses = isl::union_map::empty(give(S.getParamSpace()));
Tobias Grossere9522232017-01-16 15:49:04 +00002584
2585 for (MemoryAccess *MA : AliasGroup)
Tobias Grosser1515f6b2017-07-23 04:08:38 +00002586 Accesses = Accesses.add_map(give(MA->getAccessRelation().release()));
Tobias Grossere9522232017-01-16 15:49:04 +00002587
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002588 Accesses = Accesses.intersect_domain(Domains);
2589 isl::union_set Locations = Accesses.range();
2590 Locations = Locations.coalesce();
2591 Locations = Locations.detect_equalities();
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002592
2593 auto Lambda = [&MinMaxAccesses, &S](isl::set Set) -> isl::stat {
2594 return buildMinMaxAccess(Set, MinMaxAccesses, S);
2595 };
2596 return Locations.foreach_set(Lambda) == isl::stat::ok;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002597}
2598
Tobias Grosserc80d6972016-09-02 06:33:33 +00002599/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002600///
2601///{
2602
Tobias Grosserc80d6972016-09-02 06:33:33 +00002603/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002604static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2605 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2606 : RN->getNodeAs<BasicBlock>();
2607}
2608
Tobias Grosserc80d6972016-09-02 06:33:33 +00002609/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002610static inline BasicBlock *
2611getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002612 if (RN->isSubRegion()) {
2613 assert(idx == 0);
2614 return RN->getNodeAs<Region>()->getExit();
2615 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002616 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002617}
2618
Tobias Grosserc80d6972016-09-02 06:33:33 +00002619/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002620static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002621 if (!RN->isSubRegion()) {
2622 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2623 Loop *L = LI.getLoopFor(BB);
2624
2625 // Unreachable statements are not considered to belong to a LLVM loop, as
2626 // they are not part of an actual loop in the control flow graph.
2627 // Nevertheless, we handle certain unreachable statements that are common
2628 // when modeling run-time bounds checks as being part of the loop to be
2629 // able to model them and to later eliminate the run-time bounds checks.
2630 //
2631 // Specifically, for basic blocks that terminate in an unreachable and
Michael Krusea6d48f52017-06-08 12:06:15 +00002632 // where the immediate predecessor is part of a loop, we assume these
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002633 // basic blocks belong to the loop the predecessor belongs to. This
2634 // allows us to model the following code.
2635 //
2636 // for (i = 0; i < N; i++) {
2637 // if (i > 1024)
2638 // abort(); <- this abort might be translated to an
2639 // unreachable
2640 //
2641 // A[i] = ...
2642 // }
2643 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2644 L = LI.getLoopFor(BB->getPrevNode());
2645 return L;
2646 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002647
2648 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2649 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2650 while (L && NonAffineSubRegion->contains(L))
2651 L = L->getParentLoop();
2652 return L;
2653}
2654
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002655/// Get the number of blocks in @p L.
2656///
2657/// The number of blocks in a loop are the number of basic blocks actually
2658/// belonging to the loop, as well as all single basic blocks that the loop
2659/// exits to and which terminate in an unreachable instruction. We do not
2660/// allow such basic blocks in the exit of a scop, hence they belong to the
2661/// scop and represent run-time conditions which we want to model and
2662/// subsequently speculate away.
2663///
2664/// @see getRegionNodeLoop for additional details.
Reid Klecknerdf2b2832017-06-19 17:44:02 +00002665unsigned getNumBlocksInLoop(Loop *L) {
2666 unsigned NumBlocks = L->getNumBlocks();
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002667 SmallVector<llvm::BasicBlock *, 4> ExitBlocks;
2668 L->getExitBlocks(ExitBlocks);
2669
2670 for (auto ExitBlock : ExitBlocks) {
2671 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2672 NumBlocks++;
2673 }
2674 return NumBlocks;
2675}
2676
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002677static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2678 if (!RN->isSubRegion())
2679 return 1;
2680
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002681 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002682 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002683}
2684
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002685static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2686 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002687 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002688 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002689 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002690 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002691 return true;
2692 return false;
2693}
2694
Johannes Doerfert96425c22015-08-30 21:13:53 +00002695///}
2696
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002697static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2698 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002699 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002700 isl_id *DimId =
2701 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2702 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2703}
2704
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002705__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002706 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002707}
2708
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002709__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002710 auto DIt = DomainMap.find(BB);
2711 if (DIt != DomainMap.end())
Tobias Grosser325204a32017-07-15 12:41:32 +00002712 return DIt->getSecond().copy();
Johannes Doerfert41cda152016-04-08 10:32:26 +00002713
2714 auto &RI = *R.getRegionInfo();
2715 auto *BBR = RI.getRegionFor(BB);
2716 while (BBR->getEntry() == BB)
2717 BBR = BBR->getParent();
2718 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002719}
2720
Tobias Grosser13acbb92017-07-15 09:01:31 +00002721bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI,
2722 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002723
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002724 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002725 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002726 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2727 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002728 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002729
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002730 while (LD-- >= 0) {
2731 S = addDomainDimId(S, LD + 1, L);
2732 L = L->getParentLoop();
2733 }
2734
Tobias Grosser13acbb92017-07-15 09:01:31 +00002735 InvalidDomainMap[EntryBB] = isl::manage(isl_set_empty(isl_set_get_space(S)));
Tobias Grosser325204a32017-07-15 12:41:32 +00002736 DomainMap[EntryBB] = isl::manage(S);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002737
Johannes Doerfert432658d2016-01-26 11:01:41 +00002738 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002739 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002740
Michael Kruse476f8552017-06-29 12:47:41 +00002741 if (!buildDomainsWithBranchConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002742 return false;
2743
Michael Kruse476f8552017-06-29 12:47:41 +00002744 if (!propagateDomainConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002745 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002746
2747 // Error blocks and blocks dominated by them have been assumed to never be
2748 // executed. Representing them in the Scop does not add any value. In fact,
2749 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002750 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002751 // will cause problems when building up a ScopStmt for them.
2752 // Furthermore, basic blocks dominated by error blocks may reference
2753 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002754 // can themselves not be constructed properly. To this end we will replace
2755 // the domains of error blocks and those only reachable via error blocks
2756 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002757 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002758 // InvalidDomain. This information is needed during load hoisting.
Michael Kruse476f8552017-06-29 12:47:41 +00002759 if (!propagateInvalidStmtDomains(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002760 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002761
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002762 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002763}
2764
Tobias Grosserc80d6972016-09-02 06:33:33 +00002765/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002766/// to be compatible to domains constructed for loop @p NewL.
2767///
2768/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2769/// edge from @p OldL to @p NewL.
2770static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2771 __isl_take isl_set *Dom,
2772 Loop *OldL, Loop *NewL) {
2773
2774 // If the loops are the same there is nothing to do.
2775 if (NewL == OldL)
2776 return Dom;
2777
2778 int OldDepth = S.getRelativeLoopDepth(OldL);
2779 int NewDepth = S.getRelativeLoopDepth(NewL);
2780 // If both loops are non-affine loops there is nothing to do.
2781 if (OldDepth == -1 && NewDepth == -1)
2782 return Dom;
2783
2784 // Distinguish three cases:
2785 // 1) The depth is the same but the loops are not.
2786 // => One loop was left one was entered.
2787 // 2) The depth increased from OldL to NewL.
2788 // => One loop was entered, none was left.
2789 // 3) The depth decreased from OldL to NewL.
2790 // => Loops were left were difference of the depths defines how many.
2791 if (OldDepth == NewDepth) {
2792 assert(OldL->getParentLoop() == NewL->getParentLoop());
2793 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2794 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2795 Dom = addDomainDimId(Dom, NewDepth, NewL);
2796 } else if (OldDepth < NewDepth) {
2797 assert(OldDepth + 1 == NewDepth);
2798 auto &R = S.getRegion();
2799 (void)R;
2800 assert(NewL->getParentLoop() == OldL ||
2801 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2802 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2803 Dom = addDomainDimId(Dom, NewDepth, NewL);
2804 } else {
2805 assert(OldDepth > NewDepth);
2806 int Diff = OldDepth - NewDepth;
2807 int NumDim = isl_set_n_dim(Dom);
2808 assert(NumDim >= Diff);
2809 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2810 }
2811
2812 return Dom;
2813}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002814
Michael Kruse476f8552017-06-29 12:47:41 +00002815bool Scop::propagateInvalidStmtDomains(
2816 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002817 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse476f8552017-06-29 12:47:41 +00002818
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002819 ReversePostOrderTraversal<Region *> RTraversal(R);
2820 for (auto *RN : RTraversal) {
2821
2822 // Recurse for affine subregions but go on for basic blocks and non-affine
2823 // subregions.
2824 if (RN->isSubRegion()) {
2825 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002826 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002827 propagateInvalidStmtDomains(SubRegion, DT, LI, InvalidDomainMap);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002828 continue;
2829 }
2830 }
2831
2832 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2833 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00002834 isl::set &Domain = DomainMap[BB];
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002835 assert(Domain && "Cannot propagate a nullptr");
2836
Tobias Grosser325204a32017-07-15 12:41:32 +00002837 isl::set InvalidDomain = InvalidDomainMap[BB];
Michael Kruse476f8552017-06-29 12:47:41 +00002838
Tobias Grosser325204a32017-07-15 12:41:32 +00002839 bool IsInvalidBlock = ContainsErrorBlock || Domain.is_subset(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002840
Johannes Doerferta3519512016-04-23 13:02:23 +00002841 if (!IsInvalidBlock) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002842 InvalidDomain = InvalidDomain.intersect(Domain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002843 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002844 InvalidDomain = Domain;
Tobias Grosser325204a32017-07-15 12:41:32 +00002845 isl::set DomPar = Domain.params();
2846 recordAssumption(ERRORBLOCK, DomPar.release(),
2847 BB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002848 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002849 }
2850
Tobias Grosser325204a32017-07-15 12:41:32 +00002851 if (InvalidDomain.is_empty()) {
2852 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002853 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002854 }
2855
Johannes Doerferta3519512016-04-23 13:02:23 +00002856 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002857 auto *TI = BB->getTerminator();
2858 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2859 for (unsigned u = 0; u < NumSuccs; u++) {
2860 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002861
2862 // Skip successors outside the SCoP.
Michael Kruse476f8552017-06-29 12:47:41 +00002863 if (!contains(SuccBB))
Johannes Doerfert7c013572016-04-12 09:57:34 +00002864 continue;
2865
Johannes Doerferte4459a22016-04-25 13:34:50 +00002866 // Skip backedges.
2867 if (DT.dominates(SuccBB, BB))
2868 continue;
2869
Michael Kruse476f8552017-06-29 12:47:41 +00002870 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2871
Johannes Doerferta3519512016-04-23 13:02:23 +00002872 auto *AdjustedInvalidDomain = adjustDomainDimensions(
Tobias Grosser325204a32017-07-15 12:41:32 +00002873 *this, InvalidDomain.copy(), BBLoop, SuccBBLoop);
Michael Kruse476f8552017-06-29 12:47:41 +00002874
Tobias Grosser13acbb92017-07-15 09:01:31 +00002875 auto *SuccInvalidDomain = InvalidDomainMap[SuccBB].copy();
Johannes Doerferta3519512016-04-23 13:02:23 +00002876 SuccInvalidDomain =
2877 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2878 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2879 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
Michael Kruse476f8552017-06-29 12:47:41 +00002880
Tobias Grosser13acbb92017-07-15 09:01:31 +00002881 InvalidDomainMap[SuccBB] = isl::manage(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002882
Michael Krusebc150122016-05-02 12:25:18 +00002883 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002884 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002885 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002886 continue;
2887
Tobias Grosserf44f0052017-07-09 15:47:17 +00002888 InvalidDomainMap.erase(BB);
Eli Friedmane737fc12017-07-17 23:58:33 +00002889 invalidate(COMPLEXITY, TI->getDebugLoc(), TI->getParent());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002890 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002891 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002892
Tobias Grosser325204a32017-07-15 12:41:32 +00002893 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002894 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002895
2896 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002897}
2898
Johannes Doerfert642594a2016-04-04 07:57:39 +00002899void Scop::propagateDomainConstraintsToRegionExit(
2900 BasicBlock *BB, Loop *BBLoop,
Michael Kruse476f8552017-06-29 12:47:41 +00002901 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002902 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002903
2904 // Check if the block @p BB is the entry of a region. If so we propagate it's
2905 // domain to the exit block of the region. Otherwise we are done.
2906 auto *RI = R.getRegionInfo();
2907 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2908 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002909 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002910 return;
2911
Johannes Doerfert642594a2016-04-04 07:57:39 +00002912 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002913 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002914 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002915 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002916 SmallVector<BasicBlock *, 4> LatchBBs;
2917 BBLoop->getLoopLatches(LatchBBs);
2918 for (auto *LatchBB : LatchBBs)
2919 if (BB != LatchBB && BBReg->contains(LatchBB))
2920 return;
2921 L = L->getParentLoop();
2922 }
2923
Tobias Grosser325204a32017-07-15 12:41:32 +00002924 isl::set Domain = DomainMap[BB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002925 assert(Domain && "Cannot propagate a nullptr");
2926
Michael Kruse476f8552017-06-29 12:47:41 +00002927 Loop *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002928
2929 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2930 // adjust the domain before we can propagate it.
Tobias Grosser325204a32017-07-15 12:41:32 +00002931 isl::set AdjustedDomain = isl::manage(
2932 adjustDomainDimensions(*this, Domain.copy(), BBLoop, ExitBBLoop));
2933 isl::set &ExitDomain = DomainMap[ExitBB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002934
2935 // If the exit domain is not yet created we set it otherwise we "add" the
2936 // current domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002937 ExitDomain = ExitDomain ? AdjustedDomain.unite(ExitDomain) : AdjustedDomain;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002938
Johannes Doerferta3519512016-04-23 13:02:23 +00002939 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002940 InvalidDomainMap[ExitBB] = ExitDomain.empty(ExitDomain.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002941
Johannes Doerfert642594a2016-04-04 07:57:39 +00002942 FinishedExitBlocks.insert(ExitBB);
2943}
2944
Michael Kruse476f8552017-06-29 12:47:41 +00002945bool Scop::buildDomainsWithBranchConstraints(
2946 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002947 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse476f8552017-06-29 12:47:41 +00002948
Johannes Doerfert96425c22015-08-30 21:13:53 +00002949 // To create the domain for each block in R we iterate over all blocks and
2950 // subregions in R and propagate the conditions under which the current region
2951 // element is executed. To this end we iterate in reverse post order over R as
2952 // it ensures that we first visit all predecessors of a region node (either a
2953 // basic block or a subregion) before we visit the region node itself.
2954 // Initially, only the domain for the SCoP region entry block is set and from
2955 // there we propagate the current domain to all successors, however we add the
2956 // condition that the successor is actually executed next.
2957 // As we are only interested in non-loop carried constraints here we can
2958 // simply skip loop back edges.
2959
Johannes Doerfert642594a2016-04-04 07:57:39 +00002960 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002961 ReversePostOrderTraversal<Region *> RTraversal(R);
2962 for (auto *RN : RTraversal) {
2963
2964 // Recurse for affine subregions but go on for basic blocks and non-affine
2965 // subregions.
2966 if (RN->isSubRegion()) {
2967 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002968 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002969 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI,
2970 InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002971 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002972 continue;
2973 }
2974 }
2975
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002976 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002977 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002978
Johannes Doerfert96425c22015-08-30 21:13:53 +00002979 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002980 TerminatorInst *TI = BB->getTerminator();
2981
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002982 if (isa<UnreachableInst>(TI))
2983 continue;
2984
Tobias Grosser325204a32017-07-15 12:41:32 +00002985 isl::set Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002986 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002987 continue;
Tobias Grosser325204a32017-07-15 12:41:32 +00002988 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain.get()));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002989
Johannes Doerfert642594a2016-04-04 07:57:39 +00002990 auto *BBLoop = getRegionNodeLoop(RN, LI);
2991 // Propagate the domain from BB directly to blocks that have a superset
2992 // domain, at the moment only region exit nodes of regions that start in BB.
Michael Kruse476f8552017-06-29 12:47:41 +00002993 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI,
2994 InvalidDomainMap);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002995
2996 // If all successors of BB have been set a domain through the propagation
2997 // above we do not need to build condition sets but can just skip this
2998 // block. However, it is important to note that this is a local property
2999 // with regards to the region @p R. To this end FinishedExitBlocks is a
3000 // local variable.
3001 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
3002 return FinishedExitBlocks.count(SuccBB);
3003 };
3004 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
3005 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003006
3007 // Build the condition sets for the successor nodes of the current region
3008 // node. If it is a non-affine subregion we will always execute the single
3009 // exit node, hence the single entry node domain is the condition set. For
3010 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003011 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003012 if (RN->isSubRegion())
Tobias Grosser325204a32017-07-15 12:41:32 +00003013 ConditionSets.push_back(Domain.copy());
3014 else if (!buildConditionSets(*this, BB, TI, BBLoop, Domain.get(),
Michael Kruse476f8552017-06-29 12:47:41 +00003015 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003016 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003017
3018 // Now iterate over the successors and set their initial domain based on
3019 // their condition set. We skip back edges here and have to be careful when
3020 // we leave a loop not to keep constraints over a dimension that doesn't
3021 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003022 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00003023 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Tobias Grosser325204a32017-07-15 12:41:32 +00003024 isl::set CondSet = isl::manage(ConditionSets[u]);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003025 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003026
Johannes Doerfert535de032016-04-19 14:49:05 +00003027 // Skip blocks outside the region.
Tobias Grosser325204a32017-07-15 12:41:32 +00003028 if (!contains(SuccBB))
Johannes Doerfert535de032016-04-19 14:49:05 +00003029 continue;
Johannes Doerfert535de032016-04-19 14:49:05 +00003030
Johannes Doerfert642594a2016-04-04 07:57:39 +00003031 // If we propagate the domain of some block to "SuccBB" we do not have to
3032 // adjust the domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00003033 if (FinishedExitBlocks.count(SuccBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00003034 continue;
Johannes Doerfert642594a2016-04-04 07:57:39 +00003035
Johannes Doerfert96425c22015-08-30 21:13:53 +00003036 // Skip back edges.
Tobias Grosser325204a32017-07-15 12:41:32 +00003037 if (DT.dominates(SuccBB, BB))
Johannes Doerfert96425c22015-08-30 21:13:53 +00003038 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003039
Michael Kruse476f8552017-06-29 12:47:41 +00003040 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
3041
Tobias Grosser325204a32017-07-15 12:41:32 +00003042 CondSet = isl::manage(
3043 adjustDomainDimensions(*this, CondSet.copy(), BBLoop, SuccBBLoop));
Johannes Doerfert96425c22015-08-30 21:13:53 +00003044
3045 // Set the domain for the successor or merge it with an existing domain in
3046 // case there are multiple paths (without loop back edges) to the
3047 // successor block.
Tobias Grosser325204a32017-07-15 12:41:32 +00003048 isl::set &SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00003049
Johannes Doerferta3519512016-04-23 13:02:23 +00003050 if (SuccDomain) {
Tobias Grosser325204a32017-07-15 12:41:32 +00003051 SuccDomain = SuccDomain.unite(CondSet).coalesce();
Johannes Doerferta3519512016-04-23 13:02:23 +00003052 } else {
3053 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00003054 InvalidDomainMap[SuccBB] = CondSet.empty(CondSet.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00003055 SuccDomain = CondSet;
3056 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00003057
Tobias Grosser325204a32017-07-15 12:41:32 +00003058 SuccDomain = SuccDomain.detect_equalities();
Tobias Grosser6d459c52017-05-23 04:26:28 +00003059
Michael Krusebc150122016-05-02 12:25:18 +00003060 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003061 // In case this happens we will clean up and bail.
Tobias Grosser325204a32017-07-15 12:41:32 +00003062 if (isl_set_n_basic_set(SuccDomain.get()) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003063 continue;
3064
3065 invalidate(COMPLEXITY, DebugLoc());
3066 while (++u < ConditionSets.size())
3067 isl_set_free(ConditionSets[u]);
3068 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003069 }
3070 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003071
3072 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003073}
3074
Michael Krused56b90a2016-09-01 09:03:27 +00003075__isl_give isl_set *
3076Scop::getPredecessorDomainConstraints(BasicBlock *BB,
3077 __isl_keep isl_set *Domain,
3078 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00003079 // If @p BB is the ScopEntry we are done
3080 if (R.getEntry() == BB)
3081 return isl_set_universe(isl_set_get_space(Domain));
3082
Johannes Doerfert642594a2016-04-04 07:57:39 +00003083 // The region info of this function.
3084 auto &RI = *R.getRegionInfo();
3085
Michael Kruse476f8552017-06-29 12:47:41 +00003086 Loop *BBLoop = getFirstNonBoxedLoopFor(BB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00003087
3088 // A domain to collect all predecessor domains, thus all conditions under
3089 // which the block is executed. To this end we start with the empty domain.
3090 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
3091
3092 // Set of regions of which the entry block domain has been propagated to BB.
3093 // all predecessors inside any of the regions can be skipped.
3094 SmallSet<Region *, 8> PropagatedRegions;
3095
3096 for (auto *PredBB : predecessors(BB)) {
3097 // Skip backedges.
3098 if (DT.dominates(BB, PredBB))
3099 continue;
3100
3101 // If the predecessor is in a region we used for propagation we can skip it.
3102 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
3103 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
3104 PredBBInRegion)) {
3105 continue;
3106 }
3107
3108 // Check if there is a valid region we can use for propagation, thus look
3109 // for a region that contains the predecessor and has @p BB as exit block.
3110 auto *PredR = RI.getRegionFor(PredBB);
3111 while (PredR->getExit() != BB && !PredR->contains(BB))
3112 PredR->getParent();
3113
3114 // If a valid region for propagation was found use the entry of that region
3115 // for propagation, otherwise the PredBB directly.
3116 if (PredR->getExit() == BB) {
3117 PredBB = PredR->getEntry();
3118 PropagatedRegions.insert(PredR);
3119 }
3120
Johannes Doerfert41cda152016-04-08 10:32:26 +00003121 auto *PredBBDom = getDomainConditions(PredBB);
Michael Kruse476f8552017-06-29 12:47:41 +00003122 Loop *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, getBoxedLoops());
3123
Johannes Doerfert642594a2016-04-04 07:57:39 +00003124 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
3125
3126 PredDom = isl_set_union(PredDom, PredBBDom);
3127 }
3128
3129 return PredDom;
3130}
3131
Michael Kruse476f8552017-06-29 12:47:41 +00003132bool Scop::propagateDomainConstraints(
3133 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00003134 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003135 // Iterate over the region R and propagate the domain constrains from the
3136 // predecessors to the current node. In contrast to the
3137 // buildDomainsWithBranchConstraints function, this one will pull the domain
3138 // information from the predecessors instead of pushing it to the successors.
3139 // Additionally, we assume the domains to be already present in the domain
3140 // map here. However, we iterate again in reverse post order so we know all
3141 // predecessors have been visited before a block or non-affine subregion is
3142 // visited.
3143
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003144 ReversePostOrderTraversal<Region *> RTraversal(R);
3145 for (auto *RN : RTraversal) {
3146
3147 // Recurse for affine subregions but go on for basic blocks and non-affine
3148 // subregions.
3149 if (RN->isSubRegion()) {
3150 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003151 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00003152 if (!propagateDomainConstraints(SubRegion, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003153 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003154 continue;
3155 }
3156 }
3157
3158 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00003159 isl::set &Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00003160 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003161
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003162 // Under the union of all predecessor conditions we can reach this block.
Tobias Grosser325204a32017-07-15 12:41:32 +00003163 isl::set PredDom =
3164 isl::manage(getPredecessorDomainConstraints(BB, Domain.get(), DT, LI));
3165 Domain = Domain.intersect(PredDom).coalesce();
3166 Domain = Domain.align_params(isl::manage(getParamSpace()));
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003167
Johannes Doerfert642594a2016-04-04 07:57:39 +00003168 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00003169 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Michael Kruse476f8552017-06-29 12:47:41 +00003170 if (!addLoopBoundsToHeaderDomain(BBLoop, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003171 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003172 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00003173
3174 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003175}
3176
Tobias Grosserc80d6972016-09-02 06:33:33 +00003177/// Create a map to map from a given iteration to a subsequent iteration.
3178///
3179/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
3180/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003181/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00003182///
3183/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003184static __isl_give isl_map *
3185createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
3186 auto *MapSpace = isl_space_map_from_set(SetSpace);
3187 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00003188 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003189 if (u != Dim)
3190 NextIterationMap =
3191 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
3192 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
3193 C = isl_constraint_set_constant_si(C, 1);
3194 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
3195 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
3196 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
3197 return NextIterationMap;
3198}
3199
Michael Kruse476f8552017-06-29 12:47:41 +00003200bool Scop::addLoopBoundsToHeaderDomain(
Tobias Grosser13acbb92017-07-15 09:01:31 +00003201 Loop *L, LoopInfo &LI, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003202 int LoopDepth = getRelativeLoopDepth(L);
3203 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003204
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003205 BasicBlock *HeaderBB = L->getHeader();
3206 assert(DomainMap.count(HeaderBB));
Tobias Grosser325204a32017-07-15 12:41:32 +00003207 isl::set &HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003208
Tobias Grosser325204a32017-07-15 12:41:32 +00003209 isl::map NextIterationMap = isl::manage(
3210 createNextIterationMap(HeaderBBDom.get_space().release(), LoopDepth));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003211
Tobias Grosser325204a32017-07-15 12:41:32 +00003212 isl::set UnionBackedgeCondition = HeaderBBDom.empty(HeaderBBDom.get_space());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003213
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003214 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
3215 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003216
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003217 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003218
3219 // If the latch is only reachable via error statements we skip it.
Tobias Grosser325204a32017-07-15 12:41:32 +00003220 isl::set LatchBBDom = DomainMap.lookup(LatchBB);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003221 if (!LatchBBDom)
3222 continue;
3223
Tobias Grosser325204a32017-07-15 12:41:32 +00003224 isl::set BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003225
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003226 TerminatorInst *TI = LatchBB->getTerminator();
3227 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00003228 assert(BI && "Only branch instructions allowed in loop latches");
3229
3230 if (BI->isUnconditional())
Tobias Grosser325204a32017-07-15 12:41:32 +00003231 BackedgeCondition = LatchBBDom;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003232 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003233 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003234 int idx = BI->getSuccessor(0) != HeaderBB;
Tobias Grosser325204a32017-07-15 12:41:32 +00003235 if (!buildConditionSets(*this, LatchBB, TI, L, LatchBBDom.get(),
3236 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003237 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003238
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003239 // Free the non back edge condition set as we do not need it.
3240 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003241
Tobias Grosser325204a32017-07-15 12:41:32 +00003242 BackedgeCondition = isl::manage(ConditionSets[idx]);
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003243 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003244
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003245 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3246 assert(LatchLoopDepth >= LoopDepth);
Tobias Grosser325204a32017-07-15 12:41:32 +00003247 BackedgeCondition = BackedgeCondition.project_out(
3248 isl::dim::set, LoopDepth + 1, LatchLoopDepth - LoopDepth);
3249 UnionBackedgeCondition = UnionBackedgeCondition.unite(BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003250 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003251
Tobias Grosser325204a32017-07-15 12:41:32 +00003252 isl::map ForwardMap = ForwardMap.lex_le(HeaderBBDom.get_space());
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003253 for (int i = 0; i < LoopDepth; i++)
Tobias Grosser325204a32017-07-15 12:41:32 +00003254 ForwardMap = ForwardMap.equate(isl::dim::in, i, isl::dim::out, i);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003255
Tobias Grosser325204a32017-07-15 12:41:32 +00003256 isl::set UnionBackedgeConditionComplement =
3257 UnionBackedgeCondition.complement();
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003258 UnionBackedgeConditionComplement =
Tobias Grosser325204a32017-07-15 12:41:32 +00003259 UnionBackedgeConditionComplement.lower_bound_si(isl::dim::set, LoopDepth,
3260 0);
3261 UnionBackedgeConditionComplement =
3262 UnionBackedgeConditionComplement.apply(ForwardMap);
3263 HeaderBBDom = HeaderBBDom.subtract(UnionBackedgeConditionComplement);
3264 HeaderBBDom = HeaderBBDom.apply(NextIterationMap);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003265
Tobias Grosser325204a32017-07-15 12:41:32 +00003266 auto Parts = partitionSetParts(HeaderBBDom.copy(), LoopDepth);
3267 HeaderBBDom = isl::manage(Parts.second);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003268
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003269 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3270 // the bounded assumptions to the context as they are already implied by the
3271 // <nsw> tag.
3272 if (Affinator.hasNSWAddRecForLoop(L)) {
3273 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003274 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003275 }
3276
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003277 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003278 recordAssumption(INFINITELOOP, UnboundedCtx,
3279 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003280 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003281}
3282
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003283MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003284 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003285
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003286 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003287 if (!PointerBaseInst)
3288 return nullptr;
3289
3290 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3291 if (!BasePtrStmt)
3292 return nullptr;
3293
3294 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3295}
3296
3297bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
Tobias Grosser4071cb52017-06-06 23:13:02 +00003298 isl::union_map Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003299 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003300 return getNonHoistableCtx(BasePtrMA, Writes).is_null();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003301 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003302
Tobias Grosserbe372d52017-02-09 10:11:58 +00003303 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003304 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003305 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003306 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003307
3308 return false;
3309}
3310
Johannes Doerfert5210da52016-06-02 11:06:54 +00003311bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003312 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003313 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003314
Johannes Doerfertcd195322016-11-17 21:41:08 +00003315 if (buildAliasGroups(AA)) {
3316 // Aliasing assumptions do not go through addAssumption but we still want to
3317 // collect statistics so we do it here explicitly.
3318 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003319 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003320 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003321 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003322
3323 // If a problem occurs while building the alias groups we need to delete
3324 // this SCoP and pretend it wasn't valid in the first place. To this end
3325 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003326 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003327
3328 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3329 << " could not be created as the number of parameters involved "
3330 "is too high. The SCoP will be "
3331 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3332 "the maximal number of parameters but be advised that the "
3333 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003334 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003335}
3336
Tobias Grosser889830b2017-02-09 23:12:22 +00003337std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003338Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003339 AliasSetTracker AST(AA);
3340
3341 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003342 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003343 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003344
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003345 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003346 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3347 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003348
3349 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003350 if (StmtDomainEmpty)
3351 continue;
3352
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003353 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003354 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003355 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003356 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003357 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003358 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003359 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003360 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003361 else
3362 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003363 AST.add(Acc);
3364 }
3365 }
3366
Tobias Grosser9edcf072017-01-16 14:07:57 +00003367 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003368 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003369 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003370 continue;
3371 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003372 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003373 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003374 if (AG.size() < 2)
3375 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003376 AliasGroups.push_back(std::move(AG));
3377 }
3378
Tobias Grosser9edcf072017-01-16 14:07:57 +00003379 return std::make_tuple(AliasGroups, HasWriteAccess);
3380}
3381
Tobias Grossere39f9122017-01-16 14:08:00 +00003382void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003383 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3384 AliasGroupTy NewAG;
3385 AliasGroupTy &AG = AliasGroups[u];
3386 AliasGroupTy::iterator AGI = AG.begin();
3387 isl_set *AGDomain = getAccessDomain(*AGI);
3388 while (AGI != AG.end()) {
3389 MemoryAccess *MA = *AGI;
3390 isl_set *MADomain = getAccessDomain(MA);
3391 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3392 NewAG.push_back(MA);
3393 AGI = AG.erase(AGI);
3394 isl_set_free(MADomain);
3395 } else {
3396 AGDomain = isl_set_union(AGDomain, MADomain);
3397 AGI++;
3398 }
3399 }
3400 if (NewAG.size() > 1)
3401 AliasGroups.push_back(std::move(NewAG));
3402 isl_set_free(AGDomain);
3403 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003404}
3405
3406bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3407 // To create sound alias checks we perform the following steps:
3408 // o) We partition each group into read only and non read only accesses.
3409 // o) For each group with more than one base pointer we then compute minimal
3410 // and maximal accesses to each array of a group in read only and non
3411 // read only partitions separately.
3412 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003413 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003414
3415 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3416
3417 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003418
Johannes Doerfert13771732014-10-01 12:40:46 +00003419 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser78a7a6c2017-06-23 08:05:31 +00003420 if (!hasFeasibleRuntimeContext())
3421 return false;
3422
Tobias Grosser57a1d362017-06-23 08:05:27 +00003423 {
3424 IslMaxOperationsGuard MaxOpGuard(getIslCtx(), OptComputeOut);
3425 bool Valid = buildAliasGroup(AG, HasWriteAccess);
3426 if (!Valid)
3427 return false;
3428 }
3429 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
3430 invalidate(COMPLEXITY, DebugLoc());
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003431 return false;
Tobias Grosser57a1d362017-06-23 08:05:27 +00003432 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003433 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003434
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003435 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003436}
3437
Tobias Grosser77f32572017-01-16 15:49:07 +00003438bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003439 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003440 AliasGroupTy ReadOnlyAccesses;
3441 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003442 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003443 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003444
Tobias Grosser77f32572017-01-16 15:49:07 +00003445 if (AliasGroup.size() < 2)
3446 return true;
3447
3448 for (MemoryAccess *Access : AliasGroup) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003449 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "PossibleAlias",
3450 Access->getAccessInstruction())
3451 << "Possibly aliasing pointer, use restrict keyword.");
Tobias Grosser889830b2017-02-09 23:12:22 +00003452 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3453 if (HasWriteAccess.count(Array)) {
3454 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003455 ReadWriteAccesses.push_back(Access);
3456 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003457 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003458 ReadOnlyAccesses.push_back(Access);
3459 }
3460 }
3461
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003462 // If there are no read-only pointers, and less than two read-write pointers,
3463 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003464 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003465 return true;
3466
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003467 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003468 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003469 return true;
3470
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003471 // For non-affine accesses, no alias check can be generated as we cannot
3472 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003473 for (MemoryAccess *MA : AliasGroup) {
3474 if (!MA->isAffine()) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003475 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc(),
3476 MA->getAccessInstruction()->getParent());
Tobias Grosser77f32572017-01-16 15:49:07 +00003477 return false;
3478 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003479 }
3480
3481 // Ensure that for all memory accesses for which we generate alias checks,
3482 // their base pointers are available.
3483 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003484 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3485 addRequiredInvariantLoad(
3486 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3487 }
3488
3489 MinMaxAliasGroups.emplace_back();
3490 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3491 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3492 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3493
3494 bool Valid;
3495
3496 Valid =
3497 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3498
3499 if (!Valid)
3500 return false;
3501
3502 // Bail out if the number of values we need to compare is too large.
3503 // This is important as the number of comparisons grows quadratically with
3504 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003505 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003506 RunTimeChecksMaxArraysPerGroup)
3507 return false;
3508
3509 Valid =
3510 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3511
3512 if (!Valid)
3513 return false;
3514
3515 return true;
3516}
3517
Tobias Grosserc80d6972016-09-02 06:33:33 +00003518/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003519static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003520 // Start with the smallest loop containing the entry and expand that
3521 // loop until it contains all blocks in the region. If there is a loop
3522 // containing all blocks in the region check if it is itself contained
3523 // and if so take the parent loop as it will be the smallest containing
3524 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003525 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003526 while (L) {
3527 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003528 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003529 AllContained &= L->contains(BB);
3530 if (AllContained)
3531 break;
3532 L = L->getParentLoop();
3533 }
3534
Johannes Doerfertef744432016-05-23 12:42:38 +00003535 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003536}
3537
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003538int Scop::NextScopID = 0;
3539
3540std::string Scop::CurrentFunc = "";
3541
3542int Scop::getNextID(std::string ParentFunc) {
3543 if (ParentFunc != CurrentFunc) {
3544 CurrentFunc = ParentFunc;
3545 NextScopID = 0;
3546 }
3547 return NextScopID++;
3548}
3549
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003550Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Eli Friedmane737fc12017-07-17 23:58:33 +00003551 ScopDetection::DetectionContext &DC, OptimizationRemarkEmitter &ORE)
Philip Pfaffe35bdcaf2017-05-15 13:43:01 +00003552 : SE(&ScalarEvolution), R(R), name(R.getNameStr()), IsOptimized(false),
Siddharth Bhat47c72372017-07-05 15:07:28 +00003553 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Eli Friedmane737fc12017-07-17 23:58:33 +00003554 MaxLoopDepth(0), CopyStmtsNum(0), SkipScop(false), DC(DC), ORE(ORE),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003555 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3556 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003557 Schedule(nullptr),
3558 ID(getNextID((*R.getEntry()->getParent()).getName().str())) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003559 if (IslOnErrorAbort)
3560 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003561 buildContext();
3562}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003563
Tobias Grosserbedef002016-12-02 08:10:56 +00003564void Scop::foldSizeConstantsToRight() {
3565 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3566
3567 for (auto Array : arrays()) {
3568 if (Array->getNumberOfDimensions() <= 1)
3569 continue;
3570
Tobias Grosser77eef902017-07-21 23:07:56 +00003571 isl_space *Space = Array->getSpace().release();
Tobias Grosserbedef002016-12-02 08:10:56 +00003572
3573 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3574
3575 if (!isl_union_set_contains(Accessed, Space)) {
3576 isl_space_free(Space);
3577 continue;
3578 }
3579
3580 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3581
3582 isl_map *Transform =
Tobias Grosser77eef902017-07-21 23:07:56 +00003583 isl_map_universe(isl_space_map_from_set(Array->getSpace().release()));
Tobias Grosserbedef002016-12-02 08:10:56 +00003584
3585 std::vector<int> Int;
3586
3587 int Dims = isl_set_dim(Elements, isl_dim_set);
3588 for (int i = 0; i < Dims; i++) {
3589 isl_set *DimOnly =
3590 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3591 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3592 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3593
3594 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3595
3596 if (i == Dims - 1) {
3597 Int.push_back(1);
3598 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3599 isl_basic_set_free(DimHull);
3600 continue;
3601 }
3602
3603 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3604 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3605 isl_val *Val = isl_aff_get_denominator_val(Diff);
3606 isl_aff_free(Diff);
3607
3608 int ValInt = 1;
3609
3610 if (isl_val_is_int(Val))
3611 ValInt = isl_val_get_num_si(Val);
3612 isl_val_free(Val);
3613
3614 Int.push_back(ValInt);
3615
3616 isl_constraint *C = isl_constraint_alloc_equality(
3617 isl_local_space_from_space(isl_map_get_space(Transform)));
3618 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3619 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3620 Transform = isl_map_add_constraint(Transform, C);
3621 isl_basic_set_free(DimHull);
3622 continue;
3623 }
3624
3625 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3626 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3627
3628 int ValInt = 1;
3629 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3630 ValInt = 0;
3631 }
3632
3633 Int.push_back(ValInt);
3634 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3635 isl_basic_set_free(DimHull);
3636 isl_basic_set_free(ZeroSet);
3637 }
3638
3639 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3640
3641 if (!isl_set_is_subset(Elements, MappedElements)) {
3642 isl_set_free(Elements);
3643 isl_set_free(MappedElements);
3644 isl_map_free(Transform);
3645 continue;
3646 }
3647
3648 isl_set_free(MappedElements);
3649
3650 bool CanFold = true;
3651
3652 if (Int[0] <= 1)
3653 CanFold = false;
3654
3655 unsigned NumDims = Array->getNumberOfDimensions();
3656 for (unsigned i = 1; i < NumDims - 1; i++)
3657 if (Int[0] != Int[i] && Int[i])
3658 CanFold = false;
3659
3660 if (!CanFold) {
3661 isl_set_free(Elements);
3662 isl_map_free(Transform);
3663 continue;
3664 }
3665
Tobias Grosserbedef002016-12-02 08:10:56 +00003666 for (auto &Access : AccessFunctions)
3667 if (Access->getScopArrayInfo() == Array)
3668 Access->setAccessRelation(isl_map_apply_range(
Tobias Grosser1515f6b2017-07-23 04:08:38 +00003669 Access->getAccessRelation().release(), isl_map_copy(Transform)));
Tobias Grosserbedef002016-12-02 08:10:56 +00003670
3671 isl_map_free(Transform);
3672
3673 std::vector<const SCEV *> Sizes;
3674 for (unsigned i = 0; i < NumDims; i++) {
3675 auto Size = Array->getDimensionSize(i);
3676
3677 if (i == NumDims - 1)
3678 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3679 Sizes.push_back(Size);
3680 }
3681
3682 Array->updateSizes(Sizes, false /* CheckConsistency */);
3683
3684 isl_set_free(Elements);
3685 }
3686 isl_union_set_free(Accessed);
3687 return;
3688}
3689
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003690void Scop::markFortranArrays() {
3691 for (ScopStmt &Stmt : Stmts) {
3692 for (MemoryAccess *MemAcc : Stmt) {
3693 Value *FAD = MemAcc->getFortranArrayDescriptor();
3694 if (!FAD)
3695 continue;
3696
3697 // TODO: const_cast-ing to edit
3698 ScopArrayInfo *SAI =
3699 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3700 assert(SAI && "memory access into a Fortran array does not "
3701 "have an associated ScopArrayInfo");
3702 SAI->applyAndSetFAD(FAD);
3703 }
3704 }
3705}
3706
Tobias Grosser491b7992016-12-02 05:21:22 +00003707void Scop::finalizeAccesses() {
3708 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003709 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003710 foldAccessRelations();
3711 assumeNoOutOfBounds();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003712 markFortranArrays();
Tobias Grosser491b7992016-12-02 05:21:22 +00003713}
3714
Tobias Grosser75805372011-04-29 06:27:02 +00003715Scop::~Scop() {
3716 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003717 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003718 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003719 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003720
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003721 for (auto &It : ParameterIds)
3722 isl_id_free(It.second);
3723
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003724 for (auto &AS : RecordedAssumptions)
3725 isl_set_free(AS.Set);
3726
Johannes Doerfertb164c792014-09-18 11:17:17 +00003727 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003728 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003729 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003730 isl_pw_multi_aff_free(MMA.first);
3731 isl_pw_multi_aff_free(MMA.second);
3732 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003733 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003734 isl_pw_multi_aff_free(MMA.first);
3735 isl_pw_multi_aff_free(MMA.second);
3736 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003737 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003738
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003739 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003740 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003741
3742 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003743 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003744 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003745 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003746 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003747 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003748 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003749}
3750
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003751void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003752 // Check all array accesses for each base pointer and find a (virtual) element
3753 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003754 for (ScopStmt &Stmt : *this)
3755 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003756 if (!Access->isArrayKind())
3757 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003758 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003759 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3760
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003761 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003762 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003763 unsigned DivisibleSize = Array->getElemSizeInBytes();
3764 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003765 while (!isDivisible(Subscript, DivisibleSize, *SE))
3766 DivisibleSize /= 2;
3767 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003768 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003769 }
3770
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003771 for (auto &Stmt : *this)
3772 for (auto &Access : Stmt)
3773 Access->updateDimensionality();
3774}
3775
Tobias Grosser491b7992016-12-02 05:21:22 +00003776void Scop::foldAccessRelations() {
3777 for (auto &Stmt : *this)
3778 for (auto &Access : Stmt)
3779 Access->foldAccessRelation();
3780}
3781
3782void Scop::assumeNoOutOfBounds() {
3783 for (auto &Stmt : *this)
3784 for (auto &Access : Stmt)
3785 Access->assumeNoOutOfBound();
3786}
3787
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003788void Scop::removeFromStmtMap(ScopStmt &Stmt) {
3789 if (Stmt.isRegionStmt())
3790 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3791 StmtMap.erase(BB);
3792 else
3793 StmtMap.erase(Stmt.getBasicBlock());
3794}
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003795
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003796void Scop::removeStmts(std::function<bool(ScopStmt &)> ShouldDelete) {
3797 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3798 if (!ShouldDelete(*StmtIt)) {
3799 StmtIt++;
3800 continue;
3801 }
3802
3803 removeFromStmtMap(*StmtIt);
3804 StmtIt = Stmts.erase(StmtIt);
3805 }
3806}
3807
3808void Scop::removeStmtNotInDomainMap() {
3809 auto ShouldDelete = [this](ScopStmt &Stmt) -> bool {
Tobias Grosser199ec4a2017-07-19 16:31:10 +00003810 return !this->DomainMap.lookup(Stmt.getEntryBlock());
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003811 };
3812 removeStmts(ShouldDelete);
3813}
3814
3815void Scop::simplifySCoP(bool AfterHoisting) {
3816
3817 auto ShouldDelete = [AfterHoisting](ScopStmt &Stmt) -> bool {
Johannes Doerfert26404542016-05-10 12:19:47 +00003818 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003819
Tobias Grosser3012a0b2017-07-16 22:44:17 +00003820 // Remove read only statements only after invariant load hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003821 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003822 bool OnlyRead = true;
3823 for (MemoryAccess *MA : Stmt) {
3824 if (MA->isRead())
3825 continue;
3826
3827 OnlyRead = false;
3828 break;
3829 }
3830
3831 RemoveStmt = OnlyRead;
3832 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003833 return RemoveStmt;
3834 };
Johannes Doerferteca9e892015-11-03 16:54:49 +00003835
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003836 removeStmts(ShouldDelete);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003837}
3838
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003839InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003840 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3841 if (!LInst)
3842 return nullptr;
3843
3844 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3845 LInst = cast<LoadInst>(Rep);
3846
Johannes Doerfert96e54712016-02-07 17:30:13 +00003847 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003848 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003849 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003850 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003851 continue;
3852
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003853 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003854 for (auto *MA : MAs)
3855 if (MA->getAccessInstruction() == Val)
3856 return &IAClass;
3857 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003858
3859 return nullptr;
3860}
3861
Tobias Grosserc80d6972016-09-02 06:33:33 +00003862/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003863static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003864 bool MAInvalidCtxIsEmpty,
3865 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003866 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3867 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3868 // TODO: We can provide more information for better but more expensive
3869 // results.
3870 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3871 LInst->getAlignment(), DL))
3872 return false;
3873
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003874 // If the location might be overwritten we do not hoist it unconditionally.
3875 //
3876 // TODO: This is probably to conservative.
3877 if (!NonHoistableCtxIsEmpty)
3878 return false;
3879
Michael Krusea6d48f52017-06-08 12:06:15 +00003880 // If a dereferenceable load is in a statement that is modeled precisely we
3881 // can hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003882 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003883 return true;
3884
3885 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003886 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003887 // statement domain.
3888 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3889 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3890 return false;
3891 return true;
3892}
3893
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003894void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003895
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003896 if (InvMAs.empty())
3897 return;
3898
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003899 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003900 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003901
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003902 // Get the context under which the statement is executed but remove the error
3903 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003904 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003905 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003906
Tobias Grosser90411a92017-02-16 19:11:33 +00003907 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003908 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Eli Friedmane737fc12017-07-17 23:58:33 +00003909 invalidate(COMPLEXITY, AccInst->getDebugLoc(), AccInst->getParent());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003910 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003911 for (auto &InvMA : InvMAs)
3912 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003913 return;
3914 }
3915
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003916 // Project out all parameters that relate to loads in the statement. Otherwise
3917 // we could have cyclic dependences on the constraints under which the
3918 // hoisted loads are executed and we could not determine an order in which to
3919 // pre-load them. This happens because not only lower bounds are part of the
3920 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003921 for (auto &InvMA : InvMAs) {
3922 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003923 Instruction *AccInst = MA->getAccessInstruction();
3924 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003925 SetVector<Value *> Values;
3926 for (const SCEV *Parameter : Parameters) {
3927 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003928 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003929 if (!Values.count(AccInst))
3930 continue;
3931
3932 if (isl_id *ParamId = getIdForParam(Parameter)) {
3933 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003934 if (Dim >= 0)
3935 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003936 isl_id_free(ParamId);
3937 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003938 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003939 }
3940 }
3941
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003942 for (auto &InvMA : InvMAs) {
3943 auto *MA = InvMA.MA;
3944 auto *NHCtx = InvMA.NonHoistableCtx;
3945
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003946 // Check for another invariant access that accesses the same location as
3947 // MA and if found consolidate them. Otherwise create a new equivalence
3948 // class at the end of InvariantEquivClasses.
3949 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003950 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003951 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3952
Johannes Doerfert85676e32016-04-23 14:32:34 +00003953 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003954 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003955 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3956
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003957 isl_set *MACtx;
3958 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003959 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3960 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003961 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003962 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003963 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003964 } else {
3965 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003966 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003967 MACtx = isl_set_gist_params(MACtx, getContext());
3968 }
3969
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003970 bool Consolidated = false;
3971 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003972 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003973 continue;
3974
Johannes Doerfertdf880232016-03-03 12:26:58 +00003975 // If the pointer and the type is equal check if the access function wrt.
3976 // to the domain is equal too. It can happen that the domain fixes
3977 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003978 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003979 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003980 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003981 if (!MAs.empty()) {
3982 auto *LastMA = MAs.front();
3983
Tobias Grosser1515f6b2017-07-23 04:08:38 +00003984 auto *AR = isl_map_range(MA->getAccessRelation().release());
3985 auto *LastAR = isl_map_range(LastMA->getAccessRelation().release());
Johannes Doerfertdf880232016-03-03 12:26:58 +00003986 bool SameAR = isl_set_is_equal(AR, LastAR);
3987 isl_set_free(AR);
3988 isl_set_free(LastAR);
3989
3990 if (!SameAR)
3991 continue;
3992 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003993
3994 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003995 MAs.push_front(MA);
3996
Johannes Doerfertdf880232016-03-03 12:26:58 +00003997 Consolidated = true;
3998
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003999 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004000 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00004001 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00004002 IAClassDomainCtx =
4003 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00004004 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00004005 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004006 break;
4007 }
4008
4009 if (Consolidated)
4010 continue;
4011
4012 // If we did not consolidate MA, thus did not find an equivalence class
4013 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004014 InvariantEquivClasses.emplace_back(
4015 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004016 }
4017
4018 isl_set_free(DomainCtx);
4019}
4020
Tobias Grosser1eeedf42017-07-20 19:55:19 +00004021/// Check if an access range is too complex.
4022///
4023/// An access range is too complex, if it contains either many disjuncts or
4024/// very complex expressions. As a simple heuristic, we assume if a set to
4025/// be too complex if the sum of existentially quantified dimensions and
4026/// set dimensions is larger than a threshold. This reliably detects both
4027/// sets with many disjuncts as well as sets with many divisions as they
4028/// arise in h264.
4029///
4030/// @param AccessRange The range to check for complexity.
4031///
4032/// @returns True if the access range is too complex.
4033static bool isAccessRangeTooComplex(isl::set AccessRange) {
4034 unsigned NumTotalDims = 0;
4035
4036 auto CountDimensions = [&NumTotalDims](isl::basic_set BSet) -> isl::stat {
4037 NumTotalDims += BSet.dim(isl::dim::div);
4038 NumTotalDims += BSet.dim(isl::dim::set);
4039 return isl::stat::ok;
4040 };
4041
4042 AccessRange.foreach_basic_set(CountDimensions);
4043
4044 if (NumTotalDims > MaxDimensionsInAccessRange)
4045 return true;
4046
4047 return false;
4048}
4049
Tobias Grosser4071cb52017-06-06 23:13:02 +00004050isl::set Scop::getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004051 // TODO: Loads that are not loop carried, hence are in a statement with
4052 // zero iterators, are by construction invariant, though we
4053 // currently "hoist" them anyway. This is necessary because we allow
4054 // them to be treated as parameters (e.g., in conditions) and our code
4055 // generation would otherwise use the old value.
4056
4057 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00004058 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004059
Johannes Doerfertc9765462016-11-17 22:11:56 +00004060 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
4061 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004062 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004063
4064 // Skip accesses that have an invariant base pointer which is defined but
4065 // not loaded inside the SCoP. This can happened e.g., if a readnone call
4066 // returns a pointer that is used as a base address. However, as we want
4067 // to hoist indirect pointers, we allow the base pointer to be defined in
4068 // the region if it is also a memory access. Each ScopArrayInfo object
4069 // that has a base pointer origin has a base pointer that is loaded and
4070 // that it is invariant, thus it will be hoisted too. However, if there is
4071 // no base pointer origin we check that the base pointer is defined
4072 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004073 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00004074 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004075 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004076
Tobias Grosser1515f6b2017-07-23 04:08:38 +00004077 isl::map AccessRelation = give(Access->getAccessRelation().release());
Tobias Grosser4071cb52017-06-06 23:13:02 +00004078 assert(!AccessRelation.is_empty());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004079
Tobias Grosser4071cb52017-06-06 23:13:02 +00004080 if (AccessRelation.involves_dims(isl::dim::in, 0, Stmt.getNumIterators()))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004081 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004082
Tobias Grosser4071cb52017-06-06 23:13:02 +00004083 AccessRelation = AccessRelation.intersect_domain(give(Stmt.getDomain()));
4084 isl::set SafeToLoad;
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004085
4086 auto &DL = getFunction().getParent()->getDataLayout();
4087 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
4088 DL)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00004089 SafeToLoad = isl::set::universe(AccessRelation.get_space().range());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004090 } else if (BB != LI->getParent()) {
4091 // Skip accesses in non-affine subregions as they might not be executed
4092 // under the same condition as the entry of the non-affine subregion.
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004093 return nullptr;
4094 } else {
Tobias Grosser4071cb52017-06-06 23:13:02 +00004095 SafeToLoad = AccessRelation.range();
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004096 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004097
Tobias Grosser1eeedf42017-07-20 19:55:19 +00004098 if (isAccessRangeTooComplex(AccessRelation.range()))
4099 return nullptr;
4100
Tobias Grosser4071cb52017-06-06 23:13:02 +00004101 isl::union_map Written = Writes.intersect_range(SafeToLoad);
4102 isl::set WrittenCtx = Written.params();
4103 bool IsWritten = !WrittenCtx.is_empty();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004104
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004105 if (!IsWritten)
4106 return WrittenCtx;
4107
Tobias Grosser4071cb52017-06-06 23:13:02 +00004108 WrittenCtx = WrittenCtx.remove_divs();
4109 bool TooComplex =
4110 isl_set_n_basic_set(WrittenCtx.get()) >= MaxDisjunctsInDomain;
4111 if (TooComplex || !isRequiredInvariantLoad(LI))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004112 return nullptr;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004113
Tobias Grosser4071cb52017-06-06 23:13:02 +00004114 addAssumption(INVARIANTLOAD, WrittenCtx.copy(), LI->getDebugLoc(),
Eli Friedmane737fc12017-07-17 23:58:33 +00004115 AS_RESTRICTION, LI->getParent());
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004116 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004117}
4118
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004119void Scop::verifyInvariantLoads() {
4120 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004121 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00004122 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00004123 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00004124 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004125 invalidate(INVARIANTLOAD, LI->getDebugLoc(), LI->getParent());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004126 return;
4127 }
4128 }
4129}
4130
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004131void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00004132 if (!PollyInvariantLoadHoisting)
4133 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004134
Tobias Grosser4071cb52017-06-06 23:13:02 +00004135 isl::union_map Writes = give(getWrites());
Tobias Grosser0865e7752016-02-29 07:29:42 +00004136 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004137 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004138
Tobias Grosser0865e7752016-02-29 07:29:42 +00004139 for (MemoryAccess *Access : Stmt)
Tobias Grosser4071cb52017-06-06 23:13:02 +00004140 if (isl::set NHCtx = getNonHoistableCtx(Access, Writes))
4141 InvariantAccesses.push_back({Access, NHCtx.release()});
Tobias Grosser0865e7752016-02-29 07:29:42 +00004142
4143 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00004144 for (auto InvMA : InvariantAccesses)
4145 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00004146 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004147 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004148}
4149
Tobias Grosserf3adab42017-05-10 10:59:58 +00004150/// Find the canonical scop array info object for a set of invariant load
4151/// hoisted loads. The canonical array is the one that corresponds to the
4152/// first load in the list of accesses which is used as base pointer of a
4153/// scop array.
4154static const ScopArrayInfo *findCanonicalArray(Scop *S,
4155 MemoryAccessList &Accesses) {
4156 for (MemoryAccess *Access : Accesses) {
4157 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
4158 Access->getAccessInstruction(), MemoryKind::Array);
4159 if (CanonicalArray)
4160 return CanonicalArray;
4161 }
4162 return nullptr;
4163}
4164
4165/// Check if @p Array severs as base array in an invariant load.
4166static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
4167 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
4168 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
4169 if (Access2->getScopArrayInfo() == Array)
4170 return true;
4171 return false;
4172}
4173
4174/// Replace the base pointer arrays in all memory accesses referencing @p Old,
4175/// with a reference to @p New.
4176static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
4177 const ScopArrayInfo *New) {
4178 for (ScopStmt &Stmt : *S)
4179 for (MemoryAccess *Access : Stmt) {
4180 if (Access->getLatestScopArrayInfo() != Old)
4181 continue;
4182
Tobias Grosser77eef902017-07-21 23:07:56 +00004183 isl_id *Id = New->getBasePtrId().release();
Tobias Grosser1515f6b2017-07-23 04:08:38 +00004184 isl_map *Map = Access->getAccessRelation().release();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004185 Map = isl_map_set_tuple_id(Map, isl_dim_out, Id);
4186 Access->setAccessRelation(Map);
4187 }
4188}
4189
4190void Scop::canonicalizeDynamicBasePtrs() {
4191 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
4192 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
4193
4194 const ScopArrayInfo *CanonicalBasePtrSAI =
4195 findCanonicalArray(this, BasePtrAccesses);
4196
4197 if (!CanonicalBasePtrSAI)
4198 continue;
4199
4200 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
4201 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
4202 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
4203 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
4204 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
4205 continue;
4206
4207 // we currently do not canonicalize arrays where some accesses are
4208 // hoisted as invariant loads. If we would, we need to update the access
4209 // function of the invariant loads as well. However, as this is not a
4210 // very common situation, we leave this for now to avoid further
4211 // complexity increases.
4212 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
4213 continue;
4214
4215 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
4216 }
4217 }
4218}
4219
Michael Kruseb738ffa2017-06-28 13:02:43 +00004220ScopArrayInfo *Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
4221 ArrayRef<const SCEV *> Sizes,
4222 MemoryKind Kind,
4223 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004224 assert((BasePtr || BaseName) &&
4225 "BasePtr and BaseName can not be nullptr at the same time.");
4226 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
4227 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
4228 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004229 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004230 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00004231 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00004232 DL, this, BaseName));
4233 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004234 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004235 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00004236 // In case of mismatching array sizes, we bail out by setting the run-time
4237 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004238 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004239 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004240 }
Tobias Grosserab671442015-05-23 05:58:27 +00004241 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004242}
4243
Michael Kruseb738ffa2017-06-28 13:02:43 +00004244ScopArrayInfo *Scop::createScopArrayInfo(Type *ElementType,
4245 const std::string &BaseName,
4246 const std::vector<unsigned> &Sizes) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004247 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
4248 std::vector<const SCEV *> SCEVSizes;
4249
4250 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00004251 if (size)
4252 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
4253 else
4254 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00004255
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004256 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
4257 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00004258 return SAI;
4259}
4260
Tobias Grosserf3adab42017-05-10 10:59:58 +00004261const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
4262 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00004263 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004264 return SAI;
4265}
4266
4267const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
4268 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004269 assert(SAI && "No ScopArrayInfo available for this base pointer");
4270 return SAI;
4271}
4272
Tobias Grosser74394f02013-01-14 22:40:23 +00004273std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004274
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004275std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004276 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004277 return stringFromIslObj(AssumedContext);
4278}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004279
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004280std::string Scop::getInvalidContextStr() const {
4281 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004282}
Tobias Grosser75805372011-04-29 06:27:02 +00004283
4284std::string Scop::getNameStr() const {
4285 std::string ExitName, EntryName;
Siddharth Bhat07bee292017-06-02 08:01:22 +00004286 std::tie(EntryName, ExitName) = getEntryExitStr();
4287 return EntryName + "---" + ExitName;
4288}
4289
4290std::pair<std::string, std::string> Scop::getEntryExitStr() const {
4291 std::string ExitName, EntryName;
Tobias Grosser75805372011-04-29 06:27:02 +00004292 raw_string_ostream ExitStr(ExitName);
4293 raw_string_ostream EntryStr(EntryName);
4294
Tobias Grosserf240b482014-01-09 10:42:15 +00004295 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004296 EntryStr.str();
4297
4298 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00004299 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004300 ExitStr.str();
4301 } else
4302 ExitName = "FunctionExit";
4303
Siddharth Bhat07bee292017-06-02 08:01:22 +00004304 return std::make_pair(EntryName, ExitName);
Tobias Grosser75805372011-04-29 06:27:02 +00004305}
4306
Tobias Grosser74394f02013-01-14 22:40:23 +00004307__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00004308__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00004309 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00004310}
4311
Tobias Grossere86109f2013-10-29 21:05:49 +00004312__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004313 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00004314 return isl_set_copy(AssumedContext);
4315}
4316
Michael Krusef3091bf2017-03-17 13:09:52 +00004317bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004318 if (PollyProcessUnprofitable)
4319 return true;
4320
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004321 if (isEmpty())
4322 return false;
4323
4324 unsigned OptimizableStmtsOrLoops = 0;
4325 for (auto &Stmt : *this) {
4326 if (Stmt.getNumIterators() == 0)
4327 continue;
4328
4329 bool ContainsArrayAccs = false;
4330 bool ContainsScalarAccs = false;
4331 for (auto *MA : Stmt) {
4332 if (MA->isRead())
4333 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004334 ContainsArrayAccs |= MA->isLatestArrayKind();
4335 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004336 }
4337
Michael Krusef3091bf2017-03-17 13:09:52 +00004338 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004339 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4340 }
4341
4342 return OptimizableStmtsOrLoops > 1;
4343}
4344
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004345bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004346 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004347 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00004348 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4349 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4350 isl_set_is_subset(PositiveContext, NegativeContext));
4351 isl_set_free(PositiveContext);
4352 if (!IsFeasible) {
4353 isl_set_free(NegativeContext);
4354 return false;
4355 }
4356
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004357 auto *DomainContext = isl_union_set_params(getDomains());
4358 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00004359 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004360 isl_set_free(NegativeContext);
4361 isl_set_free(DomainContext);
4362
Johannes Doerfert43788c52015-08-20 05:58:56 +00004363 return IsFeasible;
4364}
4365
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004366static std::string toString(AssumptionKind Kind) {
4367 switch (Kind) {
4368 case ALIASING:
4369 return "No-aliasing";
4370 case INBOUNDS:
4371 return "Inbounds";
4372 case WRAPPING:
4373 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004374 case UNSIGNED:
4375 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004376 case COMPLEXITY:
4377 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004378 case PROFITABLE:
4379 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004380 case ERRORBLOCK:
4381 return "No-error";
4382 case INFINITELOOP:
4383 return "Finite loop";
4384 case INVARIANTLOAD:
4385 return "Invariant load";
4386 case DELINEARIZATION:
4387 return "Delinearization";
4388 }
4389 llvm_unreachable("Unknown AssumptionKind!");
4390}
4391
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004392bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4393 if (Sign == AS_ASSUMPTION) {
4394 if (isl_set_is_subset(Context, Set))
4395 return false;
4396
4397 if (isl_set_is_subset(AssumedContext, Set))
4398 return false;
4399 } else {
4400 if (isl_set_is_disjoint(Set, Context))
4401 return false;
4402
4403 if (isl_set_is_subset(Set, InvalidContext))
4404 return false;
4405 }
4406 return true;
4407}
4408
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004409bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004410 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004411 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4412 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004413
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004414 // Do never emit trivial assumptions as they only clutter the output.
4415 if (!PollyRemarksMinimal) {
4416 isl_set *Univ = nullptr;
4417 if (Sign == AS_ASSUMPTION)
4418 Univ = isl_set_universe(isl_set_get_space(Set));
4419
4420 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4421 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4422 isl_set_free(Univ);
4423
4424 if (IsTrivial)
4425 return false;
4426 }
4427
Johannes Doerfertcd195322016-11-17 21:41:08 +00004428 switch (Kind) {
4429 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004430 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004431 break;
4432 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004433 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004434 break;
4435 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004436 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004437 break;
4438 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004439 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004440 break;
4441 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004442 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004443 break;
4444 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004445 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004446 break;
4447 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004448 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004449 break;
4450 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004451 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004452 break;
4453 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004454 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004455 break;
4456 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004457 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004458 break;
4459 }
4460
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004461 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4462 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Eli Friedmane737fc12017-07-17 23:58:33 +00004463 if (BB)
4464 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc, BB)
4465 << Msg);
4466 else
4467 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc,
4468 R.getEntry())
4469 << Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004470 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004471}
4472
4473void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004474 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004475 // Simplify the assumptions/restrictions first.
4476 Set = isl_set_gist_params(Set, getContext());
4477
Eli Friedmane737fc12017-07-17 23:58:33 +00004478 if (!trackAssumption(Kind, Set, Loc, Sign, BB)) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004479 isl_set_free(Set);
4480 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004481 }
4482
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004483 if (Sign == AS_ASSUMPTION) {
4484 AssumedContext = isl_set_intersect(AssumedContext, Set);
4485 AssumedContext = isl_set_coalesce(AssumedContext);
4486 } else {
4487 InvalidContext = isl_set_union(InvalidContext, Set);
4488 InvalidContext = isl_set_coalesce(InvalidContext);
4489 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004490}
4491
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004492void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004493 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004494 assert((isl_set_is_params(Set) || BB) &&
4495 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004496 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004497}
4498
4499void Scop::addRecordedAssumptions() {
4500 while (!RecordedAssumptions.empty()) {
4501 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004502
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004503 if (!AS.BB) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004504 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign, nullptr /* BasicBlock */);
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004505 continue;
4506 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004507
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004508 // If the domain was deleted the assumptions are void.
4509 isl_set *Dom = getDomainConditions(AS.BB);
4510 if (!Dom) {
4511 isl_set_free(AS.Set);
4512 continue;
4513 }
4514
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004515 // If a basic block was given use its domain to simplify the assumption.
4516 // In case of restrictions we know they only have to hold on the domain,
4517 // thus we can intersect them with the domain of the block. However, for
4518 // assumptions the domain has to imply them, thus:
4519 // _ _____
4520 // Dom => S <==> A v B <==> A - B
4521 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004522 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004523 // assumption.
4524 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004525 if (AS.Sign == AS_RESTRICTION)
4526 S = isl_set_params(isl_set_intersect(S, Dom));
4527 else /* (AS.Sign == AS_ASSUMPTION) */
4528 S = isl_set_params(isl_set_subtract(Dom, S));
4529
Eli Friedmane737fc12017-07-17 23:58:33 +00004530 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION, AS.BB);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004531 }
4532}
4533
Eli Friedmane737fc12017-07-17 23:58:33 +00004534void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB) {
4535 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION, BB);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004536}
4537
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004538__isl_give isl_set *Scop::getInvalidContext() const {
4539 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004540}
4541
Tobias Grosser75805372011-04-29 06:27:02 +00004542void Scop::printContext(raw_ostream &OS) const {
4543 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004544 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004545
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004546 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004547 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004548
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004549 OS.indent(4) << "Invalid Context:\n";
4550 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004551
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004552 unsigned Dim = 0;
4553 for (const SCEV *Parameter : Parameters)
4554 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004555}
4556
Johannes Doerfertb164c792014-09-18 11:17:17 +00004557void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004558 int noOfGroups = 0;
4559 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004560 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004561 noOfGroups += 1;
4562 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004563 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004564 }
4565
Tobias Grosserbb853c22015-07-25 12:31:03 +00004566 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004567 if (MinMaxAliasGroups.empty()) {
4568 OS.indent(8) << "n/a\n";
4569 return;
4570 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004571
Tobias Grosserbb853c22015-07-25 12:31:03 +00004572 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004573
4574 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004575 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004576 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004577 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004578 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4579 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004580 }
4581 OS << " ]]\n";
4582 }
4583
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004584 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004585 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004586 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004587 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004588 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4589 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004590 }
4591 OS << " ]]\n";
4592 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004593 }
4594}
4595
Michael Krusecd4c9772017-07-21 15:35:53 +00004596void Scop::printStatements(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00004597 OS << "Statements {\n";
4598
Michael Krusecd4c9772017-07-21 15:35:53 +00004599 for (const ScopStmt &Stmt : *this) {
4600 OS.indent(4);
4601 Stmt.print(OS, PrintInstructions);
4602 }
Tobias Grosser75805372011-04-29 06:27:02 +00004603
4604 OS.indent(4) << "}\n";
4605}
4606
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004607void Scop::printArrayInfo(raw_ostream &OS) const {
4608 OS << "Arrays {\n";
4609
Tobias Grosserab671442015-05-23 05:58:27 +00004610 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004611 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004612
4613 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004614
4615 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4616
4617 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004618 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004619
4620 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004621}
4622
Michael Krusecd4c9772017-07-21 15:35:53 +00004623void Scop::print(raw_ostream &OS, bool PrintInstructions) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004624 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004625 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004626 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004627 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004628 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004629 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004630 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004631 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004632 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004633 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004634 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4635 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004636 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004637 }
4638 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004639 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004640 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004641 printAliasAssumptions(OS);
Michael Krusecd4c9772017-07-21 15:35:53 +00004642 printStatements(OS.indent(4), PrintInstructions);
Tobias Grosser75805372011-04-29 06:27:02 +00004643}
4644
Michael Kruse5d518462017-07-21 15:54:07 +00004645#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00004646LLVM_DUMP_METHOD void Scop::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00004647#endif
Tobias Grosser75805372011-04-29 06:27:02 +00004648
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004649isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004650
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004651__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4652 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004653 // First try to use the SCEVAffinator to generate a piecewise defined
4654 // affine function from @p E in the context of @p BB. If that tasks becomes to
4655 // complex the affinator might return a nullptr. In such a case we invalidate
4656 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004657 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004658 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004659 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004660 // TODO: We could use a heuristic and either use:
4661 // SCEVAffinator::takeNonNegativeAssumption
4662 // or
4663 // SCEVAffinator::interpretAsUnsigned
4664 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004665 if (NonNegative)
4666 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004667 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004668 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004669
4670 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
Eli Friedmane737fc12017-07-17 23:58:33 +00004671 invalidate(COMPLEXITY, DL, BB);
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004672 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004673}
4674
Tobias Grosser808cd692015-07-14 09:33:13 +00004675__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004676 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4677 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004678
Tobias Grosser808cd692015-07-14 09:33:13 +00004679 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004680 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004681
4682 return Domain;
4683}
4684
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004685__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4686 PWACtx PWAC = getPwAff(E, BB);
4687 isl_set_free(PWAC.second);
4688 return PWAC.first;
4689}
4690
Tobias Grossere5a35142015-11-12 14:07:09 +00004691__isl_give isl_union_map *
4692Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4693 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004694
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004695 for (ScopStmt &Stmt : *this) {
4696 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004697 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004698 continue;
4699
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004700 isl_set *Domain = Stmt.getDomain();
Tobias Grosser1515f6b2017-07-23 04:08:38 +00004701 isl_map *AccessDomain = MA->getAccessRelation().release();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004702 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004703 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004704 }
4705 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004706 return isl_union_map_coalesce(Accesses);
4707}
4708
4709__isl_give isl_union_map *Scop::getMustWrites() {
4710 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004711}
4712
4713__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004714 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004715}
4716
Tobias Grosser37eb4222014-02-20 21:43:54 +00004717__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004718 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004719}
4720
4721__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004722 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004723}
4724
Tobias Grosser2ac23382015-11-12 14:07:13 +00004725__isl_give isl_union_map *Scop::getAccesses() {
4726 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4727}
4728
Roman Gareevb3224ad2016-09-14 06:26:09 +00004729// Check whether @p Node is an extension node.
4730//
4731// @return true if @p Node is an extension node.
4732isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4733 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4734 return isl_bool_error;
4735 else
4736 return isl_bool_true;
4737}
4738
4739bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4740 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4741 nullptr) == isl_stat_error;
4742}
4743
Tobias Grosser808cd692015-07-14 09:33:13 +00004744__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004745 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004746 if (containsExtensionNode(Tree)) {
4747 isl_schedule_free(Tree);
4748 return nullptr;
4749 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004750 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004751 isl_schedule_free(Tree);
4752 return S;
4753}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004754
Tobias Grosser808cd692015-07-14 09:33:13 +00004755__isl_give isl_schedule *Scop::getScheduleTree() const {
4756 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4757 getDomains());
4758}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004759
Tobias Grosser808cd692015-07-14 09:33:13 +00004760void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4761 auto *S = isl_schedule_from_domain(getDomains());
4762 S = isl_schedule_insert_partial_schedule(
4763 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4764 isl_schedule_free(Schedule);
4765 Schedule = S;
4766}
4767
4768void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4769 isl_schedule_free(Schedule);
4770 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004771}
4772
4773bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4774 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004775 for (ScopStmt &Stmt : *this) {
4776 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004777 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4778 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4779
4780 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4781 isl_union_set_free(StmtDomain);
4782 isl_union_set_free(NewStmtDomain);
4783 continue;
4784 }
4785
4786 Changed = true;
4787
4788 isl_union_set_free(StmtDomain);
4789 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4790
4791 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004792 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004793 isl_union_set_free(NewStmtDomain);
4794 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004795 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004796 }
4797 isl_union_set_free(Domain);
4798 return Changed;
4799}
4800
Tobias Grosser75805372011-04-29 06:27:02 +00004801ScalarEvolution *Scop::getSE() const { return SE; }
4802
Tobias Grosserc80d6972016-09-02 06:33:33 +00004803// Create an isl_multi_union_aff that defines an identity mapping from the
4804// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004805//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004806// # Example:
4807//
4808// Domain: { A[i,j]; B[i,j,k] }
4809// N: 1
4810//
4811// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4812//
4813// @param USet A union set describing the elements for which to generate a
4814// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004815// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004816// @returns A mapping from USet to its N-th dimension.
Tobias Grosser99320862017-05-26 17:22:03 +00004817static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) {
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004818 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004819 assert(USet);
Siddharth Bhat8bb436e2017-05-29 11:34:29 +00004820 assert(!USet.is_empty());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004821
Tobias Grosser99320862017-05-26 17:22:03 +00004822 auto Result = isl::union_pw_multi_aff::empty(USet.get_space());
Tobias Grosser808cd692015-07-14 09:33:13 +00004823
Tobias Grosser99320862017-05-26 17:22:03 +00004824 auto Lambda = [&Result, N](isl::set S) -> isl::stat {
4825 int Dim = S.dim(isl::dim::set);
4826 auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set,
4827 N, Dim - N);
4828 if (N > 1)
4829 PMA = PMA.drop_dims(isl::dim::out, 0, N - 1);
Tobias Grosser808cd692015-07-14 09:33:13 +00004830
Tobias Grosser99320862017-05-26 17:22:03 +00004831 Result = Result.add_pw_multi_aff(PMA);
4832 return isl::stat::ok;
4833 };
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004834
Tobias Grosser99320862017-05-26 17:22:03 +00004835 isl::stat Res = USet.foreach_set(Lambda);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004836 (void)Res;
4837
Tobias Grosser99320862017-05-26 17:22:03 +00004838 assert(Res == isl::stat::ok);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004839
Tobias Grosser99320862017-05-26 17:22:03 +00004840 return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result));
Tobias Grosser808cd692015-07-14 09:33:13 +00004841}
4842
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004843void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop,
4844 std::vector<Instruction *> Instructions) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004845 assert(BB && "Unexpected nullptr!");
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004846 Stmts.emplace_back(*this, *BB, SurroundingLoop, Instructions);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004847 auto *Stmt = &Stmts.back();
Michael Kruse4dfa7322017-07-18 15:41:49 +00004848 StmtMap[BB].push_back(Stmt);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004849}
4850
Michael Kruse55454072017-03-15 22:16:43 +00004851void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004852 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004853 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004854 auto *Stmt = &Stmts.back();
4855 for (BasicBlock *BB : R->blocks())
Michael Kruse4dfa7322017-07-18 15:41:49 +00004856 StmtMap[BB].push_back(Stmt);
Tobias Grosser808cd692015-07-14 09:33:13 +00004857}
4858
Roman Gareevb3224ad2016-09-14 06:26:09 +00004859ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4860 __isl_take isl_map *TargetRel,
4861 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004862#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004863 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4864 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4865 assert(isl_set_is_subset(Domain, TargetDomain) &&
4866 "Target access not defined for complete statement domain");
4867 assert(isl_set_is_subset(Domain, SourceDomain) &&
4868 "Source access not defined for complete statement domain");
4869 isl_set_free(SourceDomain);
4870 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004871#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004872 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4873 CopyStmtsNum++;
4874 return &(Stmts.back());
4875}
4876
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004877void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004878 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004879 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004880 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004881 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4882 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004883}
4884
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004885/// To generate a schedule for the elements in a Region we traverse the Region
4886/// in reverse-post-order and add the contained RegionNodes in traversal order
4887/// to the schedule of the loop that is currently at the top of the LoopStack.
4888/// For loop-free codes, this results in a correct sequential ordering.
4889///
4890/// Example:
4891/// bb1(0)
4892/// / \.
4893/// bb2(1) bb3(2)
4894/// \ / \.
4895/// bb4(3) bb5(4)
4896/// \ /
4897/// bb6(5)
4898///
4899/// Including loops requires additional processing. Whenever a loop header is
4900/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4901/// from an empty schedule, we first process all RegionNodes that are within
4902/// this loop and complete the sequential schedule at this loop-level before
4903/// processing about any other nodes. To implement this
4904/// loop-nodes-first-processing, the reverse post-order traversal is
4905/// insufficient. Hence, we additionally check if the traversal yields
4906/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4907/// These region-nodes are then queue and only traverse after the all nodes
4908/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004909void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004910 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004911
4912 ReversePostOrderTraversal<Region *> RTraversal(R);
4913 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4914 std::deque<RegionNode *> DelayList;
4915 bool LastRNWaiting = false;
4916
4917 // Iterate over the region @p R in reverse post-order but queue
4918 // sub-regions/blocks iff they are not part of the last encountered but not
4919 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4920 // that we queued the last sub-region/block from the reverse post-order
4921 // iterator. If it is set we have to explore the next sub-region/block from
4922 // the iterator (if any) to guarantee progress. If it is not set we first try
4923 // the next queued sub-region/blocks.
4924 while (!WorkList.empty() || !DelayList.empty()) {
4925 RegionNode *RN;
4926
4927 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4928 RN = WorkList.front();
4929 WorkList.pop_front();
4930 LastRNWaiting = false;
4931 } else {
4932 RN = DelayList.front();
4933 DelayList.pop_front();
4934 }
4935
4936 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004937 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004938 L = OuterScopLoop;
4939
Tobias Grosser151ae322016-04-03 19:36:52 +00004940 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004941 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004942 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004943 LastRNWaiting = true;
4944 DelayList.push_back(RN);
4945 continue;
4946 }
4947 LoopStack.push_back({L, nullptr, 0});
4948 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004949 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004950 }
4951
4952 return;
4953}
4954
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004955void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004956
Tobias Grosser8362c262016-01-06 15:30:06 +00004957 if (RN->isSubRegion()) {
4958 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004959 if (!isNonAffineSubRegion(LocalRegion)) {
4960 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004961 return;
4962 }
4963 }
Michael Kruse046dde42015-08-10 13:01:57 +00004964
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004965 auto &LoopData = LoopStack.back();
4966 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004967
Michael Kruse1ce67912017-07-20 17:18:58 +00004968 for (auto *Stmt : getStmtListFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004969 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4970 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004971 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004972 }
4973
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004974 // Check if we just processed the last node in this loop. If we did, finalize
4975 // the loop by:
4976 //
4977 // - adding new schedule dimensions
4978 // - folding the resulting schedule into the parent loop schedule
4979 // - dropping the loop schedule from the LoopStack.
4980 //
4981 // Then continue to check surrounding loops, which might also have been
4982 // completed by this node.
4983 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00004984 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004985 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004986 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004987
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004988 LoopStack.pop_back();
4989 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004990
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004991 if (Schedule) {
Tobias Grosser99320862017-05-26 17:22:03 +00004992 isl::union_set Domain = give(isl_schedule_get_domain(Schedule));
4993 isl::multi_union_pw_aff MUPA = mapToDimension(Domain, LoopStack.size());
4994 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA.release());
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004995 NextLoopData.Schedule =
4996 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004997 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004998
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004999 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
5000 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00005001 }
Tobias Grosser75805372011-04-29 06:27:02 +00005002}
5003
Michael Kruse6f7721f2016-02-24 22:08:19 +00005004ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00005005 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00005006 if (StmtMapIt == StmtMap.end())
5007 return nullptr;
Michael Kruse4dfa7322017-07-18 15:41:49 +00005008 assert(StmtMapIt->second.size() == 1);
5009 return StmtMapIt->second.front();
Johannes Doerfert7c494212014-10-31 23:13:39 +00005010}
5011
Michael Kruse6eba4b12017-07-20 17:08:50 +00005012ArrayRef<ScopStmt *> Scop::getStmtListFor(BasicBlock *BB) const {
5013 auto StmtMapIt = StmtMap.find(BB);
5014 if (StmtMapIt == StmtMap.end())
5015 return {};
5016 assert(StmtMapIt->second.size() == 1 &&
5017 "Each statement corresponds to exactly one BB.");
5018 return StmtMapIt->second;
5019}
5020
5021ScopStmt *Scop::getLastStmtFor(BasicBlock *BB) const {
5022 ArrayRef<ScopStmt *> StmtList = getStmtListFor(BB);
5023 if (StmtList.size() > 0)
5024 return StmtList.back();
5025 return nullptr;
5026}
5027
Michael Kruse1ce67912017-07-20 17:18:58 +00005028ArrayRef<ScopStmt *> Scop::getStmtListFor(RegionNode *RN) const {
Michael Kruse6f7721f2016-02-24 22:08:19 +00005029 if (RN->isSubRegion())
Michael Kruse1ce67912017-07-20 17:18:58 +00005030 return getStmtListFor(RN->getNodeAs<Region>());
5031 return getStmtListFor(RN->getNodeAs<BasicBlock>());
Michael Kruse6f7721f2016-02-24 22:08:19 +00005032}
5033
Michael Kruse1ce67912017-07-20 17:18:58 +00005034ArrayRef<ScopStmt *> Scop::getStmtListFor(Region *R) const {
5035 return getStmtListFor(R->getEntry());
Michael Krusea902ba62015-12-13 19:21:45 +00005036}
5037
Johannes Doerfert96425c22015-08-30 21:13:53 +00005038int Scop::getRelativeLoopDepth(const Loop *L) const {
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00005039 if (!L || !R.contains(L))
Johannes Doerfert96425c22015-08-30 21:13:53 +00005040 return -1;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00005041 // outermostLoopInRegion always returns nullptr for top level regions
5042 if (R.isTopLevelRegion()) {
5043 // LoopInfo's depths start at 1, we start at 0
5044 return L->getLoopDepth() - 1;
5045 } else {
5046 Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
5047 assert(OuterLoop);
5048 return L->getLoopDepth() - OuterLoop->getLoopDepth();
5049 }
Johannes Doerfertd020b772015-08-27 06:53:52 +00005050}
5051
Roman Gareevd7754a12016-07-30 09:25:51 +00005052ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
5053 for (auto &SAI : arrays()) {
5054 if (SAI->getName() == BaseName)
5055 return SAI;
5056 }
5057 return nullptr;
5058}
5059
Michael Kruse8b805802017-07-19 17:11:25 +00005060void Scop::addAccessData(MemoryAccess *Access) {
5061 const ScopArrayInfo *SAI = Access->getOriginalScopArrayInfo();
5062 assert(SAI && "can only use after access relations have been constructed");
5063
5064 if (Access->isOriginalValueKind() && Access->isRead())
5065 ValueUseAccs[SAI].push_back(Access);
5066 else if (Access->isOriginalAnyPHIKind() && Access->isWrite())
5067 PHIIncomingAccs[SAI].push_back(Access);
5068}
5069
5070void Scop::removeAccessData(MemoryAccess *Access) {
5071 if (Access->isOriginalValueKind() && Access->isRead()) {
5072 auto &Uses = ValueUseAccs[Access->getScopArrayInfo()];
5073 std::remove(Uses.begin(), Uses.end(), Access);
5074 } else if (Access->isOriginalAnyPHIKind() && Access->isWrite()) {
5075 auto &Incomings = PHIIncomingAccs[Access->getScopArrayInfo()];
5076 std::remove(Incomings.begin(), Incomings.end(), Access);
5077 }
5078}
5079
5080MemoryAccess *Scop::getValueDef(const ScopArrayInfo *SAI) const {
5081 assert(SAI->isValueKind());
5082
5083 Instruction *Val = dyn_cast<Instruction>(SAI->getBasePtr());
5084 if (!Val)
5085 return nullptr;
5086
5087 ScopStmt *Stmt = getStmtFor(Val);
5088 if (!Stmt)
5089 return nullptr;
5090
5091 return Stmt->lookupValueWriteOf(Val);
5092}
5093
5094ArrayRef<MemoryAccess *> Scop::getValueUses(const ScopArrayInfo *SAI) const {
5095 assert(SAI->isValueKind());
5096 auto It = ValueUseAccs.find(SAI);
5097 if (It == ValueUseAccs.end())
5098 return {};
5099 return It->second;
5100}
5101
5102MemoryAccess *Scop::getPHIRead(const ScopArrayInfo *SAI) const {
5103 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
5104
5105 if (SAI->isExitPHIKind())
5106 return nullptr;
5107
5108 PHINode *PHI = cast<PHINode>(SAI->getBasePtr());
5109 ScopStmt *Stmt = getStmtFor(PHI);
5110 assert(Stmt && "PHINode must be within the SCoP");
5111
5112 return Stmt->lookupPHIReadOf(PHI);
5113}
5114
5115ArrayRef<MemoryAccess *> Scop::getPHIIncomings(const ScopArrayInfo *SAI) const {
5116 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
5117 auto It = PHIIncomingAccs.find(SAI);
5118 if (It == PHIIncomingAccs.end())
5119 return {};
5120 return It->second;
5121}
5122
Michael Krusecd4c9772017-07-21 15:35:53 +00005123raw_ostream &polly::operator<<(raw_ostream &O, const Scop &scop) {
5124 scop.print(O, PollyPrintInstructions);
5125 return O;
5126}
5127
Johannes Doerfert99191c72016-05-31 09:41:04 +00005128//===----------------------------------------------------------------------===//
5129void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
5130 AU.addRequired<LoopInfoWrapperPass>();
5131 AU.addRequired<RegionInfoPass>();
5132 AU.addRequired<DominatorTreeWrapperPass>();
5133 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005134 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005135 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005136 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005137 AU.setPreservesAll();
5138}
5139
Tobias Grossercd01a362017-02-17 08:12:36 +00005140void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
5141 NumLoopsInScop += Stats.NumLoops;
5142 MaxNumLoopsInScop =
5143 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
5144
Tobias Grossercd01a362017-02-17 08:12:36 +00005145 if (Stats.MaxDepth == 1)
5146 NumScopsDepthOne++;
5147 else if (Stats.MaxDepth == 2)
5148 NumScopsDepthTwo++;
5149 else if (Stats.MaxDepth == 3)
5150 NumScopsDepthThree++;
5151 else if (Stats.MaxDepth == 4)
5152 NumScopsDepthFour++;
5153 else if (Stats.MaxDepth == 5)
5154 NumScopsDepthFive++;
5155 else
5156 NumScopsDepthLarger++;
5157}
5158
Johannes Doerfert99191c72016-05-31 09:41:04 +00005159bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005160 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005161
5162 if (!SD.isMaxRegionInScop(*R))
5163 return false;
5164
5165 Function *F = R->getEntry()->getParent();
5166 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5167 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5168 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5169 auto const &DL = F->getParent()->getDataLayout();
5170 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005171 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005172
Michael Kruse89b1f942017-03-17 13:56:53 +00005173 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005174 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00005175
5176 if (S) {
5177 ScopDetection::LoopStats Stats =
5178 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
5179 updateLoopCountStatistic(Stats);
5180 }
5181
Tobias Grosser75805372011-04-29 06:27:02 +00005182 return false;
5183}
5184
Johannes Doerfert99191c72016-05-31 09:41:04 +00005185void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005186 if (S)
Michael Krusecd4c9772017-07-21 15:35:53 +00005187 S->print(OS, PollyPrintInstructions);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005188 else
5189 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00005190}
Tobias Grosser75805372011-04-29 06:27:02 +00005191
Johannes Doerfert99191c72016-05-31 09:41:04 +00005192char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005193
Johannes Doerfert99191c72016-05-31 09:41:04 +00005194Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
5195
5196INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005197 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005198 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00005199INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005200INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00005201INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00005202INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00005203INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005204INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00005205INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005206INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005207 "Polly - Create polyhedral description of Scops", false,
5208 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005209
5210//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00005211ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
5212 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
5213 AssumptionCache &AC) {
Michael Krusea6d48f52017-06-08 12:06:15 +00005214 /// Create polyhedral description of scops for all the valid regions of a
Philip Pfaffe838e0882017-05-15 12:55:14 +00005215 /// function.
5216 for (auto &It : SD) {
5217 Region *R = const_cast<Region *>(It);
5218 if (!SD.isMaxRegionInScop(*R))
5219 continue;
5220
5221 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
5222 std::unique_ptr<Scop> S = SB.getScop();
5223 if (!S)
5224 continue;
5225 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
5226 assert(Inserted && "Building Scop for the same region twice!");
5227 (void)Inserted;
5228 }
5229}
5230
5231AnalysisKey ScopInfoAnalysis::Key;
5232
5233ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
5234 FunctionAnalysisManager &FAM) {
5235 auto &SD = FAM.getResult<ScopAnalysis>(F);
5236 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
5237 auto &LI = FAM.getResult<LoopAnalysis>(F);
5238 auto &AA = FAM.getResult<AAManager>(F);
5239 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
5240 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
5241 auto &DL = F.getParent()->getDataLayout();
5242 return {DL, SD, SE, LI, AA, DT, AC};
5243}
5244
5245PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
5246 FunctionAnalysisManager &FAM) {
5247 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
5248 for (auto &It : SI) {
5249 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005250 It.second->print(Stream, PollyPrintInstructions);
Philip Pfaffe838e0882017-05-15 12:55:14 +00005251 else
5252 Stream << "Invalid Scop!\n";
5253 }
5254 return PreservedAnalyses::all();
5255}
5256
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005257void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
5258 AU.addRequired<LoopInfoWrapperPass>();
5259 AU.addRequired<RegionInfoPass>();
5260 AU.addRequired<DominatorTreeWrapperPass>();
5261 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005262 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005263 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005264 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005265 AU.setPreservesAll();
5266}
5267
5268bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005269 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005270 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5271 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5272 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5273 auto const &DL = F.getParent()->getDataLayout();
5274 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005275 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005276
Philip Pfaffe838e0882017-05-15 12:55:14 +00005277 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005278 return false;
5279}
5280
5281void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005282 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005283 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005284 It.second->print(OS, PollyPrintInstructions);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005285 else
5286 OS << "Invalid Scop!\n";
5287 }
5288}
5289
5290char ScopInfoWrapperPass::ID = 0;
5291
5292Pass *polly::createScopInfoWrapperPassPass() {
5293 return new ScopInfoWrapperPass();
5294}
5295
5296INITIALIZE_PASS_BEGIN(
5297 ScopInfoWrapperPass, "polly-function-scops",
5298 "Polly - Create polyhedral description of all Scops of a function", false,
5299 false);
5300INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005301INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005302INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5303INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5304INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005305INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005306INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5307INITIALIZE_PASS_END(
5308 ScopInfoWrapperPass, "polly-function-scops",
5309 "Polly - Create polyhedral description of all Scops of a function", false,
5310 false)