blob: 5faeb6f081760a8fab82bfe51292eddfe90e18ad [file] [log] [blame]
Michael Kruse2133cb92016-06-28 01:37:20 +00001//===--------- ScopInfo.cpp ----------------------------------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser5624d3c2015-12-21 12:38:56 +000020#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000021#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000022#include "polly/Options.h"
Michael Kruse73fa33b2016-06-28 01:37:28 +000023#include "polly/ScopBuilder.h"
Tobias Grosser75805372011-04-29 06:27:02 +000024#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000025#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000026#include "polly/Support/ScopHelper.h"
Tobias Grosser9737c7b2015-11-22 11:06:51 +000027#include "llvm/ADT/DepthFirstIterator.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000028#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000029#include "llvm/ADT/PostOrderIterator.h"
30#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000031#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000032#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000033#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000034#include "llvm/Analysis/AliasAnalysis.h"
Michael Kruse89b1f942017-03-17 13:56:53 +000035#include "llvm/Analysis/AssumptionCache.h"
Johannes Doerfert1dc12af2016-04-23 12:59:18 +000036#include "llvm/Analysis/Loads.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000037#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000038#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000039#include "llvm/Analysis/RegionIterator.h"
40#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000041#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000042#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000043#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000045#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000047#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000048#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000049#include "isl/schedule.h"
50#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000051#include "isl/set.h"
52#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000053#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000054#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000055#include <sstream>
56#include <string>
57#include <vector>
58
59using namespace llvm;
60using namespace polly;
61
Chandler Carruth95fef942014-04-22 03:30:19 +000062#define DEBUG_TYPE "polly-scops"
63
Johannes Doerfert81aa6e82016-11-18 14:37:08 +000064STATISTIC(AssumptionsAliasing, "Number of aliasing assumptions taken.");
65STATISTIC(AssumptionsInbounds, "Number of inbounds assumptions taken.");
66STATISTIC(AssumptionsWrapping, "Number of wrapping assumptions taken.");
67STATISTIC(AssumptionsUnsigned, "Number of unsigned assumptions taken.");
68STATISTIC(AssumptionsComplexity, "Number of too complex SCoPs.");
69STATISTIC(AssumptionsUnprofitable, "Number of unprofitable SCoPs.");
70STATISTIC(AssumptionsErrorBlock, "Number of error block assumptions taken.");
71STATISTIC(AssumptionsInfiniteLoop, "Number of bounded loop assumptions taken.");
72STATISTIC(AssumptionsInvariantLoad,
Johannes Doerfertcd195322016-11-17 21:41:08 +000073 "Number of invariant loads assumptions taken.");
Johannes Doerfert81aa6e82016-11-18 14:37:08 +000074STATISTIC(AssumptionsDelinearization,
Johannes Doerfertcd195322016-11-17 21:41:08 +000075 "Number of delinearization assumptions taken.");
76
Tobias Grossercd01a362017-02-17 08:12:36 +000077STATISTIC(NumLoopsInScop, "Number of loops in scops");
78STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
79STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
80STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
81STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
82STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
83STATISTIC(NumScopsDepthLarger,
84 "Number of scops with maximal loop depth 6 and larger");
85STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
86
Tobias Grosser75dc40c2015-12-20 13:31:48 +000087// The maximal number of basic sets we allow during domain construction to
88// be created. More complex scops will result in very high compile time and
89// are also unlikely to result in good code
Tobias Grosser90411a92017-02-16 19:11:33 +000090static int const MaxDisjunctsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +000091
Tobias Grosserc8a82762017-02-16 19:11:25 +000092// The number of disjunct in the context after which we stop to add more
93// disjuncts. This parameter is there to avoid exponential growth in the
94// number of disjunct when adding non-convex sets to the context.
95static int const MaxDisjunctsInContext = 4;
96
Tobias Grosser97715842017-05-19 04:01:52 +000097static cl::opt<int>
98 OptComputeOut("polly-analysis-computeout",
99 cl::desc("Bound the scop analysis by a maximal amount of "
100 "computational steps (0 means no bound)"),
Tobias Grosserc8d13f52017-05-24 21:24:04 +0000101 cl::Hidden, cl::init(600000), cl::ZeroOrMore,
Tobias Grosser97715842017-05-19 04:01:52 +0000102 cl::cat(PollyCategory));
Tobias Grosser45e9fd12017-05-19 03:45:00 +0000103
Johannes Doerfert2f705842016-04-12 16:09:44 +0000104static cl::opt<bool> PollyRemarksMinimal(
105 "polly-remarks-minimal",
106 cl::desc("Do not emit remarks about assumptions that are known"),
107 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
108
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +0000109// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000110// operations can overflow easily. Additive reductions and bit operations
111// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +0000112static cl::opt<bool> DisableMultiplicativeReductions(
113 "polly-disable-multiplicative-reductions",
114 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
115 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000116
Johannes Doerfert9143d672014-09-27 11:02:39 +0000117static cl::opt<unsigned> RunTimeChecksMaxParameters(
118 "polly-rtc-max-parameters",
119 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
120 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
121
Tobias Grosser71500722015-03-28 15:11:14 +0000122static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
123 "polly-rtc-max-arrays-per-group",
124 cl::desc("The maximal number of arrays to compare in each alias group."),
125 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000126
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000127static cl::opt<std::string> UserContextStr(
128 "polly-context", cl::value_desc("isl parameter set"),
129 cl::desc("Provide additional constraints on the context parameters"),
130 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000131
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000132static cl::opt<bool> DetectReductions("polly-detect-reductions",
133 cl::desc("Detect and exploit reductions"),
134 cl::Hidden, cl::ZeroOrMore,
135 cl::init(true), cl::cat(PollyCategory));
136
Tobias Grosser2937b592016-04-29 11:43:20 +0000137static cl::opt<bool>
138 IslOnErrorAbort("polly-on-isl-error-abort",
139 cl::desc("Abort if an isl error is encountered"),
140 cl::init(true), cl::cat(PollyCategory));
141
Tobias Grosserd7c49752017-02-28 09:45:54 +0000142static cl::opt<bool> PollyPreciseInbounds(
143 "polly-precise-inbounds",
144 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
145 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
146
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000147static cl::opt<bool>
148 PollyIgnoreInbounds("polly-ignore-inbounds",
149 cl::desc("Do not take inbounds assumptions at all"),
150 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
151
Tobias Grosser5842dee2017-03-17 13:00:53 +0000152static cl::opt<bool> PollyIgnoreParamBounds(
153 "polly-ignore-parameter-bounds",
154 cl::desc(
155 "Do not add parameter bounds and do no gist simplify sets accordingly"),
156 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
157
Tobias Grosserc2f15102017-03-01 21:11:27 +0000158static cl::opt<bool> PollyPreciseFoldAccesses(
159 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000160 cl::desc("Fold memory accesses to model more possible delinearizations "
161 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000162 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000163
Michael Kruse5ae08c02017-05-06 14:03:58 +0000164bool polly::UseInstructionNames;
165static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000166 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000167 cl::desc("Use LLVM-IR names when deriving statement names"),
168 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
169 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000170
Tobias Grosserd5fcbef2017-05-27 04:40:18 +0000171static cl::opt<bool> PollyPrintInstructions(
172 "polly-print-instructions", cl::desc("Output instructions per ScopStmt"),
173 cl::Hidden, cl::Optional, cl::init(false), cl::cat(PollyCategory));
174
Michael Kruse7bf39442015-09-10 12:46:52 +0000175//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000176
Michael Kruse046dde42015-08-10 13:01:57 +0000177// Create a sequence of two schedules. Either argument may be null and is
178// interpreted as the empty schedule. Can also return null if both schedules are
179// empty.
180static __isl_give isl_schedule *
181combineInSequence(__isl_take isl_schedule *Prev,
182 __isl_take isl_schedule *Succ) {
183 if (!Prev)
184 return Succ;
185 if (!Succ)
186 return Prev;
187
188 return isl_schedule_sequence(Prev, Succ);
189}
190
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000191static isl::set addRangeBoundsToSet(isl::set S, const ConstantRange &Range,
192 int dim, isl::dim type) {
193 isl::val V;
194 isl::ctx Ctx = S.get_ctx();
Johannes Doerferte7044942015-02-24 11:58:30 +0000195
Tobias Grosser3281f602017-02-16 18:39:14 +0000196 // The upper and lower bound for a parameter value is derived either from
197 // the data type of the parameter or from the - possibly more restrictive -
198 // range metadata.
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000199 V = valFromAPInt(Ctx.get(), Range.getSignedMin(), true);
200 S = S.lower_bound_val(type, dim, V);
201 V = valFromAPInt(Ctx.get(), Range.getSignedMax(), true);
202 S = S.upper_bound_val(type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000203
Tobias Grosser3281f602017-02-16 18:39:14 +0000204 if (Range.isFullSet())
205 return S;
206
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000207 if (isl_set_n_basic_set(S.get()) > MaxDisjunctsInContext)
Tobias Grosserc8a82762017-02-16 19:11:25 +0000208 return S;
209
Tobias Grosser3281f602017-02-16 18:39:14 +0000210 // In case of signed wrapping, we can refine the set of valid values by
211 // excluding the part not covered by the wrapping range.
212 if (Range.isSignWrappedSet()) {
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000213 V = valFromAPInt(Ctx.get(), Range.getLower(), true);
214 isl::set SLB = S.lower_bound_val(type, dim, V);
Tobias Grosser3281f602017-02-16 18:39:14 +0000215
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000216 V = valFromAPInt(Ctx.get(), Range.getUpper(), true);
217 V = V.sub_ui(1);
218 isl::set SUB = S.upper_bound_val(type, dim, V);
219 S = SLB.unite(SUB);
Tobias Grosser3281f602017-02-16 18:39:14 +0000220 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000221
Tobias Grosser3281f602017-02-16 18:39:14 +0000222 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000223}
224
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000225static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
226 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
227 if (!BasePtrLI)
228 return nullptr;
229
Johannes Doerfert952b5302016-05-23 12:40:48 +0000230 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000231 return nullptr;
232
233 ScalarEvolution &SE = *S->getSE();
234
235 auto *OriginBaseSCEV =
236 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
237 if (!OriginBaseSCEV)
238 return nullptr;
239
240 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
241 if (!OriginBaseSCEVUnknown)
242 return nullptr;
243
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000244 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000245 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000246}
247
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000248ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000249 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000250 const DataLayout &DL, Scop *S,
251 const char *BaseName)
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000252 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S),
253 FAD(nullptr) {
Tobias Grosser92245222015-07-28 14:53:44 +0000254 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000255 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000256 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
257 Kind == MemoryKind::PHI ? "__phi" : "",
258 UseInstructionNames);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000259 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000260
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000261 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000262
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000263 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000264 BasePtrOriginSAI = nullptr;
265 return;
266 }
267
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000268 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
269 if (BasePtrOriginSAI)
270 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000271}
272
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000273__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000274 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000275 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
276 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
277 return Space;
278}
279
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000280bool ScopArrayInfo::isReadOnly() {
Tobias Grosser2ade9862017-05-23 06:41:04 +0000281 isl::union_set WriteSet = give(S.getWrites()).range();
282 isl::space Space = give(getSpace());
283 WriteSet = WriteSet.extract_set(Space);
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000284
Tobias Grosser2ade9862017-05-23 06:41:04 +0000285 return bool(WriteSet.is_empty());
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000286}
287
Tobias Grosserf3adab42017-05-10 10:59:58 +0000288bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
289 if (Array->getElementType() != getElementType())
290 return false;
291
292 if (Array->getNumberOfDimensions() != getNumberOfDimensions())
293 return false;
294
295 for (unsigned i = 0; i < getNumberOfDimensions(); i++)
296 if (Array->getDimensionSize(i) != getDimensionSize(i))
297 return false;
298
299 return true;
300}
301
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000302void ScopArrayInfo::updateElementType(Type *NewElementType) {
303 if (NewElementType == ElementType)
304 return;
305
Tobias Grosserd840fc72016-02-04 13:18:42 +0000306 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
307 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
308
Johannes Doerferta7920982016-02-25 14:08:48 +0000309 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000310 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000311
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000312 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
313 ElementType = NewElementType;
314 } else {
315 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
316 ElementType = IntegerType::get(ElementType->getContext(), GCD);
317 }
318}
319
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000320/// Make the ScopArrayInfo model a Fortran Array
321void ScopArrayInfo::applyAndSetFAD(Value *FAD) {
322 assert(FAD && "got invalid Fortran array descriptor");
323 if (this->FAD) {
324 assert(this->FAD == FAD &&
325 "receiving different array descriptors for same array");
326 return;
327 }
328
329 assert(DimensionSizesPw.size() > 0 && !DimensionSizesPw[0]);
330 assert(!this->FAD);
331 this->FAD = FAD;
332
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000333 isl::space Space(S.getIslCtx(), 1, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000334
335 std::string param_name = getName();
336 param_name += "_fortranarr_size";
337 // TODO: see if we need to add `this` as the id user pointer
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000338 isl::id IdPwAff = isl::id::alloc(S.getIslCtx(), param_name.c_str(), nullptr);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000339
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000340 Space = Space.set_dim_id(isl::dim::param, 0, IdPwAff);
341 isl::pw_aff PwAff =
342 isl::aff::var_on_domain(isl::local_space(Space), isl::dim::param, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000343
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000344 DimensionSizesPw[0] = PwAff.release();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000345}
346
Tobias Grosserbedef002016-12-02 08:10:56 +0000347bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
348 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000349 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
350 int ExtraDimsNew = NewSizes.size() - SharedDims;
351 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000352
Tobias Grosserbedef002016-12-02 08:10:56 +0000353 if (CheckConsistency) {
354 for (int i = 0; i < SharedDims; i++) {
355 auto *NewSize = NewSizes[i + ExtraDimsNew];
356 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
357 if (NewSize && KnownSize && NewSize != KnownSize)
358 return false;
359 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000360
Tobias Grosserbedef002016-12-02 08:10:56 +0000361 if (DimensionSizes.size() >= NewSizes.size())
362 return true;
363 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000364
365 DimensionSizes.clear();
366 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
367 NewSizes.end());
368 for (isl_pw_aff *Size : DimensionSizesPw)
369 isl_pw_aff_free(Size);
370 DimensionSizesPw.clear();
371 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000372 if (!Expr) {
373 DimensionSizesPw.push_back(nullptr);
374 continue;
375 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000376 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000377 DimensionSizesPw.push_back(Size);
378 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000379 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000380}
381
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000382ScopArrayInfo::~ScopArrayInfo() {
383 isl_id_free(Id);
384 for (isl_pw_aff *Size : DimensionSizesPw)
385 isl_pw_aff_free(Size);
386}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000387
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000388std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
389
390int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000391 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000392}
393
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000394__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
395 return isl_id_copy(Id);
396}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000397
398void ScopArrayInfo::dump() const { print(errs()); }
399
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000400void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000401 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000402 unsigned u = 0;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000403 // If this is a Fortran array, then we can print the outermost dimension
404 // as a isl_pw_aff even though there is no SCEV information.
405 bool IsOutermostSizeKnown = SizeAsPwAff && FAD;
406
407 if (!IsOutermostSizeKnown && getNumberOfDimensions() > 0 &&
408 !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000409 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000410 u++;
411 }
412 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000413 OS << "[";
414
Tobias Grosser26253842015-11-10 14:24:21 +0000415 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000416 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000417 OS << " " << Size << " ";
418 isl_pw_aff_free(Size);
419 } else {
420 OS << *getDimensionSize(u);
421 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000422
423 OS << "]";
424 }
425
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000426 OS << ";";
427
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000428 if (BasePtrOriginSAI)
429 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
430
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000431 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000432}
433
434const ScopArrayInfo *
435ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
436 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
437 assert(Id && "Output dimension didn't have an ID");
438 return getFromId(Id);
439}
440
Michael Krused56b90a2016-09-01 09:03:27 +0000441const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000442 void *User = isl_id_get_user(Id);
443 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
444 isl_id_free(Id);
445 return SAI;
446}
447
Michael Kruse3b425ff2016-04-11 14:34:08 +0000448void MemoryAccess::wrapConstantDimensions() {
449 auto *SAI = getScopArrayInfo();
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000450 isl::space ArraySpace = give(SAI->getSpace());
451 isl::ctx Ctx = ArraySpace.get_ctx();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000452 unsigned DimsArray = SAI->getNumberOfDimensions();
453
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000454 isl::multi_aff DivModAff = isl::multi_aff::identity(
455 ArraySpace.map_from_domain_and_range(ArraySpace));
456 isl::local_space LArraySpace = isl::local_space(ArraySpace);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000457
458 // Begin with last dimension, to iteratively carry into higher dimensions.
459 for (int i = DimsArray - 1; i > 0; i--) {
460 auto *DimSize = SAI->getDimensionSize(i);
461 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
462
463 // This transformation is not applicable to dimensions with dynamic size.
464 if (!DimSizeCst)
465 continue;
466
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000467 // This transformation is not applicable to dimensions of size zero.
468 if (DimSize->isZero())
469 continue;
470
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000471 isl::val DimSizeVal =
472 valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
473 isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
474 isl::aff PrevVar =
475 isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000476
477 // Compute: index % size
478 // Modulo must apply in the divide of the previous iteration, if any.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000479 isl::aff Modulo = Var.mod_val(DimSizeVal);
480 Modulo = Modulo.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000481
482 // Compute: floor(index / size)
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000483 isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
484 Divide = Divide.floor();
485 Divide = Divide.add(PrevVar);
486 Divide = Divide.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000487
488 // Apply Modulo and Divide.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000489 DivModAff = DivModAff.set_aff(i, Modulo);
490 DivModAff = DivModAff.set_aff(i - 1, Divide);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000491 }
492
493 // Apply all modulo/divides on the accesses.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000494 isl::map Relation = give(AccessRelation);
495 Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
496 Relation = Relation.detect_equalities();
497 AccessRelation = Relation.release();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000498}
499
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000500void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000501 auto *SAI = getScopArrayInfo();
Tobias Grosser7be82452017-05-21 20:38:33 +0000502 isl::space ArraySpace = give(SAI->getSpace());
503 isl::space AccessSpace = give(isl_map_get_space(AccessRelation)).range();
504 isl::ctx Ctx = ArraySpace.get_ctx();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000505
Tobias Grosser7be82452017-05-21 20:38:33 +0000506 auto DimsArray = ArraySpace.dim(isl::dim::set);
507 auto DimsAccess = AccessSpace.dim(isl::dim::set);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000508 auto DimsMissing = DimsArray - DimsAccess;
509
Michael Kruse375cb5f2016-02-24 22:08:24 +0000510 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000511 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000512 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000513 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000514
Tobias Grosser7be82452017-05-21 20:38:33 +0000515 isl::map Map = isl::map::from_domain_and_range(
516 isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000517
518 for (unsigned i = 0; i < DimsMissing; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000519 Map = Map.fix_si(isl::dim::out, i, 0);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000520
521 for (unsigned i = DimsMissing; i < DimsArray; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000522 Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000523
Tobias Grosser7be82452017-05-21 20:38:33 +0000524 AccessRelation = isl_map_apply_range(AccessRelation, Map.release());
Roman Gareev10595a12016-01-08 14:01:59 +0000525
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000526 // For the non delinearized arrays, divide the access function of the last
527 // subscript by the size of the elements in the array.
528 //
529 // A stride one array access in C expressed as A[i] is expressed in
530 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
531 // two subsequent values of 'i' index two values that are stored next to
532 // each other in memory. By this division we make this characteristic
533 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000534 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000535 // that divides the offsets of all accesses to this base pointer.
536 if (DimsAccess == 1) {
Tobias Grosser7be82452017-05-21 20:38:33 +0000537 isl::val V = isl::val(Ctx, ArrayElemSize);
538 AccessRelation = isl_map_floordiv_val(AccessRelation, V.release());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000539 }
540
Michael Kruse3b425ff2016-04-11 14:34:08 +0000541 // We currently do this only if we added at least one dimension, which means
542 // some dimension's indices have not been specified, an indicator that some
543 // index values have been added together.
544 // TODO: Investigate general usefulness; Effect on unit tests is to make index
545 // expressions more complicated.
546 if (DimsMissing)
547 wrapConstantDimensions();
548
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000549 if (!isAffine())
550 computeBoundsOnAccessRelation(ArrayElemSize);
551
Tobias Grosserd840fc72016-02-04 13:18:42 +0000552 // Introduce multi-element accesses in case the type loaded by this memory
553 // access is larger than the canonical element type of the array.
554 //
555 // An access ((float *)A)[i] to an array char *A is modeled as
556 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000557 if (ElemBytes > ArrayElemSize) {
558 assert(ElemBytes % ArrayElemSize == 0 &&
559 "Loaded element size should be multiple of canonical element size");
Tobias Grosser7be82452017-05-21 20:38:33 +0000560 isl::map Map = isl::map::from_domain_and_range(
561 isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000562 for (unsigned i = 0; i < DimsArray - 1; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000563 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000564
Tobias Grosser7be82452017-05-21 20:38:33 +0000565 isl::constraint C;
566 isl::local_space LS;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000567
Tobias Grosser7be82452017-05-21 20:38:33 +0000568 LS = isl::local_space(Map.get_space());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000569 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
570
Tobias Grosser7be82452017-05-21 20:38:33 +0000571 C = isl::constraint::alloc_inequality(LS);
572 C = C.set_constant_val(isl::val(Ctx, Num - 1));
573 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
574 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
575 Map = Map.add_constraint(C);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000576
Tobias Grosser7be82452017-05-21 20:38:33 +0000577 C = isl::constraint::alloc_inequality(LS);
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 C = C.set_constant_val(isl::val(Ctx, 0));
581 Map = Map.add_constraint(C);
582 AccessRelation = isl_map_apply_range(AccessRelation, Map.release());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000583 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000584}
585
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000586const std::string
587MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
588 switch (RT) {
589 case MemoryAccess::RT_NONE:
590 llvm_unreachable("Requested a reduction operator string for a memory "
591 "access which isn't a reduction");
592 case MemoryAccess::RT_ADD:
593 return "+";
594 case MemoryAccess::RT_MUL:
595 return "*";
596 case MemoryAccess::RT_BOR:
597 return "|";
598 case MemoryAccess::RT_BXOR:
599 return "^";
600 case MemoryAccess::RT_BAND:
601 return "&";
602 }
603 llvm_unreachable("Unknown reduction type");
604 return "";
605}
606
Tobias Grosserc80d6972016-09-02 06:33:33 +0000607/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000608static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
609 const Instruction *Load) {
610 if (!BinOp)
611 return MemoryAccess::RT_NONE;
612 switch (BinOp->getOpcode()) {
613 case Instruction::FAdd:
614 if (!BinOp->hasUnsafeAlgebra())
615 return MemoryAccess::RT_NONE;
616 // Fall through
617 case Instruction::Add:
618 return MemoryAccess::RT_ADD;
619 case Instruction::Or:
620 return MemoryAccess::RT_BOR;
621 case Instruction::Xor:
622 return MemoryAccess::RT_BXOR;
623 case Instruction::And:
624 return MemoryAccess::RT_BAND;
625 case Instruction::FMul:
626 if (!BinOp->hasUnsafeAlgebra())
627 return MemoryAccess::RT_NONE;
628 // Fall through
629 case Instruction::Mul:
630 if (DisableMultiplicativeReductions)
631 return MemoryAccess::RT_NONE;
632 return MemoryAccess::RT_MUL;
633 default:
634 return MemoryAccess::RT_NONE;
635 }
636}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000637
Tobias Grosser75805372011-04-29 06:27:02 +0000638MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000639 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000640 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000641 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000642 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000643}
644
Michael Kruse2fa35192016-09-01 19:53:31 +0000645const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000646 isl_id *ArrayId = getArrayId();
647 void *User = isl_id_get_user(ArrayId);
648 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
649 isl_id_free(ArrayId);
650 return SAI;
651}
652
Michael Kruse2fa35192016-09-01 19:53:31 +0000653const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
654 isl_id *ArrayId = getLatestArrayId();
655 void *User = isl_id_get_user(ArrayId);
656 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
657 isl_id_free(ArrayId);
658 return SAI;
659}
660
661__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000662 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
663}
664
Michael Kruse2fa35192016-09-01 19:53:31 +0000665__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
666 if (!hasNewAccessRelation())
667 return getOriginalArrayId();
668 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
669}
670
Tobias Grosserd840fc72016-02-04 13:18:42 +0000671__isl_give isl_map *MemoryAccess::getAddressFunction() const {
672 return isl_map_lexmin(getAccessRelation());
673}
674
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000675__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
676 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000677 isl_map *Schedule, *ScheduledAccRel;
678 isl_union_set *UDomain;
679
680 UDomain = isl_union_set_from_set(getStatement()->getDomain());
681 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
682 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000683 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000684 return isl_pw_multi_aff_from_map(ScheduledAccRel);
685}
686
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000687__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000688 return isl_map_copy(AccessRelation);
689}
690
Johannes Doerferta99130f2014-10-13 12:58:03 +0000691std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000692 return stringFromIslObj(AccessRelation);
693}
694
Johannes Doerferta99130f2014-10-13 12:58:03 +0000695__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000696 return isl_map_get_space(AccessRelation);
697}
698
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000699__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000700 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000701}
702
Tobias Grosser6f730082015-09-05 07:46:47 +0000703std::string MemoryAccess::getNewAccessRelationStr() const {
704 return stringFromIslObj(NewAccessRelation);
705}
706
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000707__isl_give isl_basic_map *
708MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000709 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000710 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000711
Tobias Grosser084d8f72012-05-29 09:29:44 +0000712 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000713 isl_basic_set_universe(Statement->getDomainSpace()),
714 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000715}
716
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000717// Formalize no out-of-bound access assumption
718//
719// When delinearizing array accesses we optimistically assume that the
720// delinearized accesses do not access out of bound locations (the subscript
721// expression of each array evaluates for each statement instance that is
722// executed to a value that is larger than zero and strictly smaller than the
723// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000724// dimension for which we do not need to assume any upper bound. At this point
725// we formalize this assumption to ensure that at code generation time the
726// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000727//
728// To find the set of constraints necessary to avoid out of bound accesses, we
729// first build the set of data locations that are not within array bounds. We
730// then apply the reverse access relation to obtain the set of iterations that
731// may contain invalid accesses and reduce this set of iterations to the ones
732// that are actually executed by intersecting them with the domain of the
733// statement. If we now project out all loop dimensions, we obtain a set of
734// parameters that may cause statement instances to be executed that may
735// possibly yield out of bound memory accesses. The complement of these
736// constraints is the set of constraints that needs to be assumed to ensure such
737// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000738void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000739 if (PollyIgnoreInbounds)
740 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000741 auto *SAI = getScopArrayInfo();
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000742 isl::space Space = give(getOriginalAccessRelationSpace()).range();
743 isl::set Outside = isl::set::empty(Space);
744 for (int i = 1, Size = Space.dim(isl::dim::set); i < Size; ++i) {
745 isl::local_space LS(Space);
746 isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
747 isl::pw_aff Zero = isl::pw_aff(LS);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000748
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000749 isl::set DimOutside = Var.lt_set(Zero);
750 isl::pw_aff SizeE = give(SAI->getDimensionSizePw(i));
751 SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set));
752 SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
753 DimOutside = DimOutside.unite(SizeE.le_set(Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000754
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000755 Outside = Outside.unite(DimOutside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000756 }
757
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000758 Outside = Outside.apply(give(getAccessRelation()).reverse());
759 Outside = Outside.intersect(give(Statement->getDomain()));
760 Outside = Outside.params();
Tobias Grosserf54bb772015-06-26 12:09:28 +0000761
762 // Remove divs to avoid the construction of overly complicated assumptions.
763 // Doing so increases the set of parameter combinations that are assumed to
764 // not appear. This is always save, but may make the resulting run-time check
765 // bail out more often than strictly necessary.
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000766 Outside = Outside.remove_divs();
767 Outside = Outside.complement();
Michael Kruse7071e8b2016-04-11 13:24:29 +0000768 const auto &Loc = getAccessInstruction()
769 ? getAccessInstruction()->getDebugLoc()
770 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000771 if (!PollyPreciseInbounds)
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000772 Outside = Outside.gist_params(give(Statement->getDomain()).params());
773 Statement->getParent()->recordAssumption(INBOUNDS, Outside.release(), Loc,
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000774 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000775}
776
Johannes Doerfertcea61932016-02-21 19:13:19 +0000777void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000778 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000779 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000780
Tobias Grosser53fc3552017-05-23 07:07:09 +0000781 isl::pw_aff SubscriptPWA = give(getPwAff(Subscripts[0]));
782 isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000783
Tobias Grosser53fc3552017-05-23 07:07:09 +0000784 isl::map LengthMap;
Johannes Doerferta7920982016-02-25 14:08:48 +0000785 if (Subscripts[1] == nullptr) {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000786 LengthMap = isl::map::universe(SubscriptMap.get_space());
Johannes Doerferta7920982016-02-25 14:08:48 +0000787 } else {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000788 isl::pw_aff LengthPWA = give(getPwAff(Subscripts[1]));
789 LengthMap = isl::map::from_pw_aff(LengthPWA);
790 isl::space RangeSpace = LengthMap.get_space().range();
791 LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
Johannes Doerferta7920982016-02-25 14:08:48 +0000792 }
Tobias Grosser53fc3552017-05-23 07:07:09 +0000793 LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
794 LengthMap = LengthMap.align_params(SubscriptMap.get_space());
795 SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
796 LengthMap = LengthMap.sum(SubscriptMap);
797 AccessRelation =
798 LengthMap.set_tuple_id(isl::dim::in, give(getStatement()->getDomainId()))
799 .release();
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 Grosser99ea1d02017-05-21 20:23:20 +0000840 isl::map Relation = give(AccessRelation);
841 isl::set AccessRange = Relation.range();
842 AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
843 isl::dim::set);
844 AccessRelation = Relation.intersect_range(AccessRange).release();
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 Grossera32de132017-05-23 07:22:56 +0000853 isl::map NewAccessRelation = give(isl_map_copy(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 Grossera32de132017-05-23 07:22:56 +0000864 Space = give(isl_map_copy(AccessRelation)).get_space();
865 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 Grossera32de132017-05-23 07:22:56 +0000898 isl::id BaseAddrId = give(getScopArrayInfo()->getBasePtrId());
899 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()) >
911 isl_map_n_basic_map(AccessRelation)) {
Tobias Grosserc2f15102017-03-01 21:11:27 +0000912 } else {
Tobias Grossera32de132017-05-23 07:22:56 +0000913 isl_map_free(AccessRelation);
914 AccessRelation = NewAccessRelation.release();
Tobias Grosserc2f15102017-03-01 21:11:27 +0000915 }
Tobias Grosser619190d2015-03-30 17:22:28 +0000916}
917
Tobias Grosserc80d6972016-09-02 06:33:33 +0000918/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000919static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000920 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000921 if (Size == 1)
922 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000923
924 // Only one factor needs to be divisible.
925 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
926 for (auto *FactorExpr : MulExpr->operands())
927 if (isDivisible(FactorExpr, Size, SE))
928 return true;
929 return false;
930 }
931
932 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
933 // to be divisble.
934 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
935 for (auto *OpExpr : NAryExpr->operands())
936 if (!isDivisible(OpExpr, Size, SE))
937 return false;
938 return true;
939 }
940
941 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
942 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
943 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
944 return MulSCEV == Expr;
945}
946
Michael Krusee2bccbb2015-09-18 19:59:43 +0000947void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
948 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000949
Johannes Doerfert85676e32016-04-23 14:32:34 +0000950 // Initialize the invalid domain which describes all iterations for which the
951 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000952 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
953 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
954 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000955
Michael Krusee2bccbb2015-09-18 19:59:43 +0000956 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000957 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000958
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000959 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
960 buildMemIntrinsicAccessRelation();
961 AccessRelation =
962 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
963 return;
964 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000965
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000966 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000967 // We overapproximate non-affine accesses with a possible access to the
968 // whole array. For read accesses it does not make a difference, if an
969 // access must or may happen. However, for write accesses it is important to
970 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000971 if (!AccessRelation)
972 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
973
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000974 AccessRelation =
975 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000976 return;
977 }
978
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000979 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000980 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000981
Michael Krusee2bccbb2015-09-18 19:59:43 +0000982 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000983 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000984 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000985 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000986 }
987
Tobias Grosser79baa212014-04-10 08:38:02 +0000988 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000989 AccessRelation = isl_map_set_tuple_id(
990 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000991 AccessRelation =
992 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
993
Tobias Grosseraa660a92015-03-30 00:07:50 +0000994 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000995 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000996}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000997
Michael Krusecac948e2015-10-02 13:53:07 +0000998MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000999 AccessType AccType, Value *BaseAddress,
1000 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +00001001 ArrayRef<const SCEV *> Subscripts,
1002 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +00001003 MemoryKind Kind)
Johannes Doerfertcea61932016-02-21 19:13:19 +00001004 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Tobias Grosser81331282017-05-03 07:57:35 +00001005 InvalidDomain(nullptr), BaseAddr(BaseAddress), ElementType(ElementType),
1006 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
1007 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +00001008 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001009 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +00001010 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001011 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001012
Tobias Grosser81331282017-05-03 07:57:35 +00001013 std::string IdName = Stmt->getBaseName() + Access;
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001014 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1015}
Michael Krusee2bccbb2015-09-18 19:59:43 +00001016
Roman Gareevb3224ad2016-09-14 06:26:09 +00001017MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
1018 __isl_take isl_map *AccRel)
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001019 : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
1020 Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001021 IsAffine(true), AccessRelation(nullptr), NewAccessRelation(AccRel),
1022 FAD(nullptr) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001023 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
1024 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1025 Sizes.push_back(nullptr);
1026 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1027 Sizes.push_back(SAI->getDimensionSize(i));
1028 ElementType = SAI->getElementType();
1029 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001030 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001031 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001032
Tobias Grosser81331282017-05-03 07:57:35 +00001033 std::string IdName = Stmt->getBaseName() + Access;
Roman Gareevb3224ad2016-09-14 06:26:09 +00001034 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1035}
1036
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001037void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +00001038 auto *Ctx = Statement->getParent()->getContext();
1039 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1040 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001041}
1042
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001043const std::string MemoryAccess::getReductionOperatorStr() const {
1044 return MemoryAccess::getReductionOperatorStr(getReductionType());
1045}
1046
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001047__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
1048
Johannes Doerfertf6183392014-07-01 20:52:51 +00001049raw_ostream &polly::operator<<(raw_ostream &OS,
1050 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001051 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001052 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001053 else
1054 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001055 return OS;
1056}
1057
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001058void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001059
Tobias Grosser75805372011-04-29 06:27:02 +00001060void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001061 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001062 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001063 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001064 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001065 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001066 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001067 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001068 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001069 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001070 break;
1071 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001072
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001073 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001074
1075 if (FAD) {
1076 OS << "[Fortran array descriptor: " << FAD->getName();
1077 OS << "] ";
1078 };
1079
Tobias Grossera535dff2015-12-13 19:59:01 +00001080 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001081 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001082 if (hasNewAccessRelation())
1083 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001084}
1085
Tobias Grosser74394f02013-01-14 22:40:23 +00001086void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +00001087
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001088__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
1089 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001090 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +00001091 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
1092 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
1093 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +00001094 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001095}
1096
Tobias Grosser75805372011-04-29 06:27:02 +00001097// Create a map in the size of the provided set domain, that maps from the
1098// one element of the provided set domain to another element of the provided
1099// set domain.
1100// The mapping is limited to all points that are equal in all but the last
1101// dimension and for which the last dimension of the input is strict smaller
1102// than the last dimension of the output.
1103//
1104// getEqualAndLarger(set[i0, i1, ..., iX]):
1105//
1106// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1107// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1108//
Tobias Grosser2a526fe2016-09-08 11:18:56 +00001109static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +00001110 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001111 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +00001112 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001113
1114 // Set all but the last dimension to be equal for the input and output
1115 //
1116 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1117 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001118 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +00001119 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001120
1121 // Set the last dimension of the input to be strict smaller than the
1122 // last dimension of the output.
1123 //
1124 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001125 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1126 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001127 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001128}
1129
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001130__isl_give isl_set *
1131MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001132 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +00001133 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +00001134 isl_space *Space = isl_space_range(isl_map_get_space(S));
1135 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001136
Sebastian Popa00a0292012-12-18 07:46:06 +00001137 S = isl_map_reverse(S);
1138 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001139
Sebastian Popa00a0292012-12-18 07:46:06 +00001140 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1141 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1142 NextScatt = isl_map_apply_domain(NextScatt, S);
1143 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001144
Sebastian Popa00a0292012-12-18 07:46:06 +00001145 isl_set *Deltas = isl_map_deltas(NextScatt);
1146 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001147}
1148
Sebastian Popa00a0292012-12-18 07:46:06 +00001149bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001150 int StrideWidth) const {
1151 isl_set *Stride, *StrideX;
1152 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001153
Sebastian Popa00a0292012-12-18 07:46:06 +00001154 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001155 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001156 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1157 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1158 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1159 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001160 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001161
Tobias Grosser28dd4862012-01-24 16:42:16 +00001162 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001163 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001164
Tobias Grosser28dd4862012-01-24 16:42:16 +00001165 return IsStrideX;
1166}
1167
Michael Krused56b90a2016-09-01 09:03:27 +00001168bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001169 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001170}
1171
Michael Krused56b90a2016-09-01 09:03:27 +00001172bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001173 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001174}
1175
Tobias Grosserbedef002016-12-02 08:10:56 +00001176void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
1177 isl_map_free(AccessRelation);
1178 AccessRelation = NewAccess;
1179}
1180
Michael Krused56b90a2016-09-01 09:03:27 +00001181void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001182 assert(NewAccess);
1183
1184#ifndef NDEBUG
1185 // Check domain space compatibility.
1186 auto *NewSpace = isl_map_get_space(NewAccess);
1187 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1188 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1189 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1190 isl_space_free(NewDomainSpace);
1191 isl_space_free(OriginalDomainSpace);
1192
Michael Kruse706f79a2017-05-21 22:46:57 +00001193 // Reads must be executed unconditionally. Writes might be executed in a
1194 // subdomain only.
1195 if (isRead()) {
1196 // Check whether there is an access for every statement instance.
1197 auto *StmtDomain = getStatement()->getDomain();
1198 StmtDomain = isl_set_intersect_params(
1199 StmtDomain, getStatement()->getParent()->getContext());
1200 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1201 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1202 "Partial READ accesses not supported");
1203 isl_set_free(NewDomain);
1204 isl_set_free(StmtDomain);
1205 }
Michael Kruse772ce722016-09-01 19:16:58 +00001206
Michael Kruse772ce722016-09-01 19:16:58 +00001207 auto *NewAccessSpace = isl_space_range(NewSpace);
1208 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1209 "Must specify the array that is accessed");
1210 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1211 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1212 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001213
1214 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1215 InvariantEquivClassTy *EqClass =
1216 getStatement()->getParent()->lookupInvariantEquivClass(
1217 SAI->getBasePtr());
1218 assert(EqClass &&
1219 "Access functions to indirect arrays must have an invariant and "
1220 "hoisted base pointer");
1221 }
1222
1223 // Check whether access dimensions correspond to number of dimensions of the
1224 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001225 auto Dims = SAI->getNumberOfDimensions();
1226 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1227 "Access dims must match array dims");
1228 isl_space_free(NewAccessSpace);
1229 isl_id_free(NewArrayId);
1230#endif
1231
Tobias Grosser166c4222015-09-05 07:46:40 +00001232 isl_map_free(NewAccessRelation);
1233 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001234}
Tobias Grosser75805372011-04-29 06:27:02 +00001235
Michael Kruse706f79a2017-05-21 22:46:57 +00001236bool MemoryAccess::isLatestPartialAccess() const {
1237 isl::set StmtDom = give(getStatement()->getDomain());
1238 isl::set AccDom = give(isl_map_domain(getLatestAccessRelation()));
1239
1240 return isl_set_is_subset(StmtDom.keep(), AccDom.keep()) == isl_bool_false;
1241}
1242
Tobias Grosser75805372011-04-29 06:27:02 +00001243//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001244
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001245__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001246 isl_set *Domain = getDomain();
1247 if (isl_set_is_empty(Domain)) {
1248 isl_set_free(Domain);
1249 return isl_map_from_aff(
1250 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1251 }
1252 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001253 if (!Schedule) {
1254 isl_set_free(Domain);
1255 return nullptr;
1256 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001257 Schedule = isl_union_map_intersect_domain(
1258 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1259 if (isl_union_map_is_empty(Schedule)) {
1260 isl_set_free(Domain);
1261 isl_union_map_free(Schedule);
1262 return isl_map_from_aff(
1263 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1264 }
1265 auto *M = isl_map_from_union_map(Schedule);
1266 M = isl_map_coalesce(M);
1267 M = isl_map_gist_domain(M, Domain);
1268 M = isl_map_coalesce(M);
1269 return M;
1270}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001271
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001272__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1273 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001274 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1275 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001276}
1277
Tobias Grosser37eb4222014-02-20 21:43:54 +00001278void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1279 assert(isl_set_is_subset(NewDomain, Domain) &&
1280 "New domain is not a subset of old domain!");
1281 isl_set_free(Domain);
1282 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001283}
1284
Michael Krusecac948e2015-10-02 13:53:07 +00001285void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001286 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001287 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001288 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001289
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001290 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001291 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001292 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001293 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001294 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001295 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001296 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001297 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001298 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001299
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001300 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1301 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001302 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001303 }
1304}
1305
Michael Kruse4c276432017-05-11 22:56:46 +00001306MemoryAccess *ScopStmt::lookupPHIReadOf(PHINode *PHI) const {
1307 for (auto *MA : *this) {
1308 if (!MA->isRead())
1309 continue;
1310 if (!MA->isLatestAnyPHIKind())
1311 continue;
1312
1313 if (MA->getAccessInstruction() == PHI)
1314 return MA;
1315 }
1316 return nullptr;
1317}
1318
Michael Krusecac948e2015-10-02 13:53:07 +00001319void ScopStmt::addAccess(MemoryAccess *Access) {
1320 Instruction *AccessInst = Access->getAccessInstruction();
1321
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001322 if (Access->isArrayKind()) {
1323 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1324 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001325 } else if (Access->isValueKind() && Access->isWrite()) {
1326 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001327 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001328 assert(!ValueWrites.lookup(AccessVal));
1329
1330 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001331 } else if (Access->isValueKind() && Access->isRead()) {
1332 Value *AccessVal = Access->getAccessValue();
1333 assert(!ValueReads.lookup(AccessVal));
1334
1335 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001336 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001337 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001338 assert(!PHIWrites.lookup(PHI));
1339
1340 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001341 }
1342
1343 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001344}
1345
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001346void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001347 for (MemoryAccess *MA : *this)
1348 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001349
Johannes Doerferta60ad842016-05-10 12:18:22 +00001350 auto *Ctx = Parent.getContext();
1351 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1352 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001353}
1354
Tobias Grosserc80d6972016-09-02 06:33:33 +00001355/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001356static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1357 void *User) {
1358 isl_set **BoundedParts = static_cast<isl_set **>(User);
1359 if (isl_basic_set_is_bounded(BSet))
1360 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1361 else
1362 isl_basic_set_free(BSet);
1363 return isl_stat_ok;
1364}
1365
Tobias Grosserc80d6972016-09-02 06:33:33 +00001366/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001367static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1368 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1369 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1370 isl_set_free(S);
1371 return BoundedParts;
1372}
1373
Tobias Grosserc80d6972016-09-02 06:33:33 +00001374/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001375///
1376/// @returns A separation of @p S into first an unbounded then a bounded subset,
1377/// both with regards to the dimension @p Dim.
1378static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1379partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1380
1381 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001382 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001383
1384 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001385 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001386
1387 // Remove dimensions that are greater than Dim as they are not interesting.
1388 assert(NumDimsS >= Dim + 1);
1389 OnlyDimS =
1390 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1391
1392 // Create artificial parametric upper bounds for dimensions smaller than Dim
1393 // as we are not interested in them.
1394 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1395 for (unsigned u = 0; u < Dim; u++) {
1396 isl_constraint *C = isl_inequality_alloc(
1397 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1398 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1399 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1400 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1401 }
1402
1403 // Collect all bounded parts of OnlyDimS.
1404 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1405
1406 // Create the dimensions greater than Dim again.
1407 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1408 NumDimsS - Dim - 1);
1409
1410 // Remove the artificial upper bound parameters again.
1411 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1412
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001413 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001414 return std::make_pair(UnboundedParts, BoundedParts);
1415}
1416
Tobias Grosserc80d6972016-09-02 06:33:33 +00001417/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001418static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1419 __isl_take isl_set *To) {
1420 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1421 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1422 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1423 }
1424 return To;
1425}
1426
Tobias Grosserc80d6972016-09-02 06:33:33 +00001427/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001428static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001429 __isl_take isl_pw_aff *L,
1430 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001431 switch (Pred) {
1432 case ICmpInst::ICMP_EQ:
1433 return isl_pw_aff_eq_set(L, R);
1434 case ICmpInst::ICMP_NE:
1435 return isl_pw_aff_ne_set(L, R);
1436 case ICmpInst::ICMP_SLT:
1437 return isl_pw_aff_lt_set(L, R);
1438 case ICmpInst::ICMP_SLE:
1439 return isl_pw_aff_le_set(L, R);
1440 case ICmpInst::ICMP_SGT:
1441 return isl_pw_aff_gt_set(L, R);
1442 case ICmpInst::ICMP_SGE:
1443 return isl_pw_aff_ge_set(L, R);
1444 case ICmpInst::ICMP_ULT:
1445 return isl_pw_aff_lt_set(L, R);
1446 case ICmpInst::ICMP_UGT:
1447 return isl_pw_aff_gt_set(L, R);
1448 case ICmpInst::ICMP_ULE:
1449 return isl_pw_aff_le_set(L, R);
1450 case ICmpInst::ICMP_UGE:
1451 return isl_pw_aff_ge_set(L, R);
1452 default:
1453 llvm_unreachable("Non integer predicate not supported");
1454 }
1455}
1456
Tobias Grosserc80d6972016-09-02 06:33:33 +00001457/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001458///
1459/// Helper function that will make sure the dimensions of the result have the
1460/// same isl_id's as the @p Domain.
1461static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1462 __isl_take isl_pw_aff *L,
1463 __isl_take isl_pw_aff *R,
1464 __isl_keep isl_set *Domain) {
1465 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1466 return setDimensionIds(Domain, ConsequenceCondSet);
1467}
1468
Tobias Grosserc80d6972016-09-02 06:33:33 +00001469/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001470///
1471/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001472/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1473/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001474static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001475buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1476 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001477 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1478
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001479 Value *Condition = getConditionFromTerminator(SI);
1480 assert(Condition && "No condition for switch");
1481
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001482 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001483 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001484 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001485 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001486
1487 unsigned NumSuccessors = SI->getNumSuccessors();
1488 ConditionSets.resize(NumSuccessors);
1489 for (auto &Case : SI->cases()) {
1490 unsigned Idx = Case.getSuccessorIndex();
1491 ConstantInt *CaseValue = Case.getCaseValue();
1492
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001493 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001494 isl_set *CaseConditionSet =
1495 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1496 ConditionSets[Idx] = isl_set_coalesce(
1497 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1498 }
1499
1500 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1501 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1502 for (unsigned u = 2; u < NumSuccessors; u++)
1503 ConditionSetUnion =
1504 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1505 ConditionSets[0] = setDimensionIds(
1506 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1507
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001508 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001509
1510 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001511}
1512
Tobias Grosserc80d6972016-09-02 06:33:33 +00001513/// Build the conditions sets for the branch condition @p Condition in
1514/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001515///
1516/// This will fill @p ConditionSets with the conditions under which control
1517/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001518/// have as many elements as @p TI has successors. If @p TI is nullptr the
1519/// context under which @p Condition is true/false will be returned as the
1520/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001521static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001522buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1523 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001524 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1525
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001526 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001527 isl_set *ConsequenceCondSet = nullptr;
1528 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1529 if (CCond->isZero())
1530 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1531 else
1532 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1533 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1534 auto Opcode = BinOp->getOpcode();
1535 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1536
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001537 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1538 ConditionSets) &&
1539 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1540 ConditionSets);
1541 if (!Valid) {
1542 while (!ConditionSets.empty())
1543 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001544 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001545 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001546
1547 isl_set_free(ConditionSets.pop_back_val());
1548 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1549 isl_set_free(ConditionSets.pop_back_val());
1550 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1551
1552 if (Opcode == Instruction::And)
1553 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1554 else
1555 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1556 } else {
1557 auto *ICond = dyn_cast<ICmpInst>(Condition);
1558 assert(ICond &&
1559 "Condition of exiting branch was neither constant nor ICmp!");
1560
1561 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001562 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001563 // For unsigned comparisons we assumed the signed bit of neither operand
1564 // to be set. The comparison is equal to a signed comparison under this
1565 // assumption.
1566 bool NonNeg = ICond->isUnsigned();
1567 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1568 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001569 ConsequenceCondSet =
1570 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1571 }
1572
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001573 // If no terminator was given we are only looking for parameter constraints
1574 // under which @p Condition is true/false.
1575 if (!TI)
1576 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001577 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001578 ConsequenceCondSet = isl_set_coalesce(
1579 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001580
Johannes Doerfertb2885792016-04-26 09:20:41 +00001581 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001582 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001583 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001584
Michael Krusef7a4a942016-05-02 12:25:36 +00001585 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001586 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1587 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001588 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001589 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001590 }
1591
Michael Krusef7a4a942016-05-02 12:25:36 +00001592 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001593 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001594 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001595 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001596 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001597 }
1598
1599 ConditionSets.push_back(ConsequenceCondSet);
1600 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001601
1602 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001603}
1604
Tobias Grosserc80d6972016-09-02 06:33:33 +00001605/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001606///
1607/// This will fill @p ConditionSets with the conditions under which control
1608/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1609/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001610static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001611buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001612 __isl_keep isl_set *Domain,
1613 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1614
1615 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001616 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001617
1618 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1619
1620 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001621 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001622 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001623 }
1624
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001625 Value *Condition = getConditionFromTerminator(TI);
1626 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001627
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001628 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001629}
1630
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001631void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001632 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001633
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001634 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001635 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001636}
1637
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001638void ScopStmt::collectSurroundingLoops() {
1639 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1640 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1641 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1642 isl_id_free(DimId);
1643 }
1644}
1645
Michael Kruse55454072017-03-15 22:16:43 +00001646ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001647 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
Michael Kruse55454072017-03-15 22:16:43 +00001648 R(&R), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001649
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001650 BaseName = getIslCompatibleName(
1651 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001652}
1653
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001654ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop,
1655 std::vector<Instruction *> Instructions)
Johannes Doerferta3519512016-04-23 13:02:23 +00001656 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001657 R(nullptr), Build(nullptr), SurroundingLoop(SurroundingLoop),
1658 Instructions(Instructions) {
Tobias Grosser75805372011-04-29 06:27:02 +00001659
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001660 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), "",
1661 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001662}
1663
Roman Gareevb3224ad2016-09-14 06:26:09 +00001664ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1665 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1666 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1667 R(nullptr), Build(nullptr) {
1668 BaseName = getIslCompatibleName("CopyStmt_", "",
1669 std::to_string(parent.getCopyStmtsNum()));
1670 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1671 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1672 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1673 auto *Access =
1674 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1675 parent.addAccessFunction(Access);
1676 addAccess(Access);
1677 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1678 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1679 parent.addAccessFunction(Access);
1680 addAccess(Access);
1681}
1682
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001683void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001684 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001685
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001686 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001687 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001688 buildAccessRelations();
1689
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001690 if (DetectReductions)
1691 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001692}
1693
Tobias Grosserc80d6972016-09-02 06:33:33 +00001694/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001695///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001696/// Check if the stored value for @p StoreMA is a binary operator with one or
1697/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001698/// used only once (by @p StoreMA) and its load operands are also used only
1699/// once, we have found a possible reduction chain. It starts at an operand
1700/// load and includes the binary operator and @p StoreMA.
1701///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001702/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001703/// escape this block or into any other store except @p StoreMA.
1704void ScopStmt::collectCandiateReductionLoads(
1705 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1706 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1707 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001708 return;
1709
1710 // Skip if there is not one binary operator between the load and the store
1711 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001712 if (!BinOp)
1713 return;
1714
1715 // Skip if the binary operators has multiple uses
1716 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001717 return;
1718
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001719 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001720 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1721 return;
1722
Johannes Doerfert9890a052014-07-01 00:32:29 +00001723 // Skip if the binary operator is outside the current SCoP
1724 if (BinOp->getParent() != Store->getParent())
1725 return;
1726
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001727 // Skip if it is a multiplicative reduction and we disabled them
1728 if (DisableMultiplicativeReductions &&
1729 (BinOp->getOpcode() == Instruction::Mul ||
1730 BinOp->getOpcode() == Instruction::FMul))
1731 return;
1732
Johannes Doerferte58a0122014-06-27 20:31:28 +00001733 // Check the binary operator operands for a candidate load
1734 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1735 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1736 if (!PossibleLoad0 && !PossibleLoad1)
1737 return;
1738
1739 // A load is only a candidate if it cannot escape (thus has only this use)
1740 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001741 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001742 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001743 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001744 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001745 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001746}
1747
Tobias Grosserc80d6972016-09-02 06:33:33 +00001748/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001749///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001750/// Iterate over all store memory accesses and check for valid binary reduction
1751/// like chains. For all candidates we check if they have the same base address
1752/// and there are no other accesses which overlap with them. The base address
1753/// check rules out impossible reductions candidates early. The overlap check,
1754/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001755/// guarantees that none of the intermediate results will escape during
1756/// execution of the loop nest. We basically check here that no other memory
1757/// access can access the same memory as the potential reduction.
1758void ScopStmt::checkForReductions() {
1759 SmallVector<MemoryAccess *, 2> Loads;
1760 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1761
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001762 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001763 // stores and collecting possible reduction loads.
1764 for (MemoryAccess *StoreMA : MemAccs) {
1765 if (StoreMA->isRead())
1766 continue;
1767
1768 Loads.clear();
1769 collectCandiateReductionLoads(StoreMA, Loads);
1770 for (MemoryAccess *LoadMA : Loads)
1771 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1772 }
1773
1774 // Then check each possible candidate pair.
1775 for (const auto &CandidatePair : Candidates) {
1776 bool Valid = true;
1777 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1778 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1779
1780 // Skip those with obviously unequal base addresses.
1781 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1782 isl_map_free(LoadAccs);
1783 isl_map_free(StoreAccs);
1784 continue;
1785 }
1786
1787 // And check if the remaining for overlap with other memory accesses.
1788 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1789 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1790 isl_set *AllAccs = isl_map_range(AllAccsRel);
1791
1792 for (MemoryAccess *MA : MemAccs) {
1793 if (MA == CandidatePair.first || MA == CandidatePair.second)
1794 continue;
1795
1796 isl_map *AccRel =
1797 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1798 isl_set *Accs = isl_map_range(AccRel);
1799
Tobias Grosser55a7af72016-09-08 14:08:07 +00001800 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001801 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1802 Valid = Valid && isl_set_is_empty(OverlapAccs);
1803 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001804 } else {
1805 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001806 }
1807 }
1808
1809 isl_set_free(AllAccs);
1810 if (!Valid)
1811 continue;
1812
Johannes Doerfertf6183392014-07-01 20:52:51 +00001813 const LoadInst *Load =
1814 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1815 MemoryAccess::ReductionType RT =
1816 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1817
Johannes Doerferte58a0122014-06-27 20:31:28 +00001818 // If no overlapping access was found we mark the load and store as
1819 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001820 CandidatePair.first->markAsReductionLike(RT);
1821 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001822 }
Tobias Grosser75805372011-04-29 06:27:02 +00001823}
1824
Tobias Grosser74394f02013-01-14 22:40:23 +00001825std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001826
Tobias Grosser54839312015-04-21 11:37:25 +00001827std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001828 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001829 if (!S)
1830 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001831 auto Str = stringFromIslObj(S);
1832 isl_map_free(S);
1833 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001834}
1835
Johannes Doerferta3519512016-04-23 13:02:23 +00001836void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1837 isl_set_free(InvalidDomain);
1838 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001839}
1840
Michael Kruse375cb5f2016-02-24 22:08:24 +00001841BasicBlock *ScopStmt::getEntryBlock() const {
1842 if (isBlockStmt())
1843 return getBasicBlock();
1844 return getRegion()->getEntry();
1845}
1846
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001847unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001848
Tobias Grosser75805372011-04-29 06:27:02 +00001849const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1850
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001851Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001852 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001853}
1854
Tobias Grosser74394f02013-01-14 22:40:23 +00001855isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001856
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001857__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001858
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001859__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001860 return isl_set_get_space(Domain);
1861}
1862
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001863__isl_give isl_id *ScopStmt::getDomainId() const {
1864 return isl_set_get_tuple_id(Domain);
1865}
Tobias Grossercd95b772012-08-30 11:49:38 +00001866
Johannes Doerfert7c013572016-04-12 09:57:34 +00001867ScopStmt::~ScopStmt() {
1868 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001869 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001870}
Tobias Grosser75805372011-04-29 06:27:02 +00001871
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001872void ScopStmt::printInstructions(raw_ostream &OS) const {
1873 OS << "Instructions {\n";
1874
1875 for (Instruction *Inst : Instructions)
1876 OS.indent(16) << *Inst << "\n";
1877
1878 OS.indent(16) << "}\n";
1879}
1880
Tobias Grosser75805372011-04-29 06:27:02 +00001881void ScopStmt::print(raw_ostream &OS) const {
1882 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001883 OS.indent(12) << "Domain :=\n";
1884
1885 if (Domain) {
1886 OS.indent(16) << getDomainStr() << ";\n";
1887 } else
1888 OS.indent(16) << "n/a\n";
1889
Tobias Grosser54839312015-04-21 11:37:25 +00001890 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001891
1892 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001893 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001894 } else
1895 OS.indent(16) << "n/a\n";
1896
Tobias Grosser083d3d32014-06-28 08:59:45 +00001897 for (MemoryAccess *Access : MemAccs)
1898 Access->print(OS);
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001899
1900 if (PollyPrintInstructions)
1901 printInstructions(OS.indent(12));
Tobias Grosser75805372011-04-29 06:27:02 +00001902}
1903
1904void ScopStmt::dump() const { print(dbgs()); }
1905
Michael Krusee60eca72017-05-11 22:56:12 +00001906void ScopStmt::removeAccessData(MemoryAccess *MA) {
1907 if (MA->isRead() && MA->isOriginalValueKind()) {
1908 bool Found = ValueReads.erase(MA->getAccessValue());
1909 (void)Found;
1910 assert(Found && "Expected access data not found");
1911 }
1912 if (MA->isWrite() && MA->isOriginalValueKind()) {
1913 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1914 (void)Found;
1915 assert(Found && "Expected access data not found");
1916 }
1917 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1918 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1919 (void)Found;
1920 assert(Found && "Expected access data not found");
1921 }
1922}
1923
Michael Kruse10071822016-05-23 14:45:58 +00001924void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001925 // Remove the memory accesses from this statement together with all scalar
1926 // accesses that were caused by it. MemoryKind::Value READs have no access
1927 // instruction, hence would not be removed by this function. However, it is
1928 // only used for invariant LoadInst accesses, its arguments are always affine,
1929 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1930 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001931 auto Predicate = [&](MemoryAccess *Acc) {
1932 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1933 };
Michael Krusee60eca72017-05-11 22:56:12 +00001934 for (auto *MA : MemAccs) {
1935 if (Predicate(MA))
1936 removeAccessData(MA);
1937 }
Michael Kruse10071822016-05-23 14:45:58 +00001938 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1939 MemAccs.end());
1940 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001941}
1942
Michael Kruse0446d812017-03-10 16:05:24 +00001943void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
1944 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1945 assert(MAIt != MemAccs.end());
1946 MemAccs.erase(MAIt);
1947
Michael Krusee60eca72017-05-11 22:56:12 +00001948 removeAccessData(MA);
1949
Michael Kruse0446d812017-03-10 16:05:24 +00001950 auto It = InstructionToAccess.find(MA->getAccessInstruction());
1951 if (It != InstructionToAccess.end()) {
1952 It->second.remove(MA);
1953 if (It->second.empty())
1954 InstructionToAccess.erase(MA->getAccessInstruction());
1955 }
1956}
1957
Tobias Grosser75805372011-04-29 06:27:02 +00001958//===----------------------------------------------------------------------===//
1959/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001960
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001961void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001962 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1963 isl_set_free(Context);
1964 Context = NewContext;
1965}
1966
Tobias Grosserc80d6972016-09-02 06:33:33 +00001967/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001968struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001969 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001970 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001971
1972public:
1973 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001974 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001975
1976 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1977 ValueToValueMap &VMap) {
1978 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1979 return SSPR.visit(E);
1980 }
1981
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001982 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1983 auto *Start = visit(E->getStart());
1984 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1985 visit(E->getStepRecurrence(SE)),
1986 E->getLoop(), SCEV::FlagAnyWrap);
1987 return SE.getAddExpr(Start, AddRec);
1988 }
1989
1990 const SCEV *visitUnknown(const SCEVUnknown *E) {
1991 if (auto *NewValue = VMap.lookup(E->getValue()))
1992 return SE.getUnknown(NewValue);
1993 return E;
1994 }
1995};
1996
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001997const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001998 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001999}
2000
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002001// This table of function names is used to translate parameter names in more
2002// human-readable names. This makes it easier to interpret Polly analysis
2003// results.
2004StringMap<std::string> KnownNames = {
2005 {"_Z13get_global_idj", "global_id"},
2006 {"_Z12get_local_idj", "local_id"},
2007 {"_Z15get_global_sizej", "global_size"},
2008 {"_Z14get_local_sizej", "local_size"},
2009 {"_Z12get_work_dimv", "work_dim"},
2010 {"_Z17get_global_offsetj", "global_offset"},
2011 {"_Z12get_group_idj", "group_id"},
2012 {"_Z14get_num_groupsj", "num_groups"},
2013};
2014
2015static std::string getCallParamName(CallInst *Call) {
2016 std::string Result;
2017 raw_string_ostream OS(Result);
2018 std::string Name = Call->getCalledFunction()->getName();
2019
2020 auto Iterator = KnownNames.find(Name);
2021 if (Iterator != KnownNames.end())
2022 Name = "__" + KnownNames[Name];
2023 OS << Name;
2024 for (auto &Operand : Call->arg_operands()) {
2025 ConstantInt *Op = cast<ConstantInt>(&Operand);
2026 OS << "_" << Op->getValue();
2027 }
2028 OS.flush();
2029 return Result;
2030}
2031
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002032void Scop::createParameterId(const SCEV *Parameter) {
2033 assert(Parameters.count(Parameter));
2034 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002035
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002036 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002037
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002038 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
2039 Value *Val = ValueParameter->getValue();
2040 CallInst *Call = dyn_cast<CallInst>(Val);
Tobias Grosser8f99c162011-11-15 11:38:55 +00002041
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002042 if (Call && isConstCall(Call)) {
2043 ParameterName = getCallParamName(Call);
2044 } else if (UseInstructionNames) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002045 // If this parameter references a specific Value and this value has a name
2046 // we use this name as it is likely to be unique and more useful than just
2047 // a number.
2048 if (Val->hasName())
2049 ParameterName = Val->getName();
2050 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
2051 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
2052 if (LoadOrigin->hasName()) {
2053 ParameterName += "_loaded_from_";
2054 ParameterName +=
2055 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
2056 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002057 }
2058 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00002059
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002060 ParameterName = getIslCompatibleName("", ParameterName, "");
2061 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00002062
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002063 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
2064 const_cast<void *>((const void *)Parameter));
2065 ParameterIds[Parameter] = Id;
2066}
2067
2068void Scop::addParams(const ParameterSetTy &NewParameters) {
2069 for (const SCEV *Parameter : NewParameters) {
2070 // Normalize the SCEV to get the representing element for an invariant load.
2071 Parameter = extractConstantFactor(Parameter, *SE).second;
2072 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2073
2074 if (Parameters.insert(Parameter))
2075 createParameterId(Parameter);
2076 }
2077}
2078
2079__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
2080 // Normalize the SCEV to get the representing element for an invariant load.
2081 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2082 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00002083}
Tobias Grosser75805372011-04-29 06:27:02 +00002084
Michael Krused56b90a2016-09-01 09:03:27 +00002085__isl_give isl_set *
2086Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002087 isl_set *DomainContext = isl_union_set_params(getDomains());
2088 return isl_set_intersect_params(C, DomainContext);
2089}
2090
Johannes Doerferte0b08072016-05-23 12:43:44 +00002091bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2092 return DT.dominates(BB, getEntry());
2093}
2094
Michael Kruse89b1f942017-03-17 13:56:53 +00002095void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
2096 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002097 auto &F = getFunction();
Michael Kruse89b1f942017-03-17 13:56:53 +00002098 for (auto &Assumption : AC.assumptions()) {
2099 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2100 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002101 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002102
Michael Kruse89b1f942017-03-17 13:56:53 +00002103 bool InScop = contains(CI);
2104 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2105 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002106
Michael Kruse89b1f942017-03-17 13:56:53 +00002107 auto *L = LI.getLoopFor(CI->getParent());
2108 auto *Val = CI->getArgOperand(0);
2109 ParameterSetTy DetectedParams;
2110 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
2111 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
2112 CI->getDebugLoc(),
2113 "Non-affine user assumption ignored.");
2114 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002115 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002116
2117 // Collect all newly introduced parameters.
2118 ParameterSetTy NewParams;
2119 for (auto *Param : DetectedParams) {
2120 Param = extractConstantFactor(Param, *SE).second;
2121 Param = getRepresentingInvariantLoadSCEV(Param);
2122 if (Parameters.count(Param))
2123 continue;
2124 NewParams.insert(Param);
2125 }
2126
2127 SmallVector<isl_set *, 2> ConditionSets;
2128 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
2129 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
2130 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
2131 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
2132 isl_set_free(Dom);
2133
2134 if (!Valid)
2135 continue;
2136
2137 isl_set *AssumptionCtx = nullptr;
2138 if (InScop) {
2139 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2140 isl_set_free(ConditionSets[0]);
2141 } else {
2142 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2143 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2144 }
2145
2146 // Project out newly introduced parameters as they are not otherwise useful.
2147 if (!NewParams.empty()) {
2148 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2149 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2150 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2151 isl_id_free(Id);
2152
2153 if (!NewParams.count(Param))
2154 continue;
2155
2156 AssumptionCtx =
2157 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2158 }
2159 }
2160
2161 emitOptimizationRemarkAnalysis(
2162 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
2163 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
2164 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002165 }
2166}
2167
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002168void Scop::addUserContext() {
2169 if (UserContextStr.empty())
2170 return;
2171
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002172 isl_set *UserContext =
2173 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002174 isl_space *Space = getParamSpace();
2175 if (isl_space_dim(Space, isl_dim_param) !=
2176 isl_set_dim(UserContext, isl_dim_param)) {
2177 auto SpaceStr = isl_space_to_str(Space);
2178 errs() << "Error: the context provided in -polly-context has not the same "
2179 << "number of dimensions than the computed context. Due to this "
2180 << "mismatch, the -polly-context option is ignored. Please provide "
2181 << "the context in the parameter space: " << SpaceStr << ".\n";
2182 free(SpaceStr);
2183 isl_set_free(UserContext);
2184 isl_space_free(Space);
2185 return;
2186 }
2187
2188 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002189 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2190 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002191
2192 if (strcmp(NameContext, NameUserContext) != 0) {
2193 auto SpaceStr = isl_space_to_str(Space);
2194 errs() << "Error: the name of dimension " << i
2195 << " provided in -polly-context "
2196 << "is '" << NameUserContext << "', but the name in the computed "
2197 << "context is '" << NameContext
2198 << "'. Due to this name mismatch, "
2199 << "the -polly-context option is ignored. Please provide "
2200 << "the context in the parameter space: " << SpaceStr << ".\n";
2201 free(SpaceStr);
2202 isl_set_free(UserContext);
2203 isl_space_free(Space);
2204 return;
2205 }
2206
2207 UserContext =
2208 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2209 isl_space_get_dim_id(Space, isl_dim_param, i));
2210 }
2211
2212 Context = isl_set_intersect(Context, UserContext);
2213 isl_space_free(Space);
2214}
2215
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002216void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002217 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002218
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002219 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002220 for (LoadInst *LInst : RIL) {
2221 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2222
Johannes Doerfert96e54712016-02-07 17:30:13 +00002223 Type *Ty = LInst->getType();
2224 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002225 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002226 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002227 continue;
2228 }
2229
2230 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002231 InvariantEquivClasses.emplace_back(
2232 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002233 }
2234}
2235
Tobias Grosser6be480c2011-11-08 15:41:13 +00002236void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002237 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002238 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002239 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002240 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002241}
2242
Tobias Grosser18daaca2012-05-22 10:47:27 +00002243void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002244 unsigned PDim = 0;
2245 for (auto *Parameter : Parameters) {
2246 ConstantRange SRange = SE->getSignedRange(Parameter);
Tobias Grosser99ea1d02017-05-21 20:23:20 +00002247 Context =
2248 addRangeBoundsToSet(give(Context), SRange, PDim++, isl::dim::param)
2249 .release();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002250 }
2251}
2252
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002253// We use the outermost dimension to generate GPU transfers for Fortran arrays
2254// even when the array bounds are not known statically. To do so, we need the
2255// outermost dimension information. We add this into the context so that the
2256// outermost dimension is available during codegen.
2257// We currently do not care about dimensions other than the outermost
2258// dimension since it doesn't affect transfers.
2259static isl_set *addFortranArrayOutermostDimParams(__isl_give isl_set *Context,
2260 Scop::array_range Arrays) {
2261
2262 std::vector<isl_id *> OutermostSizeIds;
2263 for (auto Array : Arrays) {
2264 // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2265 // for its outermost dimension. Fortran arrays will have this since the
2266 // outermost dimension size can be picked up from their runtime description.
2267 // TODO: actually need to check if it has a FAD, but for now this works.
2268 if (Array->getNumberOfDimensions() > 0) {
2269 isl_pw_aff *PwAff = Array->getDimensionSizePw(0);
2270 if (!PwAff)
2271 continue;
2272
2273 isl_id *Id = isl_pw_aff_get_dim_id(PwAff, isl_dim_param, 0);
2274 isl_pw_aff_free(PwAff);
2275 assert(Id && "Invalid Id for PwAff expression in Fortran array");
2276 OutermostSizeIds.push_back(Id);
2277 }
2278 }
2279
2280 const int NumTrueParams = isl_set_dim(Context, isl_dim_param);
2281 Context = isl_set_add_dims(Context, isl_dim_param, OutermostSizeIds.size());
2282
2283 for (size_t i = 0; i < OutermostSizeIds.size(); i++) {
2284 Context = isl_set_set_dim_id(Context, isl_dim_param, NumTrueParams + i,
2285 OutermostSizeIds[i]);
2286 Context =
2287 isl_set_lower_bound_si(Context, isl_dim_param, NumTrueParams + i, 0);
2288 }
2289
2290 return Context;
2291}
2292
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002293void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002294 if (PollyIgnoreParamBounds)
2295 return;
2296
Tobias Grosser6be480c2011-11-08 15:41:13 +00002297 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002298 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002299
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002300 unsigned PDim = 0;
2301 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002302 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002303 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002304 }
2305
2306 // Align the parameters of all data structures to the model.
2307 Context = isl_set_align_params(Context, Space);
2308
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002309 // Add the outermost dimension of the Fortran arrays into the Context.
2310 // See the description of the function for more information.
2311 Context = addFortranArrayOutermostDimParams(Context, arrays());
2312
Johannes Doerferta60ad842016-05-10 12:18:22 +00002313 // As all parameters are known add bounds to them.
2314 addParameterBounds();
2315
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002316 for (ScopStmt &Stmt : *this)
2317 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002318 // Simplify the schedule according to the context too.
2319 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002320}
2321
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002322static __isl_give isl_set *
2323simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2324 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002325 // If we have modeled all blocks in the SCoP that have side effects we can
2326 // simplify the context with the constraints that are needed for anything to
2327 // be executed at all. However, if we have error blocks in the SCoP we already
2328 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002329 // domains, thus we cannot use the remaining domain to simplify the
2330 // assumptions.
2331 if (!S.hasErrorBlock()) {
2332 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2333 AssumptionContext =
2334 isl_set_gist_params(AssumptionContext, DomainParameters);
2335 }
2336
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002337 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2338 return AssumptionContext;
2339}
2340
2341void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002342 // The parameter constraints of the iteration domains give us a set of
2343 // constraints that need to hold for all cases where at least a single
2344 // statement iteration is executed in the whole scop. We now simplify the
2345 // assumed context under the assumption that such constraints hold and at
2346 // least a single statement iteration is executed. For cases where no
2347 // statement instances are executed, the assumptions we have taken about
2348 // the executed code do not matter and can be changed.
2349 //
2350 // WARNING: This only holds if the assumptions we have taken do not reduce
2351 // the set of statement instances that are executed. Otherwise we
2352 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002353 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002354 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002355 // performed. In such a case, modifying the run-time conditions and
2356 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002357 // to not be executed.
2358 //
2359 // Example:
2360 //
2361 // When delinearizing the following code:
2362 //
2363 // for (long i = 0; i < 100; i++)
2364 // for (long j = 0; j < m; j++)
2365 // A[i+p][j] = 1.0;
2366 //
2367 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002368 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002369 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002370 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002371 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002372}
2373
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002374struct MinMaxData {
2375 Scop::MinMaxVectorTy &MinMaxAccesses;
2376 Scop &S;
2377};
2378
Tobias Grosserc80d6972016-09-02 06:33:33 +00002379/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002380static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002381 auto Data = (struct MinMaxData *)User;
2382 Scop::MinMaxVectorTy *MinMaxAccesses = &Data->MinMaxAccesses;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002383 isl_pw_multi_aff *MinPMA, *MaxPMA;
2384 isl_pw_aff *LastDimAff;
2385 isl_aff *OneAff;
2386 unsigned Pos;
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002387 isl_ctx *Ctx = isl_set_get_ctx(Set);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002388
Johannes Doerfert6296d952016-04-22 11:38:19 +00002389 Set = isl_set_remove_divs(Set);
2390
Tobias Grosser90411a92017-02-16 19:11:33 +00002391 if (isl_set_n_basic_set(Set) >= MaxDisjunctsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002392 isl_set_free(Set);
2393 return isl_stat_error;
2394 }
2395
Johannes Doerfert9143d672014-09-27 11:02:39 +00002396 // Restrict the number of parameters involved in the access as the lexmin/
2397 // lexmax computation will take too long if this number is high.
2398 //
2399 // Experiments with a simple test case using an i7 4800MQ:
2400 //
2401 // #Parameters involved | Time (in sec)
2402 // 6 | 0.01
2403 // 7 | 0.04
2404 // 8 | 0.12
2405 // 9 | 0.40
2406 // 10 | 1.54
2407 // 11 | 6.78
2408 // 12 | 30.38
2409 //
2410 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2411 unsigned InvolvedParams = 0;
2412 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2413 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2414 InvolvedParams++;
2415
2416 if (InvolvedParams > RunTimeChecksMaxParameters) {
2417 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002418 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002419 }
2420 }
2421
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002422 {
2423 IslMaxOperationsGuard MaxOpGuard(isl_set_get_ctx(Set), OptComputeOut);
2424 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2425 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2426 }
2427
2428 if (isl_ctx_last_error(Ctx) == isl_error_quota) {
2429 MinPMA = isl_pw_multi_aff_free(MinPMA);
2430 MaxPMA = isl_pw_multi_aff_free(MaxPMA);
2431 Set = isl_set_free(Set);
2432 Data->S.invalidate(COMPLEXITY, DebugLoc());
2433 return isl_stat_error;
2434 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002435
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002436 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2437 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2438
Johannes Doerfertb164c792014-09-18 11:17:17 +00002439 // Adjust the last dimension of the maximal access by one as we want to
2440 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2441 // we test during code generation might now point after the end of the
2442 // allocated array but we will never dereference it anyway.
2443 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2444 "Assumed at least one output dimension");
2445 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2446 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2447 OneAff = isl_aff_zero_on_domain(
2448 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2449 OneAff = isl_aff_add_constant_si(OneAff, 1);
2450 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2451 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2452
2453 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2454
2455 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002456 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002457}
2458
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002459static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2460 isl_set *Domain = MA->getStatement()->getDomain();
2461 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2462 return isl_set_reset_tuple_id(Domain);
2463}
2464
Tobias Grosserc80d6972016-09-02 06:33:33 +00002465/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002466static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002467 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002468
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002469 struct MinMaxData Data = {MinMaxAccesses, S};
2470 Data.MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002471
2472 isl_union_set *Domains = S.getDomains();
2473 isl_union_map *Accesses = isl_union_map_empty(S.getParamSpace());
2474
2475 for (MemoryAccess *MA : AliasGroup)
2476 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2477
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002478 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2479 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002480 Locations = isl_union_set_coalesce(Locations);
2481 Locations = isl_union_set_detect_equalities(Locations);
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002482 bool Valid =
2483 (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess, &Data));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002484 isl_union_set_free(Locations);
2485 return Valid;
2486}
2487
Tobias Grosserc80d6972016-09-02 06:33:33 +00002488/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002489///
2490///{
2491
Tobias Grosserc80d6972016-09-02 06:33:33 +00002492/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002493static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2494 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2495 : RN->getNodeAs<BasicBlock>();
2496}
2497
Tobias Grosserc80d6972016-09-02 06:33:33 +00002498/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002499static inline BasicBlock *
2500getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002501 if (RN->isSubRegion()) {
2502 assert(idx == 0);
2503 return RN->getNodeAs<Region>()->getExit();
2504 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002505 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002506}
2507
Tobias Grosserc80d6972016-09-02 06:33:33 +00002508/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002509static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002510 if (!RN->isSubRegion()) {
2511 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2512 Loop *L = LI.getLoopFor(BB);
2513
2514 // Unreachable statements are not considered to belong to a LLVM loop, as
2515 // they are not part of an actual loop in the control flow graph.
2516 // Nevertheless, we handle certain unreachable statements that are common
2517 // when modeling run-time bounds checks as being part of the loop to be
2518 // able to model them and to later eliminate the run-time bounds checks.
2519 //
2520 // Specifically, for basic blocks that terminate in an unreachable and
2521 // where the immeditate predecessor is part of a loop, we assume these
2522 // basic blocks belong to the loop the predecessor belongs to. This
2523 // allows us to model the following code.
2524 //
2525 // for (i = 0; i < N; i++) {
2526 // if (i > 1024)
2527 // abort(); <- this abort might be translated to an
2528 // unreachable
2529 //
2530 // A[i] = ...
2531 // }
2532 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2533 L = LI.getLoopFor(BB->getPrevNode());
2534 return L;
2535 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002536
2537 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2538 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2539 while (L && NonAffineSubRegion->contains(L))
2540 L = L->getParentLoop();
2541 return L;
2542}
2543
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002544/// Get the number of blocks in @p L.
2545///
2546/// The number of blocks in a loop are the number of basic blocks actually
2547/// belonging to the loop, as well as all single basic blocks that the loop
2548/// exits to and which terminate in an unreachable instruction. We do not
2549/// allow such basic blocks in the exit of a scop, hence they belong to the
2550/// scop and represent run-time conditions which we want to model and
2551/// subsequently speculate away.
2552///
2553/// @see getRegionNodeLoop for additional details.
2554long getNumBlocksInLoop(Loop *L) {
2555 long NumBlocks = L->getNumBlocks();
2556 SmallVector<llvm::BasicBlock *, 4> ExitBlocks;
2557 L->getExitBlocks(ExitBlocks);
2558
2559 for (auto ExitBlock : ExitBlocks) {
2560 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2561 NumBlocks++;
2562 }
2563 return NumBlocks;
2564}
2565
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002566static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2567 if (!RN->isSubRegion())
2568 return 1;
2569
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002570 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002571 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002572}
2573
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002574static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2575 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002576 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002577 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002578 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002579 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002580 return true;
2581 return false;
2582}
2583
Johannes Doerfert96425c22015-08-30 21:13:53 +00002584///}
2585
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002586static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2587 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002588 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002589 isl_id *DimId =
2590 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2591 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2592}
2593
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002594__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002595 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002596}
2597
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002598__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002599 auto DIt = DomainMap.find(BB);
2600 if (DIt != DomainMap.end())
2601 return isl_set_copy(DIt->getSecond());
2602
2603 auto &RI = *R.getRegionInfo();
2604 auto *BBR = RI.getRegionFor(BB);
2605 while (BBR->getEntry() == BB)
2606 BBR = BBR->getParent();
2607 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002608}
2609
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002610bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002611
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002612 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002613 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002614 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2615 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002616 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002617
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002618 while (LD-- >= 0) {
2619 S = addDomainDimId(S, LD + 1, L);
2620 L = L->getParentLoop();
2621 }
2622
Johannes Doerferta3519512016-04-23 13:02:23 +00002623 // Initialize the invalid domain.
2624 auto *EntryStmt = getStmtFor(EntryBB);
2625 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2626
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002627 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002628
Johannes Doerfert432658d2016-01-26 11:01:41 +00002629 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002630 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002631
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002632 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002633 return false;
2634
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002635 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002636 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002637
2638 // Error blocks and blocks dominated by them have been assumed to never be
2639 // executed. Representing them in the Scop does not add any value. In fact,
2640 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002641 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002642 // will cause problems when building up a ScopStmt for them.
2643 // Furthermore, basic blocks dominated by error blocks may reference
2644 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002645 // can themselves not be constructed properly. To this end we will replace
2646 // the domains of error blocks and those only reachable via error blocks
2647 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002648 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002649 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002650 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002651 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002652
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002653 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002654}
2655
Tobias Grosserc80d6972016-09-02 06:33:33 +00002656/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002657/// to be compatible to domains constructed for loop @p NewL.
2658///
2659/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2660/// edge from @p OldL to @p NewL.
2661static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2662 __isl_take isl_set *Dom,
2663 Loop *OldL, Loop *NewL) {
2664
2665 // If the loops are the same there is nothing to do.
2666 if (NewL == OldL)
2667 return Dom;
2668
2669 int OldDepth = S.getRelativeLoopDepth(OldL);
2670 int NewDepth = S.getRelativeLoopDepth(NewL);
2671 // If both loops are non-affine loops there is nothing to do.
2672 if (OldDepth == -1 && NewDepth == -1)
2673 return Dom;
2674
2675 // Distinguish three cases:
2676 // 1) The depth is the same but the loops are not.
2677 // => One loop was left one was entered.
2678 // 2) The depth increased from OldL to NewL.
2679 // => One loop was entered, none was left.
2680 // 3) The depth decreased from OldL to NewL.
2681 // => Loops were left were difference of the depths defines how many.
2682 if (OldDepth == NewDepth) {
2683 assert(OldL->getParentLoop() == NewL->getParentLoop());
2684 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2685 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2686 Dom = addDomainDimId(Dom, NewDepth, NewL);
2687 } else if (OldDepth < NewDepth) {
2688 assert(OldDepth + 1 == NewDepth);
2689 auto &R = S.getRegion();
2690 (void)R;
2691 assert(NewL->getParentLoop() == OldL ||
2692 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2693 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2694 Dom = addDomainDimId(Dom, NewDepth, NewL);
2695 } else {
2696 assert(OldDepth > NewDepth);
2697 int Diff = OldDepth - NewDepth;
2698 int NumDim = isl_set_n_dim(Dom);
2699 assert(NumDim >= Diff);
2700 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2701 }
2702
2703 return Dom;
2704}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002705
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002706bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2707 LoopInfo &LI) {
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002708 ReversePostOrderTraversal<Region *> RTraversal(R);
2709 for (auto *RN : RTraversal) {
2710
2711 // Recurse for affine subregions but go on for basic blocks and non-affine
2712 // subregions.
2713 if (RN->isSubRegion()) {
2714 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002715 if (!isNonAffineSubRegion(SubRegion)) {
2716 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002717 continue;
2718 }
2719 }
2720
2721 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2722 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002723 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002724 isl_set *&Domain = DomainMap[BB];
2725 assert(Domain && "Cannot propagate a nullptr");
2726
Johannes Doerferta3519512016-04-23 13:02:23 +00002727 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002728 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002729 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002730
Johannes Doerferta3519512016-04-23 13:02:23 +00002731 if (!IsInvalidBlock) {
2732 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002733 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002734 isl_set_free(InvalidDomain);
2735 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002736 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2737 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2738 AS_RESTRICTION);
2739 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002740 }
2741
Johannes Doerferta3519512016-04-23 13:02:23 +00002742 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002743 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002744 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002745 }
2746
Johannes Doerferta3519512016-04-23 13:02:23 +00002747 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002748 auto *TI = BB->getTerminator();
2749 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2750 for (unsigned u = 0; u < NumSuccs; u++) {
2751 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002752 auto *SuccStmt = getStmtFor(SuccBB);
2753
2754 // Skip successors outside the SCoP.
2755 if (!SuccStmt)
2756 continue;
2757
Johannes Doerferte4459a22016-04-25 13:34:50 +00002758 // Skip backedges.
2759 if (DT.dominates(SuccBB, BB))
2760 continue;
2761
Michael Kruse55454072017-03-15 22:16:43 +00002762 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta3519512016-04-23 13:02:23 +00002763 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2764 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2765 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2766 SuccInvalidDomain =
2767 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2768 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2769 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2770 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002771
Michael Krusebc150122016-05-02 12:25:18 +00002772 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002773 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002774 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002775 continue;
2776
Johannes Doerferta3519512016-04-23 13:02:23 +00002777 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002778 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002779 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002780 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002781
2782 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002783 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002784
2785 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002786}
2787
Johannes Doerfert642594a2016-04-04 07:57:39 +00002788void Scop::propagateDomainConstraintsToRegionExit(
2789 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002790 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002791
2792 // Check if the block @p BB is the entry of a region. If so we propagate it's
2793 // domain to the exit block of the region. Otherwise we are done.
2794 auto *RI = R.getRegionInfo();
2795 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2796 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002797 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002798 return;
2799
Johannes Doerfert642594a2016-04-04 07:57:39 +00002800 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002801 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002802 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002803 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002804 SmallVector<BasicBlock *, 4> LatchBBs;
2805 BBLoop->getLoopLatches(LatchBBs);
2806 for (auto *LatchBB : LatchBBs)
2807 if (BB != LatchBB && BBReg->contains(LatchBB))
2808 return;
2809 L = L->getParentLoop();
2810 }
2811
2812 auto *Domain = DomainMap[BB];
2813 assert(Domain && "Cannot propagate a nullptr");
2814
Michael Kruse55454072017-03-15 22:16:43 +00002815 auto *ExitStmt = getStmtFor(ExitBB);
2816 auto *ExitBBLoop = ExitStmt->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002817
2818 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2819 // adjust the domain before we can propagate it.
2820 auto *AdjustedDomain =
2821 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2822 auto *&ExitDomain = DomainMap[ExitBB];
2823
2824 // If the exit domain is not yet created we set it otherwise we "add" the
2825 // current domain.
2826 ExitDomain =
2827 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2828
Johannes Doerferta3519512016-04-23 13:02:23 +00002829 // Initialize the invalid domain.
Johannes Doerferta3519512016-04-23 13:02:23 +00002830 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2831
Johannes Doerfert642594a2016-04-04 07:57:39 +00002832 FinishedExitBlocks.insert(ExitBB);
2833}
2834
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002835bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2836 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002837 // To create the domain for each block in R we iterate over all blocks and
2838 // subregions in R and propagate the conditions under which the current region
2839 // element is executed. To this end we iterate in reverse post order over R as
2840 // it ensures that we first visit all predecessors of a region node (either a
2841 // basic block or a subregion) before we visit the region node itself.
2842 // Initially, only the domain for the SCoP region entry block is set and from
2843 // there we propagate the current domain to all successors, however we add the
2844 // condition that the successor is actually executed next.
2845 // As we are only interested in non-loop carried constraints here we can
2846 // simply skip loop back edges.
2847
Johannes Doerfert642594a2016-04-04 07:57:39 +00002848 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002849 ReversePostOrderTraversal<Region *> RTraversal(R);
2850 for (auto *RN : RTraversal) {
2851
2852 // Recurse for affine subregions but go on for basic blocks and non-affine
2853 // subregions.
2854 if (RN->isSubRegion()) {
2855 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002856 if (!isNonAffineSubRegion(SubRegion)) {
2857 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002858 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002859 continue;
2860 }
2861 }
2862
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002863 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002864 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002865
Johannes Doerfert96425c22015-08-30 21:13:53 +00002866 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002867 TerminatorInst *TI = BB->getTerminator();
2868
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002869 if (isa<UnreachableInst>(TI))
2870 continue;
2871
Johannes Doerfertf5673802015-10-01 23:48:18 +00002872 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002873 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002874 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002875 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002876
Johannes Doerfert642594a2016-04-04 07:57:39 +00002877 auto *BBLoop = getRegionNodeLoop(RN, LI);
2878 // Propagate the domain from BB directly to blocks that have a superset
2879 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002880 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002881
2882 // If all successors of BB have been set a domain through the propagation
2883 // above we do not need to build condition sets but can just skip this
2884 // block. However, it is important to note that this is a local property
2885 // with regards to the region @p R. To this end FinishedExitBlocks is a
2886 // local variable.
2887 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2888 return FinishedExitBlocks.count(SuccBB);
2889 };
2890 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2891 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002892
2893 // Build the condition sets for the successor nodes of the current region
2894 // node. If it is a non-affine subregion we will always execute the single
2895 // exit node, hence the single entry node domain is the condition set. For
2896 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002897 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002898 if (RN->isSubRegion())
2899 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002900 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2901 ConditionSets))
2902 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002903
2904 // Now iterate over the successors and set their initial domain based on
2905 // their condition set. We skip back edges here and have to be careful when
2906 // we leave a loop not to keep constraints over a dimension that doesn't
2907 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002908 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002909 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002910 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002911 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002912
Johannes Doerfert535de032016-04-19 14:49:05 +00002913 auto *SuccStmt = getStmtFor(SuccBB);
2914 // Skip blocks outside the region.
2915 if (!SuccStmt) {
2916 isl_set_free(CondSet);
2917 continue;
2918 }
2919
Johannes Doerfert642594a2016-04-04 07:57:39 +00002920 // If we propagate the domain of some block to "SuccBB" we do not have to
2921 // adjust the domain.
2922 if (FinishedExitBlocks.count(SuccBB)) {
2923 isl_set_free(CondSet);
2924 continue;
2925 }
2926
Johannes Doerfert96425c22015-08-30 21:13:53 +00002927 // Skip back edges.
2928 if (DT.dominates(SuccBB, BB)) {
2929 isl_set_free(CondSet);
2930 continue;
2931 }
2932
Michael Kruse55454072017-03-15 22:16:43 +00002933 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002934 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002935
2936 // Set the domain for the successor or merge it with an existing domain in
2937 // case there are multiple paths (without loop back edges) to the
2938 // successor block.
2939 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002940
Johannes Doerferta3519512016-04-23 13:02:23 +00002941 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002942 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002943 } else {
2944 // Initialize the invalid domain.
2945 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2946 SuccDomain = CondSet;
2947 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002948
Tobias Grosser6d459c52017-05-23 04:26:28 +00002949 SuccDomain = isl_set_detect_equalities(SuccDomain);
2950
Michael Krusebc150122016-05-02 12:25:18 +00002951 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002952 // In case this happens we will clean up and bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002953 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002954 continue;
2955
2956 invalidate(COMPLEXITY, DebugLoc());
2957 while (++u < ConditionSets.size())
2958 isl_set_free(ConditionSets[u]);
2959 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002960 }
2961 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002962
2963 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002964}
2965
Michael Krused56b90a2016-09-01 09:03:27 +00002966__isl_give isl_set *
2967Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2968 __isl_keep isl_set *Domain,
2969 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002970 // If @p BB is the ScopEntry we are done
2971 if (R.getEntry() == BB)
2972 return isl_set_universe(isl_set_get_space(Domain));
2973
Johannes Doerfert642594a2016-04-04 07:57:39 +00002974 // The region info of this function.
2975 auto &RI = *R.getRegionInfo();
2976
Michael Kruse55454072017-03-15 22:16:43 +00002977 auto *BBLoop = getStmtFor(BB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002978
2979 // A domain to collect all predecessor domains, thus all conditions under
2980 // which the block is executed. To this end we start with the empty domain.
2981 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2982
2983 // Set of regions of which the entry block domain has been propagated to BB.
2984 // all predecessors inside any of the regions can be skipped.
2985 SmallSet<Region *, 8> PropagatedRegions;
2986
2987 for (auto *PredBB : predecessors(BB)) {
2988 // Skip backedges.
2989 if (DT.dominates(BB, PredBB))
2990 continue;
2991
2992 // If the predecessor is in a region we used for propagation we can skip it.
2993 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2994 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2995 PredBBInRegion)) {
2996 continue;
2997 }
2998
2999 // Check if there is a valid region we can use for propagation, thus look
3000 // for a region that contains the predecessor and has @p BB as exit block.
3001 auto *PredR = RI.getRegionFor(PredBB);
3002 while (PredR->getExit() != BB && !PredR->contains(BB))
3003 PredR->getParent();
3004
3005 // If a valid region for propagation was found use the entry of that region
3006 // for propagation, otherwise the PredBB directly.
3007 if (PredR->getExit() == BB) {
3008 PredBB = PredR->getEntry();
3009 PropagatedRegions.insert(PredR);
3010 }
3011
Johannes Doerfert41cda152016-04-08 10:32:26 +00003012 auto *PredBBDom = getDomainConditions(PredBB);
Michael Kruse55454072017-03-15 22:16:43 +00003013 auto *PredBBLoop = getStmtFor(PredBB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00003014 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
3015
3016 PredDom = isl_set_union(PredDom, PredBBDom);
3017 }
3018
3019 return PredDom;
3020}
3021
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003022bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
3023 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003024 // Iterate over the region R and propagate the domain constrains from the
3025 // predecessors to the current node. In contrast to the
3026 // buildDomainsWithBranchConstraints function, this one will pull the domain
3027 // information from the predecessors instead of pushing it to the successors.
3028 // Additionally, we assume the domains to be already present in the domain
3029 // map here. However, we iterate again in reverse post order so we know all
3030 // predecessors have been visited before a block or non-affine subregion is
3031 // visited.
3032
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003033 ReversePostOrderTraversal<Region *> RTraversal(R);
3034 for (auto *RN : RTraversal) {
3035
3036 // Recurse for affine subregions but go on for basic blocks and non-affine
3037 // subregions.
3038 if (RN->isSubRegion()) {
3039 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003040 if (!isNonAffineSubRegion(SubRegion)) {
3041 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003042 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003043 continue;
3044 }
3045 }
3046
3047 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003048 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00003049 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003050
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003051 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003052 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003053 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00003054 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003055
Johannes Doerfert642594a2016-04-04 07:57:39 +00003056 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00003057 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003058 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
3059 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003060 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00003061
3062 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003063}
3064
Tobias Grosserc80d6972016-09-02 06:33:33 +00003065/// Create a map to map from a given iteration to a subsequent iteration.
3066///
3067/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
3068/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003069/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00003070///
3071/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003072static __isl_give isl_map *
3073createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
3074 auto *MapSpace = isl_space_map_from_set(SetSpace);
3075 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00003076 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003077 if (u != Dim)
3078 NextIterationMap =
3079 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
3080 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
3081 C = isl_constraint_set_constant_si(C, 1);
3082 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
3083 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
3084 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
3085 return NextIterationMap;
3086}
3087
Johannes Doerfert297c7202016-05-10 13:06:42 +00003088bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003089 int LoopDepth = getRelativeLoopDepth(L);
3090 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003091
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003092 BasicBlock *HeaderBB = L->getHeader();
3093 assert(DomainMap.count(HeaderBB));
3094 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003095
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003096 isl_map *NextIterationMap =
3097 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003098
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003099 isl_set *UnionBackedgeCondition =
3100 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003101
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003102 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
3103 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003104
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003105 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003106
3107 // If the latch is only reachable via error statements we skip it.
3108 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
3109 if (!LatchBBDom)
3110 continue;
3111
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003112 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003113
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003114 TerminatorInst *TI = LatchBB->getTerminator();
3115 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00003116 assert(BI && "Only branch instructions allowed in loop latches");
3117
3118 if (BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003119 BackedgeCondition = isl_set_copy(LatchBBDom);
3120 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003121 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003122 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00003123 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
Michael Krusee1dc3872016-11-03 15:19:41 +00003124 ConditionSets)) {
3125 isl_map_free(NextIterationMap);
3126 isl_set_free(UnionBackedgeCondition);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003127 return false;
Michael Krusee1dc3872016-11-03 15:19:41 +00003128 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003129
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003130 // Free the non back edge condition set as we do not need it.
3131 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003132
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003133 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003134 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003135
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003136 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3137 assert(LatchLoopDepth >= LoopDepth);
3138 BackedgeCondition =
3139 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
3140 LatchLoopDepth - LoopDepth);
3141 UnionBackedgeCondition =
3142 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003143 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003144
3145 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
3146 for (int i = 0; i < LoopDepth; i++)
3147 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
3148
3149 isl_set *UnionBackedgeConditionComplement =
3150 isl_set_complement(UnionBackedgeCondition);
3151 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
3152 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
3153 UnionBackedgeConditionComplement =
3154 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
3155 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
3156 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
3157
3158 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
3159 HeaderBBDom = Parts.second;
3160
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003161 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3162 // the bounded assumptions to the context as they are already implied by the
3163 // <nsw> tag.
3164 if (Affinator.hasNSWAddRecForLoop(L)) {
3165 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003166 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003167 }
3168
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003169 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003170 recordAssumption(INFINITELOOP, UnboundedCtx,
3171 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003172 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003173}
3174
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003175MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003176 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003177
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003178 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003179 if (!PointerBaseInst)
3180 return nullptr;
3181
3182 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3183 if (!BasePtrStmt)
3184 return nullptr;
3185
3186 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3187}
3188
3189bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
3190 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003191 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
3192 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
3193 bool Hoistable = NHCtx != nullptr;
3194 isl_set_free(NHCtx);
3195 return !Hoistable;
3196 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003197
Tobias Grosserbe372d52017-02-09 10:11:58 +00003198 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003199 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003200 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003201 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003202
3203 return false;
3204}
3205
Johannes Doerfert5210da52016-06-02 11:06:54 +00003206bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003207 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003208 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003209
Johannes Doerfertcd195322016-11-17 21:41:08 +00003210 if (buildAliasGroups(AA)) {
3211 // Aliasing assumptions do not go through addAssumption but we still want to
3212 // collect statistics so we do it here explicitly.
3213 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003214 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003215 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003216 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003217
3218 // If a problem occurs while building the alias groups we need to delete
3219 // this SCoP and pretend it wasn't valid in the first place. To this end
3220 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003221 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003222
3223 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3224 << " could not be created as the number of parameters involved "
3225 "is too high. The SCoP will be "
3226 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3227 "the maximal number of parameters but be advised that the "
3228 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003229 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003230}
3231
Tobias Grosser889830b2017-02-09 23:12:22 +00003232std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003233Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003234 AliasSetTracker AST(AA);
3235
3236 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003237 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003238 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003239
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003240 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003241 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3242 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003243
3244 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003245 if (StmtDomainEmpty)
3246 continue;
3247
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003248 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003249 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003250 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003251 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003252 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003253 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003254 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003255 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003256 else
3257 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003258 AST.add(Acc);
3259 }
3260 }
3261
Tobias Grosser9edcf072017-01-16 14:07:57 +00003262 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003263 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003264 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003265 continue;
3266 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003267 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003268 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003269 if (AG.size() < 2)
3270 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003271 AliasGroups.push_back(std::move(AG));
3272 }
3273
Tobias Grosser9edcf072017-01-16 14:07:57 +00003274 return std::make_tuple(AliasGroups, HasWriteAccess);
3275}
3276
Tobias Grossere39f9122017-01-16 14:08:00 +00003277void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003278 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3279 AliasGroupTy NewAG;
3280 AliasGroupTy &AG = AliasGroups[u];
3281 AliasGroupTy::iterator AGI = AG.begin();
3282 isl_set *AGDomain = getAccessDomain(*AGI);
3283 while (AGI != AG.end()) {
3284 MemoryAccess *MA = *AGI;
3285 isl_set *MADomain = getAccessDomain(MA);
3286 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3287 NewAG.push_back(MA);
3288 AGI = AG.erase(AGI);
3289 isl_set_free(MADomain);
3290 } else {
3291 AGDomain = isl_set_union(AGDomain, MADomain);
3292 AGI++;
3293 }
3294 }
3295 if (NewAG.size() > 1)
3296 AliasGroups.push_back(std::move(NewAG));
3297 isl_set_free(AGDomain);
3298 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003299}
3300
3301bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3302 // To create sound alias checks we perform the following steps:
3303 // o) We partition each group into read only and non read only accesses.
3304 // o) For each group with more than one base pointer we then compute minimal
3305 // and maximal accesses to each array of a group in read only and non
3306 // read only partitions separately.
3307 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003308 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003309
3310 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3311
3312 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003313
Johannes Doerfert13771732014-10-01 12:40:46 +00003314 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003315 bool Valid = buildAliasGroup(AG, HasWriteAccess);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003316 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003317 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003318 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003319
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003320 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003321}
3322
Tobias Grosser77f32572017-01-16 15:49:07 +00003323bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003324 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003325 AliasGroupTy ReadOnlyAccesses;
3326 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003327 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003328 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003329
3330 auto &F = getFunction();
3331
3332 if (AliasGroup.size() < 2)
3333 return true;
3334
3335 for (MemoryAccess *Access : AliasGroup) {
3336 emitOptimizationRemarkAnalysis(
3337 F.getContext(), DEBUG_TYPE, F,
3338 Access->getAccessInstruction()->getDebugLoc(),
3339 "Possibly aliasing pointer, use restrict keyword.");
3340
Tobias Grosser889830b2017-02-09 23:12:22 +00003341 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3342 if (HasWriteAccess.count(Array)) {
3343 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003344 ReadWriteAccesses.push_back(Access);
3345 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003346 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003347 ReadOnlyAccesses.push_back(Access);
3348 }
3349 }
3350
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003351 // If there are no read-only pointers, and less than two read-write pointers,
3352 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003353 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003354 return true;
3355
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003356 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003357 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003358 return true;
3359
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003360 // For non-affine accesses, no alias check can be generated as we cannot
3361 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003362 for (MemoryAccess *MA : AliasGroup) {
3363 if (!MA->isAffine()) {
3364 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3365 return false;
3366 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003367 }
3368
3369 // Ensure that for all memory accesses for which we generate alias checks,
3370 // their base pointers are available.
3371 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003372 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3373 addRequiredInvariantLoad(
3374 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3375 }
3376
3377 MinMaxAliasGroups.emplace_back();
3378 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3379 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3380 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3381
3382 bool Valid;
3383
3384 Valid =
3385 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3386
3387 if (!Valid)
3388 return false;
3389
3390 // Bail out if the number of values we need to compare is too large.
3391 // This is important as the number of comparisons grows quadratically with
3392 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003393 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003394 RunTimeChecksMaxArraysPerGroup)
3395 return false;
3396
3397 Valid =
3398 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3399
3400 if (!Valid)
3401 return false;
3402
3403 return true;
3404}
3405
Tobias Grosserc80d6972016-09-02 06:33:33 +00003406/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003407static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003408 // Start with the smallest loop containing the entry and expand that
3409 // loop until it contains all blocks in the region. If there is a loop
3410 // containing all blocks in the region check if it is itself contained
3411 // and if so take the parent loop as it will be the smallest containing
3412 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003413 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003414 while (L) {
3415 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003416 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003417 AllContained &= L->contains(BB);
3418 if (AllContained)
3419 break;
3420 L = L->getParentLoop();
3421 }
3422
Johannes Doerfertef744432016-05-23 12:42:38 +00003423 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003424}
3425
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003426Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003427 ScopDetection::DetectionContext &DC)
Philip Pfaffe35bdcaf2017-05-15 13:43:01 +00003428 : SE(&ScalarEvolution), R(R), name(R.getNameStr()), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003429 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003430 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3431 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3432 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3433 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003434 if (IslOnErrorAbort)
3435 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003436 buildContext();
3437}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003438
Tobias Grosserbedef002016-12-02 08:10:56 +00003439void Scop::foldSizeConstantsToRight() {
3440 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3441
3442 for (auto Array : arrays()) {
3443 if (Array->getNumberOfDimensions() <= 1)
3444 continue;
3445
3446 isl_space *Space = Array->getSpace();
3447
3448 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3449
3450 if (!isl_union_set_contains(Accessed, Space)) {
3451 isl_space_free(Space);
3452 continue;
3453 }
3454
3455 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3456
3457 isl_map *Transform =
3458 isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3459
3460 std::vector<int> Int;
3461
3462 int Dims = isl_set_dim(Elements, isl_dim_set);
3463 for (int i = 0; i < Dims; i++) {
3464 isl_set *DimOnly =
3465 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3466 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3467 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3468
3469 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3470
3471 if (i == Dims - 1) {
3472 Int.push_back(1);
3473 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3474 isl_basic_set_free(DimHull);
3475 continue;
3476 }
3477
3478 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3479 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3480 isl_val *Val = isl_aff_get_denominator_val(Diff);
3481 isl_aff_free(Diff);
3482
3483 int ValInt = 1;
3484
3485 if (isl_val_is_int(Val))
3486 ValInt = isl_val_get_num_si(Val);
3487 isl_val_free(Val);
3488
3489 Int.push_back(ValInt);
3490
3491 isl_constraint *C = isl_constraint_alloc_equality(
3492 isl_local_space_from_space(isl_map_get_space(Transform)));
3493 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3494 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3495 Transform = isl_map_add_constraint(Transform, C);
3496 isl_basic_set_free(DimHull);
3497 continue;
3498 }
3499
3500 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3501 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3502
3503 int ValInt = 1;
3504 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3505 ValInt = 0;
3506 }
3507
3508 Int.push_back(ValInt);
3509 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3510 isl_basic_set_free(DimHull);
3511 isl_basic_set_free(ZeroSet);
3512 }
3513
3514 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3515
3516 if (!isl_set_is_subset(Elements, MappedElements)) {
3517 isl_set_free(Elements);
3518 isl_set_free(MappedElements);
3519 isl_map_free(Transform);
3520 continue;
3521 }
3522
3523 isl_set_free(MappedElements);
3524
3525 bool CanFold = true;
3526
3527 if (Int[0] <= 1)
3528 CanFold = false;
3529
3530 unsigned NumDims = Array->getNumberOfDimensions();
3531 for (unsigned i = 1; i < NumDims - 1; i++)
3532 if (Int[0] != Int[i] && Int[i])
3533 CanFold = false;
3534
3535 if (!CanFold) {
3536 isl_set_free(Elements);
3537 isl_map_free(Transform);
3538 continue;
3539 }
3540
Tobias Grosserbedef002016-12-02 08:10:56 +00003541 for (auto &Access : AccessFunctions)
3542 if (Access->getScopArrayInfo() == Array)
3543 Access->setAccessRelation(isl_map_apply_range(
3544 Access->getAccessRelation(), isl_map_copy(Transform)));
3545
3546 isl_map_free(Transform);
3547
3548 std::vector<const SCEV *> Sizes;
3549 for (unsigned i = 0; i < NumDims; i++) {
3550 auto Size = Array->getDimensionSize(i);
3551
3552 if (i == NumDims - 1)
3553 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3554 Sizes.push_back(Size);
3555 }
3556
3557 Array->updateSizes(Sizes, false /* CheckConsistency */);
3558
3559 isl_set_free(Elements);
3560 }
3561 isl_union_set_free(Accessed);
3562 return;
3563}
3564
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003565void Scop::markFortranArrays() {
3566 for (ScopStmt &Stmt : Stmts) {
3567 for (MemoryAccess *MemAcc : Stmt) {
3568 Value *FAD = MemAcc->getFortranArrayDescriptor();
3569 if (!FAD)
3570 continue;
3571
3572 // TODO: const_cast-ing to edit
3573 ScopArrayInfo *SAI =
3574 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3575 assert(SAI && "memory access into a Fortran array does not "
3576 "have an associated ScopArrayInfo");
3577 SAI->applyAndSetFAD(FAD);
3578 }
3579 }
3580}
3581
Tobias Grosser491b7992016-12-02 05:21:22 +00003582void Scop::finalizeAccesses() {
3583 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003584 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003585 foldAccessRelations();
3586 assumeNoOutOfBounds();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003587 markFortranArrays();
Tobias Grosser491b7992016-12-02 05:21:22 +00003588}
3589
Tobias Grosser75805372011-04-29 06:27:02 +00003590Scop::~Scop() {
3591 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003592 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003593 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003594 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003595
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003596 for (auto &It : ParameterIds)
3597 isl_id_free(It.second);
3598
Johannes Doerfert96425c22015-08-30 21:13:53 +00003599 for (auto It : DomainMap)
3600 isl_set_free(It.second);
3601
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003602 for (auto &AS : RecordedAssumptions)
3603 isl_set_free(AS.Set);
3604
Johannes Doerfertb164c792014-09-18 11:17:17 +00003605 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003606 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003607 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003608 isl_pw_multi_aff_free(MMA.first);
3609 isl_pw_multi_aff_free(MMA.second);
3610 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003611 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003612 isl_pw_multi_aff_free(MMA.first);
3613 isl_pw_multi_aff_free(MMA.second);
3614 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003615 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003616
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003617 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003618 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003619
3620 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003621 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003622 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003623 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003624 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003625 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003626 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003627}
3628
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003629void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003630 // Check all array accesses for each base pointer and find a (virtual) element
3631 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003632 for (ScopStmt &Stmt : *this)
3633 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003634 if (!Access->isArrayKind())
3635 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003636 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003637 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3638
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003639 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003640 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003641 unsigned DivisibleSize = Array->getElemSizeInBytes();
3642 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003643 while (!isDivisible(Subscript, DivisibleSize, *SE))
3644 DivisibleSize /= 2;
3645 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003646 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003647 }
3648
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003649 for (auto &Stmt : *this)
3650 for (auto &Access : Stmt)
3651 Access->updateDimensionality();
3652}
3653
Tobias Grosser491b7992016-12-02 05:21:22 +00003654void Scop::foldAccessRelations() {
3655 for (auto &Stmt : *this)
3656 for (auto &Access : Stmt)
3657 Access->foldAccessRelation();
3658}
3659
3660void Scop::assumeNoOutOfBounds() {
3661 for (auto &Stmt : *this)
3662 for (auto &Access : Stmt)
3663 Access->assumeNoOutOfBound();
3664}
3665
Michael Kruse977d38b2016-07-22 17:31:17 +00003666void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003667 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3668 ScopStmt &Stmt = *StmtIt;
3669
Johannes Doerfert26404542016-05-10 12:19:47 +00003670 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003671 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003672 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003673
Johannes Doerferteca9e892015-11-03 16:54:49 +00003674 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003675 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003676 bool OnlyRead = true;
3677 for (MemoryAccess *MA : Stmt) {
3678 if (MA->isRead())
3679 continue;
3680
3681 OnlyRead = false;
3682 break;
3683 }
3684
3685 RemoveStmt = OnlyRead;
3686 }
3687
Johannes Doerfert26404542016-05-10 12:19:47 +00003688 if (!RemoveStmt) {
3689 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003690 continue;
3691 }
3692
Johannes Doerfert26404542016-05-10 12:19:47 +00003693 // Remove the statement because it is unnecessary.
3694 if (Stmt.isRegionStmt())
3695 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3696 StmtMap.erase(BB);
3697 else
3698 StmtMap.erase(Stmt.getBasicBlock());
3699
3700 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003701 }
3702}
3703
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003704InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003705 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3706 if (!LInst)
3707 return nullptr;
3708
3709 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3710 LInst = cast<LoadInst>(Rep);
3711
Johannes Doerfert96e54712016-02-07 17:30:13 +00003712 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003713 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003714 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003715 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003716 continue;
3717
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003718 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003719 for (auto *MA : MAs)
3720 if (MA->getAccessInstruction() == Val)
3721 return &IAClass;
3722 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003723
3724 return nullptr;
3725}
3726
Tobias Grosserc80d6972016-09-02 06:33:33 +00003727/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003728static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003729 bool MAInvalidCtxIsEmpty,
3730 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003731 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3732 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3733 // TODO: We can provide more information for better but more expensive
3734 // results.
3735 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3736 LInst->getAlignment(), DL))
3737 return false;
3738
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003739 // If the location might be overwritten we do not hoist it unconditionally.
3740 //
3741 // TODO: This is probably to conservative.
3742 if (!NonHoistableCtxIsEmpty)
3743 return false;
3744
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003745 // If a dereferencable load is in a statement that is modeled precisely we can
3746 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003747 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003748 return true;
3749
3750 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003751 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003752 // statement domain.
3753 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3754 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3755 return false;
3756 return true;
3757}
3758
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003759void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003760
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003761 if (InvMAs.empty())
3762 return;
3763
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003764 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003765 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003766
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003767 // Get the context under which the statement is executed but remove the error
3768 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003769 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003770 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003771
Tobias Grosser90411a92017-02-16 19:11:33 +00003772 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003773 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003774 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3775 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003776 for (auto &InvMA : InvMAs)
3777 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003778 return;
3779 }
3780
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003781 // Project out all parameters that relate to loads in the statement. Otherwise
3782 // we could have cyclic dependences on the constraints under which the
3783 // hoisted loads are executed and we could not determine an order in which to
3784 // pre-load them. This happens because not only lower bounds are part of the
3785 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003786 for (auto &InvMA : InvMAs) {
3787 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003788 Instruction *AccInst = MA->getAccessInstruction();
3789 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003790 SetVector<Value *> Values;
3791 for (const SCEV *Parameter : Parameters) {
3792 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003793 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003794 if (!Values.count(AccInst))
3795 continue;
3796
3797 if (isl_id *ParamId = getIdForParam(Parameter)) {
3798 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003799 if (Dim >= 0)
3800 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003801 isl_id_free(ParamId);
3802 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003803 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003804 }
3805 }
3806
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003807 for (auto &InvMA : InvMAs) {
3808 auto *MA = InvMA.MA;
3809 auto *NHCtx = InvMA.NonHoistableCtx;
3810
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003811 // Check for another invariant access that accesses the same location as
3812 // MA and if found consolidate them. Otherwise create a new equivalence
3813 // class at the end of InvariantEquivClasses.
3814 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003815 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003816 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3817
Johannes Doerfert85676e32016-04-23 14:32:34 +00003818 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003819 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003820 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3821
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003822 isl_set *MACtx;
3823 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003824 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3825 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003826 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003827 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003828 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003829 } else {
3830 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003831 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003832 MACtx = isl_set_gist_params(MACtx, getContext());
3833 }
3834
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003835 bool Consolidated = false;
3836 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003837 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003838 continue;
3839
Johannes Doerfertdf880232016-03-03 12:26:58 +00003840 // If the pointer and the type is equal check if the access function wrt.
3841 // to the domain is equal too. It can happen that the domain fixes
3842 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003843 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003844 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003845 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003846 if (!MAs.empty()) {
3847 auto *LastMA = MAs.front();
3848
3849 auto *AR = isl_map_range(MA->getAccessRelation());
3850 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3851 bool SameAR = isl_set_is_equal(AR, LastAR);
3852 isl_set_free(AR);
3853 isl_set_free(LastAR);
3854
3855 if (!SameAR)
3856 continue;
3857 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003858
3859 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003860 MAs.push_front(MA);
3861
Johannes Doerfertdf880232016-03-03 12:26:58 +00003862 Consolidated = true;
3863
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003864 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003865 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003866 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003867 IAClassDomainCtx =
3868 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003869 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003870 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003871 break;
3872 }
3873
3874 if (Consolidated)
3875 continue;
3876
3877 // If we did not consolidate MA, thus did not find an equivalence class
3878 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003879 InvariantEquivClasses.emplace_back(
3880 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003881 }
3882
3883 isl_set_free(DomainCtx);
3884}
3885
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003886__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3887 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003888 // TODO: Loads that are not loop carried, hence are in a statement with
3889 // zero iterators, are by construction invariant, though we
3890 // currently "hoist" them anyway. This is necessary because we allow
3891 // them to be treated as parameters (e.g., in conditions) and our code
3892 // generation would otherwise use the old value.
3893
3894 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003895 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003896
Johannes Doerfertc9765462016-11-17 22:11:56 +00003897 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3898 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003899 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003900
3901 // Skip accesses that have an invariant base pointer which is defined but
3902 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3903 // returns a pointer that is used as a base address. However, as we want
3904 // to hoist indirect pointers, we allow the base pointer to be defined in
3905 // the region if it is also a memory access. Each ScopArrayInfo object
3906 // that has a base pointer origin has a base pointer that is loaded and
3907 // that it is invariant, thus it will be hoisted too. However, if there is
3908 // no base pointer origin we check that the base pointer is defined
3909 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003910 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003911 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003912 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003913
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003914 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003915 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003916
3917 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3918 Stmt.getNumIterators())) {
3919 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003920 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003921 }
3922
3923 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003924 isl_set *SafeToLoad;
3925
3926 auto &DL = getFunction().getParent()->getDataLayout();
3927 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
3928 DL)) {
3929 SafeToLoad =
3930 isl_set_universe(isl_space_range(isl_map_get_space(AccessRelation)));
3931 isl_map_free(AccessRelation);
3932 } else if (BB != LI->getParent()) {
3933 // Skip accesses in non-affine subregions as they might not be executed
3934 // under the same condition as the entry of the non-affine subregion.
3935 isl_map_free(AccessRelation);
3936 return nullptr;
3937 } else {
3938 SafeToLoad = isl_map_range(AccessRelation);
3939 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003940
3941 isl_union_map *Written = isl_union_map_intersect_range(
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003942 isl_union_map_copy(Writes), isl_union_set_from_set(SafeToLoad));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003943 auto *WrittenCtx = isl_union_map_params(Written);
3944 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003945
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003946 if (!IsWritten)
3947 return WrittenCtx;
3948
3949 WrittenCtx = isl_set_remove_divs(WrittenCtx);
Tobias Grosser90411a92017-02-16 19:11:33 +00003950 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctsInDomain;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003951 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3952 isl_set_free(WrittenCtx);
3953 return nullptr;
3954 }
3955
3956 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3957 AS_RESTRICTION);
3958 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003959}
3960
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003961void Scop::verifyInvariantLoads() {
3962 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003963 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003964 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003965 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003966 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003967 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3968 return;
3969 }
3970 }
3971}
3972
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003973void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003974 if (!PollyInvariantLoadHoisting)
3975 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003976
Tobias Grosser0865e7752016-02-29 07:29:42 +00003977 isl_union_map *Writes = getWrites();
3978 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003979 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003980
Tobias Grosser0865e7752016-02-29 07:29:42 +00003981 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003982 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3983 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003984
3985 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003986 for (auto InvMA : InvariantAccesses)
3987 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003988 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003989 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003990 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003991}
3992
Tobias Grosserf3adab42017-05-10 10:59:58 +00003993/// Find the canonical scop array info object for a set of invariant load
3994/// hoisted loads. The canonical array is the one that corresponds to the
3995/// first load in the list of accesses which is used as base pointer of a
3996/// scop array.
3997static const ScopArrayInfo *findCanonicalArray(Scop *S,
3998 MemoryAccessList &Accesses) {
3999 for (MemoryAccess *Access : Accesses) {
4000 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
4001 Access->getAccessInstruction(), MemoryKind::Array);
4002 if (CanonicalArray)
4003 return CanonicalArray;
4004 }
4005 return nullptr;
4006}
4007
4008/// Check if @p Array severs as base array in an invariant load.
4009static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
4010 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
4011 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
4012 if (Access2->getScopArrayInfo() == Array)
4013 return true;
4014 return false;
4015}
4016
4017/// Replace the base pointer arrays in all memory accesses referencing @p Old,
4018/// with a reference to @p New.
4019static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
4020 const ScopArrayInfo *New) {
4021 for (ScopStmt &Stmt : *S)
4022 for (MemoryAccess *Access : Stmt) {
4023 if (Access->getLatestScopArrayInfo() != Old)
4024 continue;
4025
4026 isl_id *Id = New->getBasePtrId();
4027 isl_map *Map = Access->getAccessRelation();
4028 Map = isl_map_set_tuple_id(Map, isl_dim_out, Id);
4029 Access->setAccessRelation(Map);
4030 }
4031}
4032
4033void Scop::canonicalizeDynamicBasePtrs() {
4034 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
4035 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
4036
4037 const ScopArrayInfo *CanonicalBasePtrSAI =
4038 findCanonicalArray(this, BasePtrAccesses);
4039
4040 if (!CanonicalBasePtrSAI)
4041 continue;
4042
4043 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
4044 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
4045 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
4046 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
4047 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
4048 continue;
4049
4050 // we currently do not canonicalize arrays where some accesses are
4051 // hoisted as invariant loads. If we would, we need to update the access
4052 // function of the invariant loads as well. However, as this is not a
4053 // very common situation, we leave this for now to avoid further
4054 // complexity increases.
4055 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
4056 continue;
4057
4058 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
4059 }
4060 }
4061}
4062
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004063const ScopArrayInfo *
4064Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
4065 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
4066 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004067 assert((BasePtr || BaseName) &&
4068 "BasePtr and BaseName can not be nullptr at the same time.");
4069 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
4070 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
4071 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004072 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004073 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00004074 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00004075 DL, this, BaseName));
4076 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004077 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004078 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00004079 // In case of mismatching array sizes, we bail out by setting the run-time
4080 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004081 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004082 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004083 }
Tobias Grosserab671442015-05-23 05:58:27 +00004084 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004085}
4086
Roman Gareevd7754a12016-07-30 09:25:51 +00004087const ScopArrayInfo *
4088Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
4089 const std::vector<unsigned> &Sizes) {
4090 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
4091 std::vector<const SCEV *> SCEVSizes;
4092
4093 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00004094 if (size)
4095 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
4096 else
4097 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00004098
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004099 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
4100 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00004101 return SAI;
4102}
4103
Tobias Grosserf3adab42017-05-10 10:59:58 +00004104const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
4105 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00004106 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004107 return SAI;
4108}
4109
4110const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
4111 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004112 assert(SAI && "No ScopArrayInfo available for this base pointer");
4113 return SAI;
4114}
4115
Tobias Grosser74394f02013-01-14 22:40:23 +00004116std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004117
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004118std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004119 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004120 return stringFromIslObj(AssumedContext);
4121}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004122
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004123std::string Scop::getInvalidContextStr() const {
4124 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004125}
Tobias Grosser75805372011-04-29 06:27:02 +00004126
4127std::string Scop::getNameStr() const {
4128 std::string ExitName, EntryName;
4129 raw_string_ostream ExitStr(ExitName);
4130 raw_string_ostream EntryStr(EntryName);
4131
Tobias Grosserf240b482014-01-09 10:42:15 +00004132 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004133 EntryStr.str();
4134
4135 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00004136 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004137 ExitStr.str();
4138 } else
4139 ExitName = "FunctionExit";
4140
4141 return EntryName + "---" + ExitName;
4142}
4143
Tobias Grosser74394f02013-01-14 22:40:23 +00004144__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00004145__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00004146 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00004147}
4148
Tobias Grossere86109f2013-10-29 21:05:49 +00004149__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004150 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00004151 return isl_set_copy(AssumedContext);
4152}
4153
Michael Krusef3091bf2017-03-17 13:09:52 +00004154bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004155 if (PollyProcessUnprofitable)
4156 return true;
4157
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004158 if (isEmpty())
4159 return false;
4160
4161 unsigned OptimizableStmtsOrLoops = 0;
4162 for (auto &Stmt : *this) {
4163 if (Stmt.getNumIterators() == 0)
4164 continue;
4165
4166 bool ContainsArrayAccs = false;
4167 bool ContainsScalarAccs = false;
4168 for (auto *MA : Stmt) {
4169 if (MA->isRead())
4170 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004171 ContainsArrayAccs |= MA->isLatestArrayKind();
4172 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004173 }
4174
Michael Krusef3091bf2017-03-17 13:09:52 +00004175 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004176 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4177 }
4178
4179 return OptimizableStmtsOrLoops > 1;
4180}
4181
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004182bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004183 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004184 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00004185 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4186 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4187 isl_set_is_subset(PositiveContext, NegativeContext));
4188 isl_set_free(PositiveContext);
4189 if (!IsFeasible) {
4190 isl_set_free(NegativeContext);
4191 return false;
4192 }
4193
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004194 auto *DomainContext = isl_union_set_params(getDomains());
4195 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00004196 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004197 isl_set_free(NegativeContext);
4198 isl_set_free(DomainContext);
4199
Johannes Doerfert43788c52015-08-20 05:58:56 +00004200 return IsFeasible;
4201}
4202
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004203static std::string toString(AssumptionKind Kind) {
4204 switch (Kind) {
4205 case ALIASING:
4206 return "No-aliasing";
4207 case INBOUNDS:
4208 return "Inbounds";
4209 case WRAPPING:
4210 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004211 case UNSIGNED:
4212 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004213 case COMPLEXITY:
4214 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004215 case PROFITABLE:
4216 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004217 case ERRORBLOCK:
4218 return "No-error";
4219 case INFINITELOOP:
4220 return "Finite loop";
4221 case INVARIANTLOAD:
4222 return "Invariant load";
4223 case DELINEARIZATION:
4224 return "Delinearization";
4225 }
4226 llvm_unreachable("Unknown AssumptionKind!");
4227}
4228
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004229bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4230 if (Sign == AS_ASSUMPTION) {
4231 if (isl_set_is_subset(Context, Set))
4232 return false;
4233
4234 if (isl_set_is_subset(AssumedContext, Set))
4235 return false;
4236 } else {
4237 if (isl_set_is_disjoint(Set, Context))
4238 return false;
4239
4240 if (isl_set_is_subset(Set, InvalidContext))
4241 return false;
4242 }
4243 return true;
4244}
4245
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004246bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
4247 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004248 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4249 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004250
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004251 // Do never emit trivial assumptions as they only clutter the output.
4252 if (!PollyRemarksMinimal) {
4253 isl_set *Univ = nullptr;
4254 if (Sign == AS_ASSUMPTION)
4255 Univ = isl_set_universe(isl_set_get_space(Set));
4256
4257 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4258 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4259 isl_set_free(Univ);
4260
4261 if (IsTrivial)
4262 return false;
4263 }
4264
Johannes Doerfertcd195322016-11-17 21:41:08 +00004265 switch (Kind) {
4266 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004267 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004268 break;
4269 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004270 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004271 break;
4272 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004273 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004274 break;
4275 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004276 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004277 break;
4278 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004279 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004280 break;
4281 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004282 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004283 break;
4284 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004285 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004286 break;
4287 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004288 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004289 break;
4290 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004291 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004292 break;
4293 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004294 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004295 break;
4296 }
4297
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004298 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004299 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4300 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004301 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004302 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004303}
4304
4305void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004306 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004307 // Simplify the assumptions/restrictions first.
4308 Set = isl_set_gist_params(Set, getContext());
4309
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004310 if (!trackAssumption(Kind, Set, Loc, Sign)) {
4311 isl_set_free(Set);
4312 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004313 }
4314
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004315 if (Sign == AS_ASSUMPTION) {
4316 AssumedContext = isl_set_intersect(AssumedContext, Set);
4317 AssumedContext = isl_set_coalesce(AssumedContext);
4318 } else {
4319 InvalidContext = isl_set_union(InvalidContext, Set);
4320 InvalidContext = isl_set_coalesce(InvalidContext);
4321 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004322}
4323
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004324void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004325 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004326 assert((isl_set_is_params(Set) || BB) &&
4327 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004328 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004329}
4330
4331void Scop::addRecordedAssumptions() {
4332 while (!RecordedAssumptions.empty()) {
4333 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004334
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004335 if (!AS.BB) {
4336 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
4337 continue;
4338 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004339
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004340 // If the domain was deleted the assumptions are void.
4341 isl_set *Dom = getDomainConditions(AS.BB);
4342 if (!Dom) {
4343 isl_set_free(AS.Set);
4344 continue;
4345 }
4346
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004347 // If a basic block was given use its domain to simplify the assumption.
4348 // In case of restrictions we know they only have to hold on the domain,
4349 // thus we can intersect them with the domain of the block. However, for
4350 // assumptions the domain has to imply them, thus:
4351 // _ _____
4352 // Dom => S <==> A v B <==> A - B
4353 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004354 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004355 // assumption.
4356 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004357 if (AS.Sign == AS_RESTRICTION)
4358 S = isl_set_params(isl_set_intersect(S, Dom));
4359 else /* (AS.Sign == AS_ASSUMPTION) */
4360 S = isl_set_params(isl_set_subtract(Dom, S));
4361
4362 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004363 }
4364}
4365
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004366void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004367 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004368}
4369
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004370__isl_give isl_set *Scop::getInvalidContext() const {
4371 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004372}
4373
Tobias Grosser75805372011-04-29 06:27:02 +00004374void Scop::printContext(raw_ostream &OS) const {
4375 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004376 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004377
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004378 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004379 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004380
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004381 OS.indent(4) << "Invalid Context:\n";
4382 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004383
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004384 unsigned Dim = 0;
4385 for (const SCEV *Parameter : Parameters)
4386 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004387}
4388
Johannes Doerfertb164c792014-09-18 11:17:17 +00004389void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004390 int noOfGroups = 0;
4391 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004392 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004393 noOfGroups += 1;
4394 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004395 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004396 }
4397
Tobias Grosserbb853c22015-07-25 12:31:03 +00004398 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004399 if (MinMaxAliasGroups.empty()) {
4400 OS.indent(8) << "n/a\n";
4401 return;
4402 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004403
Tobias Grosserbb853c22015-07-25 12:31:03 +00004404 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004405
4406 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004407 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004408 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004409 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004410 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4411 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004412 }
4413 OS << " ]]\n";
4414 }
4415
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004416 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004417 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004418 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004419 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004420 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4421 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004422 }
4423 OS << " ]]\n";
4424 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004425 }
4426}
4427
Tobias Grosser75805372011-04-29 06:27:02 +00004428void Scop::printStatements(raw_ostream &OS) const {
4429 OS << "Statements {\n";
4430
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004431 for (const ScopStmt &Stmt : *this)
4432 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00004433
4434 OS.indent(4) << "}\n";
4435}
4436
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004437void Scop::printArrayInfo(raw_ostream &OS) const {
4438 OS << "Arrays {\n";
4439
Tobias Grosserab671442015-05-23 05:58:27 +00004440 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004441 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004442
4443 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004444
4445 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4446
4447 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004448 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004449
4450 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004451}
4452
Tobias Grosser75805372011-04-29 06:27:02 +00004453void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004454 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004455 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004456 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004457 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004458 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004459 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004460 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004461 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004462 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004463 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004464 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4465 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004466 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004467 }
4468 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004469 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004470 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004471 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00004472 printStatements(OS.indent(4));
4473}
4474
4475void Scop::dump() const { print(dbgs()); }
4476
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004477isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004478
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004479__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4480 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004481 // First try to use the SCEVAffinator to generate a piecewise defined
4482 // affine function from @p E in the context of @p BB. If that tasks becomes to
4483 // complex the affinator might return a nullptr. In such a case we invalidate
4484 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004485 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004486 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004487 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004488 // TODO: We could use a heuristic and either use:
4489 // SCEVAffinator::takeNonNegativeAssumption
4490 // or
4491 // SCEVAffinator::interpretAsUnsigned
4492 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004493 if (NonNegative)
4494 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004495 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004496 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004497
4498 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
4499 invalidate(COMPLEXITY, DL);
4500 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004501}
4502
Tobias Grosser808cd692015-07-14 09:33:13 +00004503__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004504 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4505 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004506
Tobias Grosser808cd692015-07-14 09:33:13 +00004507 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004508 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004509
4510 return Domain;
4511}
4512
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004513__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4514 PWACtx PWAC = getPwAff(E, BB);
4515 isl_set_free(PWAC.second);
4516 return PWAC.first;
4517}
4518
Tobias Grossere5a35142015-11-12 14:07:09 +00004519__isl_give isl_union_map *
4520Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4521 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004522
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004523 for (ScopStmt &Stmt : *this) {
4524 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004525 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004526 continue;
4527
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004528 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004529 isl_map *AccessDomain = MA->getAccessRelation();
4530 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004531 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004532 }
4533 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004534 return isl_union_map_coalesce(Accesses);
4535}
4536
4537__isl_give isl_union_map *Scop::getMustWrites() {
4538 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004539}
4540
4541__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004542 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004543}
4544
Tobias Grosser37eb4222014-02-20 21:43:54 +00004545__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004546 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004547}
4548
4549__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004550 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004551}
4552
Tobias Grosser2ac23382015-11-12 14:07:13 +00004553__isl_give isl_union_map *Scop::getAccesses() {
4554 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4555}
4556
Roman Gareevb3224ad2016-09-14 06:26:09 +00004557// Check whether @p Node is an extension node.
4558//
4559// @return true if @p Node is an extension node.
4560isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4561 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4562 return isl_bool_error;
4563 else
4564 return isl_bool_true;
4565}
4566
4567bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4568 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4569 nullptr) == isl_stat_error;
4570}
4571
Tobias Grosser808cd692015-07-14 09:33:13 +00004572__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004573 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004574 if (containsExtensionNode(Tree)) {
4575 isl_schedule_free(Tree);
4576 return nullptr;
4577 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004578 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004579 isl_schedule_free(Tree);
4580 return S;
4581}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004582
Tobias Grosser808cd692015-07-14 09:33:13 +00004583__isl_give isl_schedule *Scop::getScheduleTree() const {
4584 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4585 getDomains());
4586}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004587
Tobias Grosser808cd692015-07-14 09:33:13 +00004588void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4589 auto *S = isl_schedule_from_domain(getDomains());
4590 S = isl_schedule_insert_partial_schedule(
4591 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4592 isl_schedule_free(Schedule);
4593 Schedule = S;
4594}
4595
4596void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4597 isl_schedule_free(Schedule);
4598 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004599}
4600
4601bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4602 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004603 for (ScopStmt &Stmt : *this) {
4604 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004605 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4606 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4607
4608 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4609 isl_union_set_free(StmtDomain);
4610 isl_union_set_free(NewStmtDomain);
4611 continue;
4612 }
4613
4614 Changed = true;
4615
4616 isl_union_set_free(StmtDomain);
4617 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4618
4619 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004620 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004621 isl_union_set_free(NewStmtDomain);
4622 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004623 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004624 }
4625 isl_union_set_free(Domain);
4626 return Changed;
4627}
4628
Tobias Grosser75805372011-04-29 06:27:02 +00004629ScalarEvolution *Scop::getSE() const { return SE; }
4630
Tobias Grosserc80d6972016-09-02 06:33:33 +00004631// Create an isl_multi_union_aff that defines an identity mapping from the
4632// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004633//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004634// # Example:
4635//
4636// Domain: { A[i,j]; B[i,j,k] }
4637// N: 1
4638//
4639// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4640//
4641// @param USet A union set describing the elements for which to generate a
4642// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004643// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004644// @returns A mapping from USet to its N-th dimension.
Tobias Grosser99320862017-05-26 17:22:03 +00004645static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) {
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004646 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004647 assert(USet);
Siddharth Bhat8bb436e2017-05-29 11:34:29 +00004648 assert(!USet.is_empty());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004649
Tobias Grosser99320862017-05-26 17:22:03 +00004650 auto Result = isl::union_pw_multi_aff::empty(USet.get_space());
Tobias Grosser808cd692015-07-14 09:33:13 +00004651
Tobias Grosser99320862017-05-26 17:22:03 +00004652 auto Lambda = [&Result, N](isl::set S) -> isl::stat {
4653 int Dim = S.dim(isl::dim::set);
4654 auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set,
4655 N, Dim - N);
4656 if (N > 1)
4657 PMA = PMA.drop_dims(isl::dim::out, 0, N - 1);
Tobias Grosser808cd692015-07-14 09:33:13 +00004658
Tobias Grosser99320862017-05-26 17:22:03 +00004659 Result = Result.add_pw_multi_aff(PMA);
4660 return isl::stat::ok;
4661 };
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004662
Tobias Grosser99320862017-05-26 17:22:03 +00004663 isl::stat Res = USet.foreach_set(Lambda);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004664 (void)Res;
4665
Tobias Grosser99320862017-05-26 17:22:03 +00004666 assert(Res == isl::stat::ok);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004667
Tobias Grosser99320862017-05-26 17:22:03 +00004668 return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result));
Tobias Grosser808cd692015-07-14 09:33:13 +00004669}
4670
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004671void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop,
4672 std::vector<Instruction *> Instructions) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004673 assert(BB && "Unexpected nullptr!");
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004674 Stmts.emplace_back(*this, *BB, SurroundingLoop, Instructions);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004675 auto *Stmt = &Stmts.back();
4676 StmtMap[BB] = Stmt;
4677}
4678
Michael Kruse55454072017-03-15 22:16:43 +00004679void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004680 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004681 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004682 auto *Stmt = &Stmts.back();
4683 for (BasicBlock *BB : R->blocks())
Tobias Grosser808cd692015-07-14 09:33:13 +00004684 StmtMap[BB] = Stmt;
Tobias Grosser808cd692015-07-14 09:33:13 +00004685}
4686
Roman Gareevb3224ad2016-09-14 06:26:09 +00004687ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4688 __isl_take isl_map *TargetRel,
4689 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004690#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004691 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4692 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4693 assert(isl_set_is_subset(Domain, TargetDomain) &&
4694 "Target access not defined for complete statement domain");
4695 assert(isl_set_is_subset(Domain, SourceDomain) &&
4696 "Source access not defined for complete statement domain");
4697 isl_set_free(SourceDomain);
4698 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004699#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004700 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4701 CopyStmtsNum++;
4702 return &(Stmts.back());
4703}
4704
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004705void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004706 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004707 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004708 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004709 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4710 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004711}
4712
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004713/// To generate a schedule for the elements in a Region we traverse the Region
4714/// in reverse-post-order and add the contained RegionNodes in traversal order
4715/// to the schedule of the loop that is currently at the top of the LoopStack.
4716/// For loop-free codes, this results in a correct sequential ordering.
4717///
4718/// Example:
4719/// bb1(0)
4720/// / \.
4721/// bb2(1) bb3(2)
4722/// \ / \.
4723/// bb4(3) bb5(4)
4724/// \ /
4725/// bb6(5)
4726///
4727/// Including loops requires additional processing. Whenever a loop header is
4728/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4729/// from an empty schedule, we first process all RegionNodes that are within
4730/// this loop and complete the sequential schedule at this loop-level before
4731/// processing about any other nodes. To implement this
4732/// loop-nodes-first-processing, the reverse post-order traversal is
4733/// insufficient. Hence, we additionally check if the traversal yields
4734/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4735/// These region-nodes are then queue and only traverse after the all nodes
4736/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004737void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004738 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004739
4740 ReversePostOrderTraversal<Region *> RTraversal(R);
4741 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4742 std::deque<RegionNode *> DelayList;
4743 bool LastRNWaiting = false;
4744
4745 // Iterate over the region @p R in reverse post-order but queue
4746 // sub-regions/blocks iff they are not part of the last encountered but not
4747 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4748 // that we queued the last sub-region/block from the reverse post-order
4749 // iterator. If it is set we have to explore the next sub-region/block from
4750 // the iterator (if any) to guarantee progress. If it is not set we first try
4751 // the next queued sub-region/blocks.
4752 while (!WorkList.empty() || !DelayList.empty()) {
4753 RegionNode *RN;
4754
4755 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4756 RN = WorkList.front();
4757 WorkList.pop_front();
4758 LastRNWaiting = false;
4759 } else {
4760 RN = DelayList.front();
4761 DelayList.pop_front();
4762 }
4763
4764 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004765 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004766 L = OuterScopLoop;
4767
Tobias Grosser151ae322016-04-03 19:36:52 +00004768 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004769 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004770 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004771 LastRNWaiting = true;
4772 DelayList.push_back(RN);
4773 continue;
4774 }
4775 LoopStack.push_back({L, nullptr, 0});
4776 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004777 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004778 }
4779
4780 return;
4781}
4782
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004783void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004784
Tobias Grosser8362c262016-01-06 15:30:06 +00004785 if (RN->isSubRegion()) {
4786 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004787 if (!isNonAffineSubRegion(LocalRegion)) {
4788 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004789 return;
4790 }
4791 }
Michael Kruse046dde42015-08-10 13:01:57 +00004792
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004793 auto &LoopData = LoopStack.back();
4794 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004795
Michael Kruse6f7721f2016-02-24 22:08:19 +00004796 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004797 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4798 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004799 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004800 }
4801
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004802 // Check if we just processed the last node in this loop. If we did, finalize
4803 // the loop by:
4804 //
4805 // - adding new schedule dimensions
4806 // - folding the resulting schedule into the parent loop schedule
4807 // - dropping the loop schedule from the LoopStack.
4808 //
4809 // Then continue to check surrounding loops, which might also have been
4810 // completed by this node.
4811 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00004812 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004813 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004814 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004815
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004816 LoopStack.pop_back();
4817 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004818
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004819 if (Schedule) {
Tobias Grosser99320862017-05-26 17:22:03 +00004820 isl::union_set Domain = give(isl_schedule_get_domain(Schedule));
4821 isl::multi_union_pw_aff MUPA = mapToDimension(Domain, LoopStack.size());
4822 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA.release());
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004823 NextLoopData.Schedule =
4824 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004825 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004826
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004827 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4828 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004829 }
Tobias Grosser75805372011-04-29 06:27:02 +00004830}
4831
Michael Kruse6f7721f2016-02-24 22:08:19 +00004832ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004833 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004834 if (StmtMapIt == StmtMap.end())
4835 return nullptr;
4836 return StmtMapIt->second;
4837}
4838
Michael Kruse6f7721f2016-02-24 22:08:19 +00004839ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4840 if (RN->isSubRegion())
4841 return getStmtFor(RN->getNodeAs<Region>());
4842 return getStmtFor(RN->getNodeAs<BasicBlock>());
4843}
4844
4845ScopStmt *Scop::getStmtFor(Region *R) const {
4846 ScopStmt *Stmt = getStmtFor(R->getEntry());
4847 assert(!Stmt || Stmt->getRegion() == R);
4848 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004849}
4850
Johannes Doerfert96425c22015-08-30 21:13:53 +00004851int Scop::getRelativeLoopDepth(const Loop *L) const {
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00004852 if (!L || !R.contains(L))
Johannes Doerfert96425c22015-08-30 21:13:53 +00004853 return -1;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00004854 // outermostLoopInRegion always returns nullptr for top level regions
4855 if (R.isTopLevelRegion()) {
4856 // LoopInfo's depths start at 1, we start at 0
4857 return L->getLoopDepth() - 1;
4858 } else {
4859 Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
4860 assert(OuterLoop);
4861 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4862 }
Johannes Doerfertd020b772015-08-27 06:53:52 +00004863}
4864
Roman Gareevd7754a12016-07-30 09:25:51 +00004865ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4866 for (auto &SAI : arrays()) {
4867 if (SAI->getName() == BaseName)
4868 return SAI;
4869 }
4870 return nullptr;
4871}
4872
Johannes Doerfert99191c72016-05-31 09:41:04 +00004873//===----------------------------------------------------------------------===//
4874void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4875 AU.addRequired<LoopInfoWrapperPass>();
4876 AU.addRequired<RegionInfoPass>();
4877 AU.addRequired<DominatorTreeWrapperPass>();
4878 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004879 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004880 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004881 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004882 AU.setPreservesAll();
4883}
4884
Tobias Grossercd01a362017-02-17 08:12:36 +00004885void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
4886 NumLoopsInScop += Stats.NumLoops;
4887 MaxNumLoopsInScop =
4888 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
4889
Tobias Grossercd01a362017-02-17 08:12:36 +00004890 if (Stats.MaxDepth == 1)
4891 NumScopsDepthOne++;
4892 else if (Stats.MaxDepth == 2)
4893 NumScopsDepthTwo++;
4894 else if (Stats.MaxDepth == 3)
4895 NumScopsDepthThree++;
4896 else if (Stats.MaxDepth == 4)
4897 NumScopsDepthFour++;
4898 else if (Stats.MaxDepth == 5)
4899 NumScopsDepthFive++;
4900 else
4901 NumScopsDepthLarger++;
4902}
4903
Johannes Doerfert99191c72016-05-31 09:41:04 +00004904bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004905 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004906
4907 if (!SD.isMaxRegionInScop(*R))
4908 return false;
4909
4910 Function *F = R->getEntry()->getParent();
4911 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4912 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4913 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4914 auto const &DL = F->getParent()->getDataLayout();
4915 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004916 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004917
Michael Kruse89b1f942017-03-17 13:56:53 +00004918 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004919 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00004920
4921 if (S) {
4922 ScopDetection::LoopStats Stats =
4923 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
4924 updateLoopCountStatistic(Stats);
4925 }
4926
Tobias Grosser75805372011-04-29 06:27:02 +00004927 return false;
4928}
4929
Johannes Doerfert99191c72016-05-31 09:41:04 +00004930void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004931 if (S)
4932 S->print(OS);
4933 else
4934 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004935}
Tobias Grosser75805372011-04-29 06:27:02 +00004936
Johannes Doerfert99191c72016-05-31 09:41:04 +00004937char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004938
Johannes Doerfert99191c72016-05-31 09:41:04 +00004939Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4940
4941INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004942 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004943 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004944INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00004945INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004946INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004947INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004948INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004949INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004950INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004951INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004952 "Polly - Create polyhedral description of Scops", false,
4953 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004954
4955//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00004956ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
4957 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
4958 AssumptionCache &AC) {
4959 /// Create polyhedral descripton of scops for all the valid regions of a
4960 /// function.
4961 for (auto &It : SD) {
4962 Region *R = const_cast<Region *>(It);
4963 if (!SD.isMaxRegionInScop(*R))
4964 continue;
4965
4966 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4967 std::unique_ptr<Scop> S = SB.getScop();
4968 if (!S)
4969 continue;
4970 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
4971 assert(Inserted && "Building Scop for the same region twice!");
4972 (void)Inserted;
4973 }
4974}
4975
4976AnalysisKey ScopInfoAnalysis::Key;
4977
4978ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
4979 FunctionAnalysisManager &FAM) {
4980 auto &SD = FAM.getResult<ScopAnalysis>(F);
4981 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
4982 auto &LI = FAM.getResult<LoopAnalysis>(F);
4983 auto &AA = FAM.getResult<AAManager>(F);
4984 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
4985 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
4986 auto &DL = F.getParent()->getDataLayout();
4987 return {DL, SD, SE, LI, AA, DT, AC};
4988}
4989
4990PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
4991 FunctionAnalysisManager &FAM) {
4992 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
4993 for (auto &It : SI) {
4994 if (It.second)
4995 It.second->print(Stream);
4996 else
4997 Stream << "Invalid Scop!\n";
4998 }
4999 return PreservedAnalyses::all();
5000}
5001
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005002void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
5003 AU.addRequired<LoopInfoWrapperPass>();
5004 AU.addRequired<RegionInfoPass>();
5005 AU.addRequired<DominatorTreeWrapperPass>();
5006 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005007 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005008 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005009 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005010 AU.setPreservesAll();
5011}
5012
5013bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005014 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005015 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5016 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5017 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5018 auto const &DL = F.getParent()->getDataLayout();
5019 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005020 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005021
Philip Pfaffe838e0882017-05-15 12:55:14 +00005022 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005023 return false;
5024}
5025
5026void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005027 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005028 if (It.second)
5029 It.second->print(OS);
5030 else
5031 OS << "Invalid Scop!\n";
5032 }
5033}
5034
5035char ScopInfoWrapperPass::ID = 0;
5036
5037Pass *polly::createScopInfoWrapperPassPass() {
5038 return new ScopInfoWrapperPass();
5039}
5040
5041INITIALIZE_PASS_BEGIN(
5042 ScopInfoWrapperPass, "polly-function-scops",
5043 "Polly - Create polyhedral description of all Scops of a function", false,
5044 false);
5045INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005046INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005047INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5048INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5049INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005050INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005051INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5052INITIALIZE_PASS_END(
5053 ScopInfoWrapperPass, "polly-function-scops",
5054 "Polly - Create polyhedral description of all Scops of a function", false,
5055 false)