blob: 2b304ae3ea6f2a65c2b833db372950294fec9620 [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"
Johannes Doerfert2af10e22015-11-12 03:25:01 +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
Tobias Grosser75dc40c2015-12-20 13:31:48 +000064// The maximal number of basic sets we allow during domain construction to
65// be created. More complex scops will result in very high compile time and
66// are also unlikely to result in good code
Michael Krusebc150122016-05-02 12:25:18 +000067static int const MaxDisjunctionsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +000068
Johannes Doerfert2f705842016-04-12 16:09:44 +000069static cl::opt<bool> PollyRemarksMinimal(
70 "polly-remarks-minimal",
71 cl::desc("Do not emit remarks about assumptions that are known"),
72 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
73
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000074// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000075// operations can overflow easily. Additive reductions and bit operations
76// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000077static cl::opt<bool> DisableMultiplicativeReductions(
78 "polly-disable-multiplicative-reductions",
79 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
80 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000081
Johannes Doerfert9143d672014-09-27 11:02:39 +000082static cl::opt<unsigned> RunTimeChecksMaxParameters(
83 "polly-rtc-max-parameters",
84 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
85 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
86
Tobias Grosser71500722015-03-28 15:11:14 +000087static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
88 "polly-rtc-max-arrays-per-group",
89 cl::desc("The maximal number of arrays to compare in each alias group."),
90 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +000091
Tobias Grosser8a9c2352015-08-16 10:19:29 +000092static cl::opt<std::string> UserContextStr(
93 "polly-context", cl::value_desc("isl parameter set"),
94 cl::desc("Provide additional constraints on the context parameters"),
95 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000096
Tobias Grosserd83b8a82015-08-20 19:08:11 +000097static cl::opt<bool> DetectReductions("polly-detect-reductions",
98 cl::desc("Detect and exploit reductions"),
99 cl::Hidden, cl::ZeroOrMore,
100 cl::init(true), cl::cat(PollyCategory));
101
Tobias Grosser2937b592016-04-29 11:43:20 +0000102static cl::opt<bool>
103 IslOnErrorAbort("polly-on-isl-error-abort",
104 cl::desc("Abort if an isl error is encountered"),
105 cl::init(true), cl::cat(PollyCategory));
106
Michael Kruse7bf39442015-09-10 12:46:52 +0000107//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000108
Michael Kruse046dde42015-08-10 13:01:57 +0000109// Create a sequence of two schedules. Either argument may be null and is
110// interpreted as the empty schedule. Can also return null if both schedules are
111// empty.
112static __isl_give isl_schedule *
113combineInSequence(__isl_take isl_schedule *Prev,
114 __isl_take isl_schedule *Succ) {
115 if (!Prev)
116 return Succ;
117 if (!Succ)
118 return Prev;
119
120 return isl_schedule_sequence(Prev, Succ);
121}
122
Johannes Doerferte7044942015-02-24 11:58:30 +0000123static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
124 const ConstantRange &Range,
125 int dim,
126 enum isl_dim_type type) {
127 isl_val *V;
128 isl_ctx *ctx = isl_set_get_ctx(S);
129
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000130 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
131 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000132 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000133 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
134
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000135 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000136 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000137 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000138 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000139 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
140
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000141 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000142 return isl_set_union(SLB, SUB);
143 else
144 return isl_set_intersect(SLB, SUB);
145}
146
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000147static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
148 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
149 if (!BasePtrLI)
150 return nullptr;
151
Johannes Doerfert952b5302016-05-23 12:40:48 +0000152 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000153 return nullptr;
154
155 ScalarEvolution &SE = *S->getSE();
156
157 auto *OriginBaseSCEV =
158 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
159 if (!OriginBaseSCEV)
160 return nullptr;
161
162 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
163 if (!OriginBaseSCEVUnknown)
164 return nullptr;
165
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000166 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000167 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000168}
169
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000170ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000171 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000172 const DataLayout &DL, Scop *S,
173 const char *BaseName)
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000174 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000175 std::string BasePtrName =
Roman Gareevd7754a12016-07-30 09:25:51 +0000176 BaseName ? BaseName : getIslCompatibleName("MemRef_", BasePtr,
177 Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000178 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000179
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000180 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000181
182 if (!BasePtr) {
183 BasePtrOriginSAI = nullptr;
184 return;
185 }
186
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000187 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
188 if (BasePtrOriginSAI)
189 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000190}
191
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000192__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000193 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000194 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
195 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
196 return Space;
197}
198
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000199void ScopArrayInfo::updateElementType(Type *NewElementType) {
200 if (NewElementType == ElementType)
201 return;
202
Tobias Grosserd840fc72016-02-04 13:18:42 +0000203 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
204 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
205
Johannes Doerferta7920982016-02-25 14:08:48 +0000206 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000207 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000208
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000209 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
210 ElementType = NewElementType;
211 } else {
212 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
213 ElementType = IntegerType::get(ElementType->getContext(), GCD);
214 }
215}
216
217bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000218 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
219 int ExtraDimsNew = NewSizes.size() - SharedDims;
220 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000221
222 for (int i = 0; i < SharedDims; i++) {
Michael Kruse19c9d992016-09-13 09:56:05 +0000223 auto *NewSize = NewSizes[i + ExtraDimsNew];
224 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
Roman Gareevf5aff702016-09-12 17:08:31 +0000225 if (NewSize && KnownSize && NewSize != KnownSize)
Tobias Grosser8286b832015-11-02 11:29:32 +0000226 return false;
Roman Gareevf5aff702016-09-12 17:08:31 +0000227 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000228
229 if (DimensionSizes.size() >= NewSizes.size())
230 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000231
232 DimensionSizes.clear();
233 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
234 NewSizes.end());
235 for (isl_pw_aff *Size : DimensionSizesPw)
236 isl_pw_aff_free(Size);
237 DimensionSizesPw.clear();
238 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000239 if (!Expr) {
240 DimensionSizesPw.push_back(nullptr);
241 continue;
242 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000243 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000244 DimensionSizesPw.push_back(Size);
245 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000246 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000247}
248
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000249ScopArrayInfo::~ScopArrayInfo() {
250 isl_id_free(Id);
251 for (isl_pw_aff *Size : DimensionSizesPw)
252 isl_pw_aff_free(Size);
253}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000254
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000255std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
256
257int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000258 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000259}
260
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000261__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
262 return isl_id_copy(Id);
263}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000264
265void ScopArrayInfo::dump() const { print(errs()); }
266
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000267void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000268 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000269 unsigned u = 0;
270 if (getNumberOfDimensions() > 0 && !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000271 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000272 u++;
273 }
274 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000275 OS << "[";
276
Tobias Grosser26253842015-11-10 14:24:21 +0000277 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000278 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000279 OS << " " << Size << " ";
280 isl_pw_aff_free(Size);
281 } else {
282 OS << *getDimensionSize(u);
283 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000284
285 OS << "]";
286 }
287
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000288 OS << ";";
289
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000290 if (BasePtrOriginSAI)
291 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
292
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000293 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000294}
295
296const ScopArrayInfo *
297ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
298 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
299 assert(Id && "Output dimension didn't have an ID");
300 return getFromId(Id);
301}
302
Michael Krused56b90a2016-09-01 09:03:27 +0000303const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000304 void *User = isl_id_get_user(Id);
305 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
306 isl_id_free(Id);
307 return SAI;
308}
309
Michael Kruse3b425ff2016-04-11 14:34:08 +0000310void MemoryAccess::wrapConstantDimensions() {
311 auto *SAI = getScopArrayInfo();
312 auto *ArraySpace = SAI->getSpace();
313 auto *Ctx = isl_space_get_ctx(ArraySpace);
314 unsigned DimsArray = SAI->getNumberOfDimensions();
315
316 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
317 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
318 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
319
320 // Begin with last dimension, to iteratively carry into higher dimensions.
321 for (int i = DimsArray - 1; i > 0; i--) {
322 auto *DimSize = SAI->getDimensionSize(i);
323 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
324
325 // This transformation is not applicable to dimensions with dynamic size.
326 if (!DimSizeCst)
327 continue;
328
329 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
330 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
331 isl_dim_set, i);
332 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
333 isl_dim_set, i - 1);
334
335 // Compute: index % size
336 // Modulo must apply in the divide of the previous iteration, if any.
337 auto *Modulo = isl_aff_copy(Var);
338 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
339 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
340
341 // Compute: floor(index / size)
342 auto *Divide = Var;
343 Divide = isl_aff_div(
344 Divide,
345 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
346 Divide = isl_aff_floor(Divide);
347 Divide = isl_aff_add(Divide, PrevVar);
348 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
349
350 // Apply Modulo and Divide.
351 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
352 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
353 }
354
355 // Apply all modulo/divides on the accesses.
356 AccessRelation =
357 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
358 AccessRelation = isl_map_detect_equalities(AccessRelation);
359 isl_local_space_free(LArraySpace);
360}
361
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000362void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000363 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000364 auto *ArraySpace = SAI->getSpace();
365 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000366 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000367
368 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
369 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
370 auto DimsMissing = DimsArray - DimsAccess;
371
Michael Kruse375cb5f2016-02-24 22:08:24 +0000372 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000373 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000374 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000375 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000376
Johannes Doerferta90943d2016-02-21 16:37:25 +0000377 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000378 isl_set_universe(AccessSpace),
379 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000380
381 for (unsigned i = 0; i < DimsMissing; i++)
382 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
383
384 for (unsigned i = DimsMissing; i < DimsArray; i++)
385 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
386
387 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000388
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000389 // For the non delinearized arrays, divide the access function of the last
390 // subscript by the size of the elements in the array.
391 //
392 // A stride one array access in C expressed as A[i] is expressed in
393 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
394 // two subsequent values of 'i' index two values that are stored next to
395 // each other in memory. By this division we make this characteristic
396 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000397 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000398 // that divides the offsets of all accesses to this base pointer.
399 if (DimsAccess == 1) {
400 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
401 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
402 }
403
Michael Kruse3b425ff2016-04-11 14:34:08 +0000404 // We currently do this only if we added at least one dimension, which means
405 // some dimension's indices have not been specified, an indicator that some
406 // index values have been added together.
407 // TODO: Investigate general usefulness; Effect on unit tests is to make index
408 // expressions more complicated.
409 if (DimsMissing)
410 wrapConstantDimensions();
411
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000412 if (!isAffine())
413 computeBoundsOnAccessRelation(ArrayElemSize);
414
Tobias Grosserd840fc72016-02-04 13:18:42 +0000415 // Introduce multi-element accesses in case the type loaded by this memory
416 // access is larger than the canonical element type of the array.
417 //
418 // An access ((float *)A)[i] to an array char *A is modeled as
419 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000420 if (ElemBytes > ArrayElemSize) {
421 assert(ElemBytes % ArrayElemSize == 0 &&
422 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000423 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000424 isl_set_universe(isl_space_copy(ArraySpace)),
425 isl_set_universe(isl_space_copy(ArraySpace)));
426 for (unsigned i = 0; i < DimsArray - 1; i++)
427 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
428
Tobias Grosserd840fc72016-02-04 13:18:42 +0000429 isl_constraint *C;
430 isl_local_space *LS;
431
432 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000433 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
434
435 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
436 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000437 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000438 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
439 Map = isl_map_add_constraint(Map, C);
440
441 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000442 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000443 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
444 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
445 Map = isl_map_add_constraint(Map, C);
446 AccessRelation = isl_map_apply_range(AccessRelation, Map);
447 }
448
449 isl_space_free(ArraySpace);
450
Roman Gareev10595a12016-01-08 14:01:59 +0000451 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000452}
453
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000454const std::string
455MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
456 switch (RT) {
457 case MemoryAccess::RT_NONE:
458 llvm_unreachable("Requested a reduction operator string for a memory "
459 "access which isn't a reduction");
460 case MemoryAccess::RT_ADD:
461 return "+";
462 case MemoryAccess::RT_MUL:
463 return "*";
464 case MemoryAccess::RT_BOR:
465 return "|";
466 case MemoryAccess::RT_BXOR:
467 return "^";
468 case MemoryAccess::RT_BAND:
469 return "&";
470 }
471 llvm_unreachable("Unknown reduction type");
472 return "";
473}
474
Tobias Grosserc80d6972016-09-02 06:33:33 +0000475/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000476static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
477 const Instruction *Load) {
478 if (!BinOp)
479 return MemoryAccess::RT_NONE;
480 switch (BinOp->getOpcode()) {
481 case Instruction::FAdd:
482 if (!BinOp->hasUnsafeAlgebra())
483 return MemoryAccess::RT_NONE;
484 // Fall through
485 case Instruction::Add:
486 return MemoryAccess::RT_ADD;
487 case Instruction::Or:
488 return MemoryAccess::RT_BOR;
489 case Instruction::Xor:
490 return MemoryAccess::RT_BXOR;
491 case Instruction::And:
492 return MemoryAccess::RT_BAND;
493 case Instruction::FMul:
494 if (!BinOp->hasUnsafeAlgebra())
495 return MemoryAccess::RT_NONE;
496 // Fall through
497 case Instruction::Mul:
498 if (DisableMultiplicativeReductions)
499 return MemoryAccess::RT_NONE;
500 return MemoryAccess::RT_MUL;
501 default:
502 return MemoryAccess::RT_NONE;
503 }
504}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000505
Tobias Grosser75805372011-04-29 06:27:02 +0000506MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000507 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000508 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000509 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000510 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000511}
512
Michael Kruse2fa35192016-09-01 19:53:31 +0000513const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000514 isl_id *ArrayId = getArrayId();
515 void *User = isl_id_get_user(ArrayId);
516 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
517 isl_id_free(ArrayId);
518 return SAI;
519}
520
Michael Kruse2fa35192016-09-01 19:53:31 +0000521const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
522 isl_id *ArrayId = getLatestArrayId();
523 void *User = isl_id_get_user(ArrayId);
524 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
525 isl_id_free(ArrayId);
526 return SAI;
527}
528
529__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000530 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
531}
532
Michael Kruse2fa35192016-09-01 19:53:31 +0000533__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
534 if (!hasNewAccessRelation())
535 return getOriginalArrayId();
536 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
537}
538
Tobias Grosserd840fc72016-02-04 13:18:42 +0000539__isl_give isl_map *MemoryAccess::getAddressFunction() const {
540 return isl_map_lexmin(getAccessRelation());
541}
542
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000543__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
544 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000545 isl_map *Schedule, *ScheduledAccRel;
546 isl_union_set *UDomain;
547
548 UDomain = isl_union_set_from_set(getStatement()->getDomain());
549 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
550 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000551 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000552 return isl_pw_multi_aff_from_map(ScheduledAccRel);
553}
554
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000555__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000556 return isl_map_copy(AccessRelation);
557}
558
Johannes Doerferta99130f2014-10-13 12:58:03 +0000559std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000560 return stringFromIslObj(AccessRelation);
561}
562
Johannes Doerferta99130f2014-10-13 12:58:03 +0000563__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000564 return isl_map_get_space(AccessRelation);
565}
566
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000567__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000568 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000569}
570
Tobias Grosser6f730082015-09-05 07:46:47 +0000571std::string MemoryAccess::getNewAccessRelationStr() const {
572 return stringFromIslObj(NewAccessRelation);
573}
574
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000575__isl_give isl_basic_map *
576MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000577 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000578 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000579
Tobias Grosser084d8f72012-05-29 09:29:44 +0000580 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000581 isl_basic_set_universe(Statement->getDomainSpace()),
582 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000583}
584
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000585// Formalize no out-of-bound access assumption
586//
587// When delinearizing array accesses we optimistically assume that the
588// delinearized accesses do not access out of bound locations (the subscript
589// expression of each array evaluates for each statement instance that is
590// executed to a value that is larger than zero and strictly smaller than the
591// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000592// dimension for which we do not need to assume any upper bound. At this point
593// we formalize this assumption to ensure that at code generation time the
594// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000595//
596// To find the set of constraints necessary to avoid out of bound accesses, we
597// first build the set of data locations that are not within array bounds. We
598// then apply the reverse access relation to obtain the set of iterations that
599// may contain invalid accesses and reduce this set of iterations to the ones
600// that are actually executed by intersecting them with the domain of the
601// statement. If we now project out all loop dimensions, we obtain a set of
602// parameters that may cause statement instances to be executed that may
603// possibly yield out of bound memory accesses. The complement of these
604// constraints is the set of constraints that needs to be assumed to ensure such
605// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000606void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000607 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000608 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000609 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000610 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000611 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
612 isl_pw_aff *Var =
613 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
614 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
615
616 isl_set *DimOutside;
617
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000618 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000619 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000620 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
621 isl_space_dim(Space, isl_dim_set));
622 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
623 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000624
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000625 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000626
627 Outside = isl_set_union(Outside, DimOutside);
628 }
629
630 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
631 Outside = isl_set_intersect(Outside, Statement->getDomain());
632 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000633
634 // Remove divs to avoid the construction of overly complicated assumptions.
635 // Doing so increases the set of parameter combinations that are assumed to
636 // not appear. This is always save, but may make the resulting run-time check
637 // bail out more often than strictly necessary.
638 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000639 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000640 const auto &Loc = getAccessInstruction()
641 ? getAccessInstruction()->getDebugLoc()
642 : DebugLoc();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000643 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
644 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000645 isl_space_free(Space);
646}
647
Johannes Doerfertcea61932016-02-21 19:13:19 +0000648void MemoryAccess::buildMemIntrinsicAccessRelation() {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000649 assert(isa<MemIntrinsic>(getAccessInstruction()));
Roman Gareevf5aff702016-09-12 17:08:31 +0000650 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000651
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000652 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000653 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000654
655 isl_map *LengthMap;
656 if (Subscripts[1] == nullptr) {
657 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
658 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000659 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000660 LengthMap = isl_map_from_pw_aff(LengthPWA);
661 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
662 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
663 }
664 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
665 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000666 SubscriptMap =
667 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000668 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
669 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
670 getStatement()->getDomainId());
671}
672
Johannes Doerferte7044942015-02-24 11:58:30 +0000673void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
674 ScalarEvolution *SE = Statement->getParent()->getSE();
675
Johannes Doerfertcea61932016-02-21 19:13:19 +0000676 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000677 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000678 return;
679
680 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000681 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
682 return;
683
684 auto *PtrSCEV = SE->getSCEV(Ptr);
685 if (isa<SCEVCouldNotCompute>(PtrSCEV))
686 return;
687
688 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
689 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
690 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
691
692 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
693 if (Range.isFullSet())
694 return;
695
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000696 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000697 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000698 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000699 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000700 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000701
702 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000703 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000704
705 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
706 AccessRange =
707 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
708 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
709}
710
Michael Krusee2bccbb2015-09-18 19:59:43 +0000711__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000712 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000713 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000714
715 for (int i = Size - 2; i >= 0; --i) {
716 isl_space *Space;
717 isl_map *MapOne, *MapTwo;
Roman Gareevf5aff702016-09-12 17:08:31 +0000718 isl_pw_aff *DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000719
720 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
721 isl_pw_aff_free(DimSize);
722 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
723
724 Space = isl_map_get_space(AccessRelation);
725 Space = isl_space_map_from_set(isl_space_range(Space));
726 Space = isl_space_align_params(Space, SpaceSize);
727
728 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
729 isl_id_free(ParamId);
730
731 MapOne = isl_map_universe(isl_space_copy(Space));
732 for (int j = 0; j < Size; ++j)
733 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
734 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
735
736 MapTwo = isl_map_universe(isl_space_copy(Space));
737 for (int j = 0; j < Size; ++j)
738 if (j < i || j > i + 1)
739 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
740
741 isl_local_space *LS = isl_local_space_from_space(Space);
742 isl_constraint *C;
743 C = isl_equality_alloc(isl_local_space_copy(LS));
744 C = isl_constraint_set_constant_si(C, -1);
745 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
746 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
747 MapTwo = isl_map_add_constraint(MapTwo, C);
748 C = isl_equality_alloc(LS);
749 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
750 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
751 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
752 MapTwo = isl_map_add_constraint(MapTwo, C);
753 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
754
755 MapOne = isl_map_union(MapOne, MapTwo);
756 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
757 }
758 return AccessRelation;
759}
760
Tobias Grosserc80d6972016-09-02 06:33:33 +0000761/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000762static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000763 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000764 if (Size == 1)
765 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000766
767 // Only one factor needs to be divisible.
768 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
769 for (auto *FactorExpr : MulExpr->operands())
770 if (isDivisible(FactorExpr, Size, SE))
771 return true;
772 return false;
773 }
774
775 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
776 // to be divisble.
777 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
778 for (auto *OpExpr : NAryExpr->operands())
779 if (!isDivisible(OpExpr, Size, SE))
780 return false;
781 return true;
782 }
783
784 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
785 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
786 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
787 return MulSCEV == Expr;
788}
789
Michael Krusee2bccbb2015-09-18 19:59:43 +0000790void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
791 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000792
Johannes Doerfert85676e32016-04-23 14:32:34 +0000793 // Initialize the invalid domain which describes all iterations for which the
794 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000795 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
796 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
797 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000798
Michael Krusee2bccbb2015-09-18 19:59:43 +0000799 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000800 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000801
Michael Krusee2bccbb2015-09-18 19:59:43 +0000802 if (!isAffine()) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000803 if (isa<MemIntrinsic>(getAccessInstruction()))
804 buildMemIntrinsicAccessRelation();
805
Tobias Grosser4f967492013-06-23 05:21:18 +0000806 // We overapproximate non-affine accesses with a possible access to the
807 // whole array. For read accesses it does not make a difference, if an
808 // access must or may happen. However, for write accesses it is important to
809 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000810 if (!AccessRelation)
811 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
812
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000813 AccessRelation =
814 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000815 return;
816 }
817
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000818 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000819 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000820
Michael Krusee2bccbb2015-09-18 19:59:43 +0000821 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000822 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000823 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000824 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000825 }
826
Roman Gareevf5aff702016-09-12 17:08:31 +0000827 if (Sizes.size() >= 2 && !isa<SCEVConstant>(Sizes[1]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000828 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000829
Tobias Grosser79baa212014-04-10 08:38:02 +0000830 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000831 AccessRelation = isl_map_set_tuple_id(
832 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000833 AccessRelation =
834 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
835
Tobias Grosseraa660a92015-03-30 00:07:50 +0000836 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000837 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000838}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000839
Michael Krusecac948e2015-10-02 13:53:07 +0000840MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000841 AccessType AccType, Value *BaseAddress,
842 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000843 ArrayRef<const SCEV *> Subscripts,
844 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000845 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000846 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Johannes Doerfert85676e32016-04-23 14:32:34 +0000847 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
848 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()),
849 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000850 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000851 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000852 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000853 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000854
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000855 std::string IdName =
856 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000857 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
858}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000859
Roman Gareevb3224ad2016-09-14 06:26:09 +0000860MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
861 __isl_take isl_map *AccRel)
862 : Kind(ScopArrayInfo::MemoryKind::MK_Array), AccType(AccType),
863 RedType(RT_NONE), Statement(Stmt), InvalidDomain(nullptr),
864 AccessInstruction(nullptr), IsAffine(true), AccessRelation(nullptr),
865 NewAccessRelation(AccRel) {
866 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
867 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
868 Sizes.push_back(nullptr);
869 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
870 Sizes.push_back(SAI->getDimensionSize(i));
871 ElementType = SAI->getElementType();
872 BaseAddr = SAI->getBasePtr();
873 BaseName = SAI->getName();
874 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
875 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
876
877 std::string IdName =
878 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
879 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
880}
881
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000882void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +0000883 auto *Ctx = Statement->getParent()->getContext();
884 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
885 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +0000886}
887
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000888const std::string MemoryAccess::getReductionOperatorStr() const {
889 return MemoryAccess::getReductionOperatorStr(getReductionType());
890}
891
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000892__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
893
Johannes Doerfertf6183392014-07-01 20:52:51 +0000894raw_ostream &polly::operator<<(raw_ostream &OS,
895 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000896 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000897 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000898 else
899 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000900 return OS;
901}
902
Tobias Grosser75805372011-04-29 06:27:02 +0000903void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000904 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000905 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000906 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000907 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000908 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000909 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000910 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000911 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000912 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000913 break;
914 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000915 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000916 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000917 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000918 if (hasNewAccessRelation())
919 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000920}
921
Tobias Grosser74394f02013-01-14 22:40:23 +0000922void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000923
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000924__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
925 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000926 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +0000927 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
928 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
929 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000930 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000931}
932
Tobias Grosser75805372011-04-29 06:27:02 +0000933// Create a map in the size of the provided set domain, that maps from the
934// one element of the provided set domain to another element of the provided
935// set domain.
936// The mapping is limited to all points that are equal in all but the last
937// dimension and for which the last dimension of the input is strict smaller
938// than the last dimension of the output.
939//
940// getEqualAndLarger(set[i0, i1, ..., iX]):
941//
942// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
943// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
944//
Tobias Grosser2a526fe2016-09-08 11:18:56 +0000945static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000946 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000947 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000948 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000949
950 // Set all but the last dimension to be equal for the input and output
951 //
952 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
953 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000954 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000955 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000956
957 // Set the last dimension of the input to be strict smaller than the
958 // last dimension of the output.
959 //
960 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000961 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
962 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000963 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000964}
965
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000966__isl_give isl_set *
967MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000968 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000969 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000970 isl_space *Space = isl_space_range(isl_map_get_space(S));
971 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000972
Sebastian Popa00a0292012-12-18 07:46:06 +0000973 S = isl_map_reverse(S);
974 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000975
Sebastian Popa00a0292012-12-18 07:46:06 +0000976 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
977 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
978 NextScatt = isl_map_apply_domain(NextScatt, S);
979 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000980
Sebastian Popa00a0292012-12-18 07:46:06 +0000981 isl_set *Deltas = isl_map_deltas(NextScatt);
982 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000983}
984
Sebastian Popa00a0292012-12-18 07:46:06 +0000985bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000986 int StrideWidth) const {
987 isl_set *Stride, *StrideX;
988 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000989
Sebastian Popa00a0292012-12-18 07:46:06 +0000990 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000991 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000992 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
993 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
994 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
995 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000996 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000997
Tobias Grosser28dd4862012-01-24 16:42:16 +0000998 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000999 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001000
Tobias Grosser28dd4862012-01-24 16:42:16 +00001001 return IsStrideX;
1002}
1003
Michael Krused56b90a2016-09-01 09:03:27 +00001004bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001005 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001006}
1007
Michael Krused56b90a2016-09-01 09:03:27 +00001008bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001009 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001010}
1011
Michael Krused56b90a2016-09-01 09:03:27 +00001012void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001013 assert(NewAccess);
1014
1015#ifndef NDEBUG
1016 // Check domain space compatibility.
1017 auto *NewSpace = isl_map_get_space(NewAccess);
1018 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1019 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1020 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1021 isl_space_free(NewDomainSpace);
1022 isl_space_free(OriginalDomainSpace);
1023
1024 // Check whether there is an access for every statement instance.
1025 auto *StmtDomain = getStatement()->getDomain();
1026 StmtDomain = isl_set_intersect_params(
1027 StmtDomain, getStatement()->getParent()->getContext());
1028 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1029 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1030 "Partial accesses not supported");
1031 isl_set_free(NewDomain);
1032 isl_set_free(StmtDomain);
1033
1034 // Check whether access dimensions correspond to number of dimensions of the
1035 // accesses array.
1036 auto *NewAccessSpace = isl_space_range(NewSpace);
1037 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1038 "Must specify the array that is accessed");
1039 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1040 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1041 assert(SAI && "Must set a ScopArrayInfo");
1042 assert(!SAI->getBasePtrOriginSAI() &&
1043 "Indirect array not supported by codegen");
1044 auto Dims = SAI->getNumberOfDimensions();
1045 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1046 "Access dims must match array dims");
1047 isl_space_free(NewAccessSpace);
1048 isl_id_free(NewArrayId);
1049#endif
1050
Tobias Grosser166c4222015-09-05 07:46:40 +00001051 isl_map_free(NewAccessRelation);
1052 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001053}
Tobias Grosser75805372011-04-29 06:27:02 +00001054
1055//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001056
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001057__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001058 isl_set *Domain = getDomain();
1059 if (isl_set_is_empty(Domain)) {
1060 isl_set_free(Domain);
1061 return isl_map_from_aff(
1062 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1063 }
1064 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001065 if (!Schedule) {
1066 isl_set_free(Domain);
1067 return nullptr;
1068 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001069 Schedule = isl_union_map_intersect_domain(
1070 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1071 if (isl_union_map_is_empty(Schedule)) {
1072 isl_set_free(Domain);
1073 isl_union_map_free(Schedule);
1074 return isl_map_from_aff(
1075 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1076 }
1077 auto *M = isl_map_from_union_map(Schedule);
1078 M = isl_map_coalesce(M);
1079 M = isl_map_gist_domain(M, Domain);
1080 M = isl_map_coalesce(M);
1081 return M;
1082}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001083
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001084__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1085 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001086 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1087 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001088}
1089
Tobias Grosser37eb4222014-02-20 21:43:54 +00001090void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1091 assert(isl_set_is_subset(NewDomain, Domain) &&
1092 "New domain is not a subset of old domain!");
1093 isl_set_free(Domain);
1094 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001095}
1096
Michael Krusecac948e2015-10-02 13:53:07 +00001097void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001098 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001099 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001100 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001101
Tobias Grossera535dff2015-12-13 19:59:01 +00001102 ScopArrayInfo::MemoryKind Ty;
1103 if (Access->isPHIKind())
1104 Ty = ScopArrayInfo::MK_PHI;
1105 else if (Access->isExitPHIKind())
1106 Ty = ScopArrayInfo::MK_ExitPHI;
1107 else if (Access->isValueKind())
1108 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001109 else
Tobias Grossera535dff2015-12-13 19:59:01 +00001110 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001111
Johannes Doerfertadeab372016-02-07 13:57:32 +00001112 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1113 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001114 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001115 }
1116}
1117
Michael Krusecac948e2015-10-02 13:53:07 +00001118void ScopStmt::addAccess(MemoryAccess *Access) {
1119 Instruction *AccessInst = Access->getAccessInstruction();
1120
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001121 if (Access->isArrayKind()) {
1122 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1123 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001124 } else if (Access->isValueKind() && Access->isWrite()) {
1125 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001126 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001127 assert(!ValueWrites.lookup(AccessVal));
1128
1129 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001130 } else if (Access->isValueKind() && Access->isRead()) {
1131 Value *AccessVal = Access->getAccessValue();
1132 assert(!ValueReads.lookup(AccessVal));
1133
1134 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001135 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1136 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1137 assert(!PHIWrites.lookup(PHI));
1138
1139 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001140 }
1141
1142 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001143}
1144
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001145void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001146 for (MemoryAccess *MA : *this)
1147 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001148
Johannes Doerferta60ad842016-05-10 12:18:22 +00001149 auto *Ctx = Parent.getContext();
1150 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1151 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001152}
1153
Tobias Grosserc80d6972016-09-02 06:33:33 +00001154/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001155static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1156 void *User) {
1157 isl_set **BoundedParts = static_cast<isl_set **>(User);
1158 if (isl_basic_set_is_bounded(BSet))
1159 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1160 else
1161 isl_basic_set_free(BSet);
1162 return isl_stat_ok;
1163}
1164
Tobias Grosserc80d6972016-09-02 06:33:33 +00001165/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001166static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1167 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1168 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1169 isl_set_free(S);
1170 return BoundedParts;
1171}
1172
Tobias Grosserc80d6972016-09-02 06:33:33 +00001173/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001174///
1175/// @returns A separation of @p S into first an unbounded then a bounded subset,
1176/// both with regards to the dimension @p Dim.
1177static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1178partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1179
1180 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001181 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001182
1183 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001184 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001185
1186 // Remove dimensions that are greater than Dim as they are not interesting.
1187 assert(NumDimsS >= Dim + 1);
1188 OnlyDimS =
1189 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1190
1191 // Create artificial parametric upper bounds for dimensions smaller than Dim
1192 // as we are not interested in them.
1193 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1194 for (unsigned u = 0; u < Dim; u++) {
1195 isl_constraint *C = isl_inequality_alloc(
1196 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1197 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1198 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1199 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1200 }
1201
1202 // Collect all bounded parts of OnlyDimS.
1203 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1204
1205 // Create the dimensions greater than Dim again.
1206 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1207 NumDimsS - Dim - 1);
1208
1209 // Remove the artificial upper bound parameters again.
1210 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1211
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001212 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001213 return std::make_pair(UnboundedParts, BoundedParts);
1214}
1215
Tobias Grosserc80d6972016-09-02 06:33:33 +00001216/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001217static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1218 __isl_take isl_set *To) {
1219 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1220 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1221 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1222 }
1223 return To;
1224}
1225
Tobias Grosserc80d6972016-09-02 06:33:33 +00001226/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001227static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001228 __isl_take isl_pw_aff *L,
1229 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001230 switch (Pred) {
1231 case ICmpInst::ICMP_EQ:
1232 return isl_pw_aff_eq_set(L, R);
1233 case ICmpInst::ICMP_NE:
1234 return isl_pw_aff_ne_set(L, R);
1235 case ICmpInst::ICMP_SLT:
1236 return isl_pw_aff_lt_set(L, R);
1237 case ICmpInst::ICMP_SLE:
1238 return isl_pw_aff_le_set(L, R);
1239 case ICmpInst::ICMP_SGT:
1240 return isl_pw_aff_gt_set(L, R);
1241 case ICmpInst::ICMP_SGE:
1242 return isl_pw_aff_ge_set(L, R);
1243 case ICmpInst::ICMP_ULT:
1244 return isl_pw_aff_lt_set(L, R);
1245 case ICmpInst::ICMP_UGT:
1246 return isl_pw_aff_gt_set(L, R);
1247 case ICmpInst::ICMP_ULE:
1248 return isl_pw_aff_le_set(L, R);
1249 case ICmpInst::ICMP_UGE:
1250 return isl_pw_aff_ge_set(L, R);
1251 default:
1252 llvm_unreachable("Non integer predicate not supported");
1253 }
1254}
1255
Tobias Grosserc80d6972016-09-02 06:33:33 +00001256/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001257///
1258/// Helper function that will make sure the dimensions of the result have the
1259/// same isl_id's as the @p Domain.
1260static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1261 __isl_take isl_pw_aff *L,
1262 __isl_take isl_pw_aff *R,
1263 __isl_keep isl_set *Domain) {
1264 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1265 return setDimensionIds(Domain, ConsequenceCondSet);
1266}
1267
Tobias Grosserc80d6972016-09-02 06:33:33 +00001268/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001269///
1270/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001271/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1272/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001273static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001274buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1275 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001276 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1277
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001278 Value *Condition = getConditionFromTerminator(SI);
1279 assert(Condition && "No condition for switch");
1280
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001281 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001282 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001283 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001284 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001285
1286 unsigned NumSuccessors = SI->getNumSuccessors();
1287 ConditionSets.resize(NumSuccessors);
1288 for (auto &Case : SI->cases()) {
1289 unsigned Idx = Case.getSuccessorIndex();
1290 ConstantInt *CaseValue = Case.getCaseValue();
1291
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001292 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001293 isl_set *CaseConditionSet =
1294 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1295 ConditionSets[Idx] = isl_set_coalesce(
1296 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1297 }
1298
1299 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1300 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1301 for (unsigned u = 2; u < NumSuccessors; u++)
1302 ConditionSetUnion =
1303 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1304 ConditionSets[0] = setDimensionIds(
1305 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1306
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001307 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001308
1309 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001310}
1311
Tobias Grosserc80d6972016-09-02 06:33:33 +00001312/// Build the conditions sets for the branch condition @p Condition in
1313/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001314///
1315/// This will fill @p ConditionSets with the conditions under which control
1316/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001317/// have as many elements as @p TI has successors. If @p TI is nullptr the
1318/// context under which @p Condition is true/false will be returned as the
1319/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001320static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001321buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1322 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001323 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1324
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001325 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001326 isl_set *ConsequenceCondSet = nullptr;
1327 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1328 if (CCond->isZero())
1329 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1330 else
1331 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1332 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1333 auto Opcode = BinOp->getOpcode();
1334 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1335
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001336 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1337 ConditionSets) &&
1338 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1339 ConditionSets);
1340 if (!Valid) {
1341 while (!ConditionSets.empty())
1342 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001343 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001344 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001345
1346 isl_set_free(ConditionSets.pop_back_val());
1347 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1348 isl_set_free(ConditionSets.pop_back_val());
1349 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1350
1351 if (Opcode == Instruction::And)
1352 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1353 else
1354 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1355 } else {
1356 auto *ICond = dyn_cast<ICmpInst>(Condition);
1357 assert(ICond &&
1358 "Condition of exiting branch was neither constant nor ICmp!");
1359
1360 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001361 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001362 // For unsigned comparisons we assumed the signed bit of neither operand
1363 // to be set. The comparison is equal to a signed comparison under this
1364 // assumption.
1365 bool NonNeg = ICond->isUnsigned();
1366 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1367 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001368 ConsequenceCondSet =
1369 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1370 }
1371
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001372 // If no terminator was given we are only looking for parameter constraints
1373 // under which @p Condition is true/false.
1374 if (!TI)
1375 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001376 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001377 ConsequenceCondSet = isl_set_coalesce(
1378 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001379
Johannes Doerfertb2885792016-04-26 09:20:41 +00001380 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001381 bool TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001382 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001383
Michael Krusef7a4a942016-05-02 12:25:36 +00001384 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001385 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1386 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001387 TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001388 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001389 }
1390
Michael Krusef7a4a942016-05-02 12:25:36 +00001391 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001392 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001393 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001394 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001395 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001396 }
1397
1398 ConditionSets.push_back(ConsequenceCondSet);
1399 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001400
1401 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001402}
1403
Tobias Grosserc80d6972016-09-02 06:33:33 +00001404/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001405///
1406/// This will fill @p ConditionSets with the conditions under which control
1407/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1408/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001409static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001410buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001411 __isl_keep isl_set *Domain,
1412 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1413
1414 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001415 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001416
1417 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1418
1419 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001420 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001421 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001422 }
1423
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001424 Value *Condition = getConditionFromTerminator(TI);
1425 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001426
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001427 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001428}
1429
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001430void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001431 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001432
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001433 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001434 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001435}
1436
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001437void ScopStmt::collectSurroundingLoops() {
1438 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1439 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1440 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1441 isl_id_free(DimId);
1442 }
1443}
1444
Michael Kruse9d080092015-09-11 21:41:48 +00001445ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerferta3519512016-04-23 13:02:23 +00001446 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1447 R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001448
Tobias Grosser16c44032015-07-09 07:31:45 +00001449 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001450}
1451
Michael Kruse9d080092015-09-11 21:41:48 +00001452ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerferta3519512016-04-23 13:02:23 +00001453 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1454 R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001455
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001456 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001457}
1458
Roman Gareevb3224ad2016-09-14 06:26:09 +00001459ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1460 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1461 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1462 R(nullptr), Build(nullptr) {
1463 BaseName = getIslCompatibleName("CopyStmt_", "",
1464 std::to_string(parent.getCopyStmtsNum()));
1465 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1466 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1467 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1468 auto *Access =
1469 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1470 parent.addAccessFunction(Access);
1471 addAccess(Access);
1472 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1473 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1474 parent.addAccessFunction(Access);
1475 addAccess(Access);
1476}
1477
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001478void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001479 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001480
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001481 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001482 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001483 buildAccessRelations();
1484
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001485 if (DetectReductions)
1486 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001487}
1488
Tobias Grosserc80d6972016-09-02 06:33:33 +00001489/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001490///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001491/// Check if the stored value for @p StoreMA is a binary operator with one or
1492/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001493/// used only once (by @p StoreMA) and its load operands are also used only
1494/// once, we have found a possible reduction chain. It starts at an operand
1495/// load and includes the binary operator and @p StoreMA.
1496///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001497/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001498/// escape this block or into any other store except @p StoreMA.
1499void ScopStmt::collectCandiateReductionLoads(
1500 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1501 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1502 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001503 return;
1504
1505 // Skip if there is not one binary operator between the load and the store
1506 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001507 if (!BinOp)
1508 return;
1509
1510 // Skip if the binary operators has multiple uses
1511 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001512 return;
1513
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001514 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001515 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1516 return;
1517
Johannes Doerfert9890a052014-07-01 00:32:29 +00001518 // Skip if the binary operator is outside the current SCoP
1519 if (BinOp->getParent() != Store->getParent())
1520 return;
1521
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001522 // Skip if it is a multiplicative reduction and we disabled them
1523 if (DisableMultiplicativeReductions &&
1524 (BinOp->getOpcode() == Instruction::Mul ||
1525 BinOp->getOpcode() == Instruction::FMul))
1526 return;
1527
Johannes Doerferte58a0122014-06-27 20:31:28 +00001528 // Check the binary operator operands for a candidate load
1529 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1530 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1531 if (!PossibleLoad0 && !PossibleLoad1)
1532 return;
1533
1534 // A load is only a candidate if it cannot escape (thus has only this use)
1535 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001536 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001537 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001538 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001539 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001540 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001541}
1542
Tobias Grosserc80d6972016-09-02 06:33:33 +00001543/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001544///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001545/// Iterate over all store memory accesses and check for valid binary reduction
1546/// like chains. For all candidates we check if they have the same base address
1547/// and there are no other accesses which overlap with them. The base address
1548/// check rules out impossible reductions candidates early. The overlap check,
1549/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001550/// guarantees that none of the intermediate results will escape during
1551/// execution of the loop nest. We basically check here that no other memory
1552/// access can access the same memory as the potential reduction.
1553void ScopStmt::checkForReductions() {
1554 SmallVector<MemoryAccess *, 2> Loads;
1555 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1556
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001557 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001558 // stores and collecting possible reduction loads.
1559 for (MemoryAccess *StoreMA : MemAccs) {
1560 if (StoreMA->isRead())
1561 continue;
1562
1563 Loads.clear();
1564 collectCandiateReductionLoads(StoreMA, Loads);
1565 for (MemoryAccess *LoadMA : Loads)
1566 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1567 }
1568
1569 // Then check each possible candidate pair.
1570 for (const auto &CandidatePair : Candidates) {
1571 bool Valid = true;
1572 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1573 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1574
1575 // Skip those with obviously unequal base addresses.
1576 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1577 isl_map_free(LoadAccs);
1578 isl_map_free(StoreAccs);
1579 continue;
1580 }
1581
1582 // And check if the remaining for overlap with other memory accesses.
1583 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1584 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1585 isl_set *AllAccs = isl_map_range(AllAccsRel);
1586
1587 for (MemoryAccess *MA : MemAccs) {
1588 if (MA == CandidatePair.first || MA == CandidatePair.second)
1589 continue;
1590
1591 isl_map *AccRel =
1592 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1593 isl_set *Accs = isl_map_range(AccRel);
1594
Tobias Grosser55a7af72016-09-08 14:08:07 +00001595 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001596 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1597 Valid = Valid && isl_set_is_empty(OverlapAccs);
1598 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001599 } else {
1600 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001601 }
1602 }
1603
1604 isl_set_free(AllAccs);
1605 if (!Valid)
1606 continue;
1607
Johannes Doerfertf6183392014-07-01 20:52:51 +00001608 const LoadInst *Load =
1609 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1610 MemoryAccess::ReductionType RT =
1611 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1612
Johannes Doerferte58a0122014-06-27 20:31:28 +00001613 // If no overlapping access was found we mark the load and store as
1614 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001615 CandidatePair.first->markAsReductionLike(RT);
1616 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001617 }
Tobias Grosser75805372011-04-29 06:27:02 +00001618}
1619
Tobias Grosser74394f02013-01-14 22:40:23 +00001620std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001621
Tobias Grosser54839312015-04-21 11:37:25 +00001622std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001623 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001624 if (!S)
1625 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001626 auto Str = stringFromIslObj(S);
1627 isl_map_free(S);
1628 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001629}
1630
Johannes Doerferta3519512016-04-23 13:02:23 +00001631void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1632 isl_set_free(InvalidDomain);
1633 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001634}
1635
Michael Kruse375cb5f2016-02-24 22:08:24 +00001636BasicBlock *ScopStmt::getEntryBlock() const {
1637 if (isBlockStmt())
1638 return getBasicBlock();
1639 return getRegion()->getEntry();
1640}
1641
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001642unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001643
Tobias Grosser75805372011-04-29 06:27:02 +00001644const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1645
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001646Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001647 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001648}
1649
Tobias Grosser74394f02013-01-14 22:40:23 +00001650isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001651
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001652__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001653
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001654__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001655 return isl_set_get_space(Domain);
1656}
1657
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001658__isl_give isl_id *ScopStmt::getDomainId() const {
1659 return isl_set_get_tuple_id(Domain);
1660}
Tobias Grossercd95b772012-08-30 11:49:38 +00001661
Johannes Doerfert7c013572016-04-12 09:57:34 +00001662ScopStmt::~ScopStmt() {
1663 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001664 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001665}
Tobias Grosser75805372011-04-29 06:27:02 +00001666
1667void ScopStmt::print(raw_ostream &OS) const {
1668 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001669 OS.indent(12) << "Domain :=\n";
1670
1671 if (Domain) {
1672 OS.indent(16) << getDomainStr() << ";\n";
1673 } else
1674 OS.indent(16) << "n/a\n";
1675
Tobias Grosser54839312015-04-21 11:37:25 +00001676 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001677
1678 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001679 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001680 } else
1681 OS.indent(16) << "n/a\n";
1682
Tobias Grosser083d3d32014-06-28 08:59:45 +00001683 for (MemoryAccess *Access : MemAccs)
1684 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001685}
1686
1687void ScopStmt::dump() const { print(dbgs()); }
1688
Michael Kruse10071822016-05-23 14:45:58 +00001689void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
1690 // Remove the memory accesses from this statement
1691 // together with all scalar accesses that were caused by it.
Michael Krusead28e5a2016-01-26 13:33:15 +00001692 // MK_Value READs have no access instruction, hence would not be removed by
1693 // this function. However, it is only used for invariant LoadInst accesses,
1694 // its arguments are always affine, hence synthesizable, and therefore there
1695 // are no MK_Value READ accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001696 auto Predicate = [&](MemoryAccess *Acc) {
1697 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1698 };
1699 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1700 MemAccs.end());
1701 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001702}
1703
Tobias Grosser75805372011-04-29 06:27:02 +00001704//===----------------------------------------------------------------------===//
1705/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001706
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001707void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001708 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1709 isl_set_free(Context);
1710 Context = NewContext;
1711}
1712
Tobias Grosserc80d6972016-09-02 06:33:33 +00001713/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001714struct SCEVSensitiveParameterRewriter
1715 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1716 ValueToValueMap &VMap;
1717 ScalarEvolution &SE;
1718
1719public:
1720 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1721 : VMap(VMap), SE(SE) {}
1722
1723 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1724 ValueToValueMap &VMap) {
1725 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1726 return SSPR.visit(E);
1727 }
1728
1729 const SCEV *visit(const SCEV *E) {
1730 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1731 }
1732
1733 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1734
1735 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1736 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1737 }
1738
1739 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1740 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1741 }
1742
1743 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1744 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1745 }
1746
1747 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1748 SmallVector<const SCEV *, 4> Operands;
1749 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1750 Operands.push_back(visit(E->getOperand(i)));
1751 return SE.getAddExpr(Operands);
1752 }
1753
1754 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1755 SmallVector<const SCEV *, 4> Operands;
1756 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1757 Operands.push_back(visit(E->getOperand(i)));
1758 return SE.getMulExpr(Operands);
1759 }
1760
1761 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1762 SmallVector<const SCEV *, 4> Operands;
1763 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1764 Operands.push_back(visit(E->getOperand(i)));
1765 return SE.getSMaxExpr(Operands);
1766 }
1767
1768 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1769 SmallVector<const SCEV *, 4> Operands;
1770 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1771 Operands.push_back(visit(E->getOperand(i)));
1772 return SE.getUMaxExpr(Operands);
1773 }
1774
1775 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1776 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1777 }
1778
1779 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1780 auto *Start = visit(E->getStart());
1781 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1782 visit(E->getStepRecurrence(SE)),
1783 E->getLoop(), SCEV::FlagAnyWrap);
1784 return SE.getAddExpr(Start, AddRec);
1785 }
1786
1787 const SCEV *visitUnknown(const SCEVUnknown *E) {
1788 if (auto *NewValue = VMap.lookup(E->getValue()))
1789 return SE.getUnknown(NewValue);
1790 return E;
1791 }
1792};
1793
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001794const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001795 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001796}
1797
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001798void Scop::createParameterId(const SCEV *Parameter) {
1799 assert(Parameters.count(Parameter));
1800 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001801
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001802 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001803
Tobias Grosser8f99c162011-11-15 11:38:55 +00001804 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1805 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001806
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001807 // If this parameter references a specific Value and this value has a name
1808 // we use this name as it is likely to be unique and more useful than just
1809 // a number.
1810 if (Val->hasName())
1811 ParameterName = Val->getName();
1812 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001813 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001814 if (LoadOrigin->hasName()) {
1815 ParameterName += "_loaded_from_";
1816 ParameterName +=
1817 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1818 }
1819 }
1820 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001821
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001822 ParameterName = getIslCompatibleName("", ParameterName, "");
1823
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001824 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1825 const_cast<void *>((const void *)Parameter));
1826 ParameterIds[Parameter] = Id;
1827}
1828
1829void Scop::addParams(const ParameterSetTy &NewParameters) {
1830 for (const SCEV *Parameter : NewParameters) {
1831 // Normalize the SCEV to get the representing element for an invariant load.
1832 Parameter = extractConstantFactor(Parameter, *SE).second;
1833 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1834
1835 if (Parameters.insert(Parameter))
1836 createParameterId(Parameter);
1837 }
1838}
1839
1840__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1841 // Normalize the SCEV to get the representing element for an invariant load.
1842 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1843 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001844}
Tobias Grosser75805372011-04-29 06:27:02 +00001845
Michael Krused56b90a2016-09-01 09:03:27 +00001846__isl_give isl_set *
1847Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001848 isl_set *DomainContext = isl_union_set_params(getDomains());
1849 return isl_set_intersect_params(C, DomainContext);
1850}
1851
Johannes Doerferte0b08072016-05-23 12:43:44 +00001852bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1853 return DT.dominates(BB, getEntry());
1854}
1855
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001856void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1857 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001858 auto &F = getFunction();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001859 for (auto &Assumption : AC.assumptions()) {
1860 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1861 if (!CI || CI->getNumArgOperands() != 1)
1862 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001863
Johannes Doerfert952b5302016-05-23 12:40:48 +00001864 bool InScop = contains(CI);
Johannes Doerferte0b08072016-05-23 12:43:44 +00001865 if (!InScop && !isDominatedBy(DT, CI->getParent()))
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001866 continue;
1867
Michael Kruse09eb4452016-03-03 22:10:47 +00001868 auto *L = LI.getLoopFor(CI->getParent());
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001869 auto *Val = CI->getArgOperand(0);
Johannes Doerfertf560b3d2016-04-25 13:33:07 +00001870 ParameterSetTy DetectedParams;
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001871 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001872 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1873 CI->getDebugLoc(),
1874 "Non-affine user assumption ignored.");
1875 continue;
1876 }
1877
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001878 // Collect all newly introduced parameters.
1879 ParameterSetTy NewParams;
1880 for (auto *Param : DetectedParams) {
1881 Param = extractConstantFactor(Param, *SE).second;
1882 Param = getRepresentingInvariantLoadSCEV(Param);
1883 if (Parameters.count(Param))
1884 continue;
1885 NewParams.insert(Param);
1886 }
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001887
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001888 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001889 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
1890 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
1891 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001892 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
1893 isl_set_free(Dom);
1894
1895 if (!Valid)
Johannes Doerfert297c7202016-05-10 13:06:42 +00001896 continue;
1897
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001898 isl_set *AssumptionCtx = nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001899 if (InScop) {
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001900 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
1901 isl_set_free(ConditionSets[0]);
1902 } else {
1903 AssumptionCtx = isl_set_complement(ConditionSets[1]);
1904 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
1905 }
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001906
1907 // Project out newly introduced parameters as they are not otherwise useful.
1908 if (!NewParams.empty()) {
1909 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
1910 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
1911 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
1912 isl_id_free(Id);
1913
1914 if (!NewParams.count(Param))
1915 continue;
1916
1917 AssumptionCtx =
1918 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
1919 }
1920 }
1921
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001922 emitOptimizationRemarkAnalysis(
1923 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1924 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1925 Context = isl_set_intersect(Context, AssumptionCtx);
1926 }
1927}
1928
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001929void Scop::addUserContext() {
1930 if (UserContextStr.empty())
1931 return;
1932
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001933 isl_set *UserContext =
1934 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001935 isl_space *Space = getParamSpace();
1936 if (isl_space_dim(Space, isl_dim_param) !=
1937 isl_set_dim(UserContext, isl_dim_param)) {
1938 auto SpaceStr = isl_space_to_str(Space);
1939 errs() << "Error: the context provided in -polly-context has not the same "
1940 << "number of dimensions than the computed context. Due to this "
1941 << "mismatch, the -polly-context option is ignored. Please provide "
1942 << "the context in the parameter space: " << SpaceStr << ".\n";
1943 free(SpaceStr);
1944 isl_set_free(UserContext);
1945 isl_space_free(Space);
1946 return;
1947 }
1948
1949 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001950 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1951 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001952
1953 if (strcmp(NameContext, NameUserContext) != 0) {
1954 auto SpaceStr = isl_space_to_str(Space);
1955 errs() << "Error: the name of dimension " << i
1956 << " provided in -polly-context "
1957 << "is '" << NameUserContext << "', but the name in the computed "
1958 << "context is '" << NameContext
1959 << "'. Due to this name mismatch, "
1960 << "the -polly-context option is ignored. Please provide "
1961 << "the context in the parameter space: " << SpaceStr << ".\n";
1962 free(SpaceStr);
1963 isl_set_free(UserContext);
1964 isl_space_free(Space);
1965 return;
1966 }
1967
1968 UserContext =
1969 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1970 isl_space_get_dim_id(Space, isl_dim_param, i));
1971 }
1972
1973 Context = isl_set_intersect(Context, UserContext);
1974 isl_space_free(Space);
1975}
1976
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001977void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001978 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001979
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001980 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001981 for (LoadInst *LInst : RIL) {
1982 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1983
Johannes Doerfert96e54712016-02-07 17:30:13 +00001984 Type *Ty = LInst->getType();
1985 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001986 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001987 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001988 continue;
1989 }
1990
1991 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00001992 InvariantEquivClasses.emplace_back(
1993 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001994 }
1995}
1996
Tobias Grosser6be480c2011-11-08 15:41:13 +00001997void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001998 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001999 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002000 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002001 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002002}
2003
Tobias Grosser18daaca2012-05-22 10:47:27 +00002004void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002005 unsigned PDim = 0;
2006 for (auto *Parameter : Parameters) {
2007 ConstantRange SRange = SE->getSignedRange(Parameter);
2008 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002009 }
2010}
2011
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002012void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002013 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002014 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002015
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002016 unsigned PDim = 0;
2017 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002018 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002019 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002020 }
2021
2022 // Align the parameters of all data structures to the model.
2023 Context = isl_set_align_params(Context, Space);
2024
Johannes Doerferta60ad842016-05-10 12:18:22 +00002025 // As all parameters are known add bounds to them.
2026 addParameterBounds();
2027
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002028 for (ScopStmt &Stmt : *this)
2029 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002030
2031 // Simplify the schedule according to the context too.
2032 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002033}
2034
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002035static __isl_give isl_set *
2036simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2037 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002038 // If we modelt all blocks in the SCoP that have side effects we can simplify
2039 // the context with the constraints that are needed for anything to be
2040 // executed at all. However, if we have error blocks in the SCoP we already
2041 // assumed some parameter combinations cannot occure and removed them from the
2042 // domains, thus we cannot use the remaining domain to simplify the
2043 // assumptions.
2044 if (!S.hasErrorBlock()) {
2045 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2046 AssumptionContext =
2047 isl_set_gist_params(AssumptionContext, DomainParameters);
2048 }
2049
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002050 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2051 return AssumptionContext;
2052}
2053
2054void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002055 // The parameter constraints of the iteration domains give us a set of
2056 // constraints that need to hold for all cases where at least a single
2057 // statement iteration is executed in the whole scop. We now simplify the
2058 // assumed context under the assumption that such constraints hold and at
2059 // least a single statement iteration is executed. For cases where no
2060 // statement instances are executed, the assumptions we have taken about
2061 // the executed code do not matter and can be changed.
2062 //
2063 // WARNING: This only holds if the assumptions we have taken do not reduce
2064 // the set of statement instances that are executed. Otherwise we
2065 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002066 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002067 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002068 // performed. In such a case, modifying the run-time conditions and
2069 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002070 // to not be executed.
2071 //
2072 // Example:
2073 //
2074 // When delinearizing the following code:
2075 //
2076 // for (long i = 0; i < 100; i++)
2077 // for (long j = 0; j < m; j++)
2078 // A[i+p][j] = 1.0;
2079 //
2080 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002081 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002082 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002083 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002084 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002085}
2086
Tobias Grosserc80d6972016-09-02 06:33:33 +00002087/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002088static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002089 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2090 isl_pw_multi_aff *MinPMA, *MaxPMA;
2091 isl_pw_aff *LastDimAff;
2092 isl_aff *OneAff;
2093 unsigned Pos;
2094
Johannes Doerfert6296d952016-04-22 11:38:19 +00002095 Set = isl_set_remove_divs(Set);
2096
Michael Krusebc150122016-05-02 12:25:18 +00002097 if (isl_set_n_basic_set(Set) >= MaxDisjunctionsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002098 isl_set_free(Set);
2099 return isl_stat_error;
2100 }
2101
Johannes Doerfert9143d672014-09-27 11:02:39 +00002102 // Restrict the number of parameters involved in the access as the lexmin/
2103 // lexmax computation will take too long if this number is high.
2104 //
2105 // Experiments with a simple test case using an i7 4800MQ:
2106 //
2107 // #Parameters involved | Time (in sec)
2108 // 6 | 0.01
2109 // 7 | 0.04
2110 // 8 | 0.12
2111 // 9 | 0.40
2112 // 10 | 1.54
2113 // 11 | 6.78
2114 // 12 | 30.38
2115 //
2116 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2117 unsigned InvolvedParams = 0;
2118 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2119 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2120 InvolvedParams++;
2121
2122 if (InvolvedParams > RunTimeChecksMaxParameters) {
2123 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002124 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002125 }
2126 }
2127
Johannes Doerfertb164c792014-09-18 11:17:17 +00002128 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2129 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2130
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002131 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2132 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2133
Johannes Doerfertb164c792014-09-18 11:17:17 +00002134 // Adjust the last dimension of the maximal access by one as we want to
2135 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2136 // we test during code generation might now point after the end of the
2137 // allocated array but we will never dereference it anyway.
2138 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2139 "Assumed at least one output dimension");
2140 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2141 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2142 OneAff = isl_aff_zero_on_domain(
2143 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2144 OneAff = isl_aff_add_constant_si(OneAff, 1);
2145 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2146 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2147
2148 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2149
2150 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002151 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002152}
2153
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002154static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2155 isl_set *Domain = MA->getStatement()->getDomain();
2156 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2157 return isl_set_reset_tuple_id(Domain);
2158}
2159
Tobias Grosserc80d6972016-09-02 06:33:33 +00002160/// Wrapper function to calculate minimal/maximal accesses to each array.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002161static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002162 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002163 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002164
2165 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2166 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002167 Locations = isl_union_set_coalesce(Locations);
2168 Locations = isl_union_set_detect_equalities(Locations);
2169 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002170 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002171 isl_union_set_free(Locations);
2172 return Valid;
2173}
2174
Tobias Grosserc80d6972016-09-02 06:33:33 +00002175/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002176///
2177///{
2178
Tobias Grosserc80d6972016-09-02 06:33:33 +00002179/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002180static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2181 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2182 : RN->getNodeAs<BasicBlock>();
2183}
2184
Tobias Grosserc80d6972016-09-02 06:33:33 +00002185/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002186static inline BasicBlock *
2187getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002188 if (RN->isSubRegion()) {
2189 assert(idx == 0);
2190 return RN->getNodeAs<Region>()->getExit();
2191 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002192 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002193}
2194
Tobias Grosserc80d6972016-09-02 06:33:33 +00002195/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002196static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2197 if (!RN->isSubRegion())
2198 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2199
2200 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2201 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2202 while (L && NonAffineSubRegion->contains(L))
2203 L = L->getParentLoop();
2204 return L;
2205}
2206
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002207static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2208 if (!RN->isSubRegion())
2209 return 1;
2210
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002211 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002212 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002213}
2214
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002215static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2216 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002217 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002218 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002219 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002220 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002221 return true;
2222 return false;
2223}
2224
Johannes Doerfert96425c22015-08-30 21:13:53 +00002225///}
2226
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002227static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2228 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002229 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002230 isl_id *DimId =
2231 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2232 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2233}
2234
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002235__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002236 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002237}
2238
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002239__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002240 auto DIt = DomainMap.find(BB);
2241 if (DIt != DomainMap.end())
2242 return isl_set_copy(DIt->getSecond());
2243
2244 auto &RI = *R.getRegionInfo();
2245 auto *BBR = RI.getRegionFor(BB);
2246 while (BBR->getEntry() == BB)
2247 BBR = BBR->getParent();
2248 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002249}
2250
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002251bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002252
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002253 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002254 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002255 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2256 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002257 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002258
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002259 while (LD-- >= 0) {
2260 S = addDomainDimId(S, LD + 1, L);
2261 L = L->getParentLoop();
2262 }
2263
Johannes Doerferta3519512016-04-23 13:02:23 +00002264 // Initialize the invalid domain.
2265 auto *EntryStmt = getStmtFor(EntryBB);
2266 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2267
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002268 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002269
Johannes Doerfert432658d2016-01-26 11:01:41 +00002270 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002271 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002272
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002273 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002274 return false;
2275
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002276 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002277 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002278
2279 // Error blocks and blocks dominated by them have been assumed to never be
2280 // executed. Representing them in the Scop does not add any value. In fact,
2281 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002282 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002283 // will cause problems when building up a ScopStmt for them.
2284 // Furthermore, basic blocks dominated by error blocks may reference
2285 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002286 // can themselves not be constructed properly. To this end we will replace
2287 // the domains of error blocks and those only reachable via error blocks
2288 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002289 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002290 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002291 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002292 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002293
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002294 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002295}
2296
Michael Kruse586e5792016-07-08 12:38:28 +00002297// If the loop is nonaffine/boxed, return the first non-boxed surrounding loop
2298// for Polly. If the loop is affine, return the loop itself. Do not call
2299// `getSCEVAtScope()` on the result of `getFirstNonBoxedLoopFor()`, as we need
2300// to analyze the memory accesses of the nonaffine/boxed loops.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002301static Loop *getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI,
2302 const BoxedLoopsSetTy &BoxedLoops) {
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002303 auto *L = LI.getLoopFor(BB);
2304 while (BoxedLoops.count(L))
2305 L = L->getParentLoop();
2306 return L;
2307}
2308
Tobias Grosserc80d6972016-09-02 06:33:33 +00002309/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002310/// to be compatible to domains constructed for loop @p NewL.
2311///
2312/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2313/// edge from @p OldL to @p NewL.
2314static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2315 __isl_take isl_set *Dom,
2316 Loop *OldL, Loop *NewL) {
2317
2318 // If the loops are the same there is nothing to do.
2319 if (NewL == OldL)
2320 return Dom;
2321
2322 int OldDepth = S.getRelativeLoopDepth(OldL);
2323 int NewDepth = S.getRelativeLoopDepth(NewL);
2324 // If both loops are non-affine loops there is nothing to do.
2325 if (OldDepth == -1 && NewDepth == -1)
2326 return Dom;
2327
2328 // Distinguish three cases:
2329 // 1) The depth is the same but the loops are not.
2330 // => One loop was left one was entered.
2331 // 2) The depth increased from OldL to NewL.
2332 // => One loop was entered, none was left.
2333 // 3) The depth decreased from OldL to NewL.
2334 // => Loops were left were difference of the depths defines how many.
2335 if (OldDepth == NewDepth) {
2336 assert(OldL->getParentLoop() == NewL->getParentLoop());
2337 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2338 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2339 Dom = addDomainDimId(Dom, NewDepth, NewL);
2340 } else if (OldDepth < NewDepth) {
2341 assert(OldDepth + 1 == NewDepth);
2342 auto &R = S.getRegion();
2343 (void)R;
2344 assert(NewL->getParentLoop() == OldL ||
2345 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2346 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2347 Dom = addDomainDimId(Dom, NewDepth, NewL);
2348 } else {
2349 assert(OldDepth > NewDepth);
2350 int Diff = OldDepth - NewDepth;
2351 int NumDim = isl_set_n_dim(Dom);
2352 assert(NumDim >= Diff);
2353 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2354 }
2355
2356 return Dom;
2357}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002358
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002359bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2360 LoopInfo &LI) {
2361 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002362
2363 ReversePostOrderTraversal<Region *> RTraversal(R);
2364 for (auto *RN : RTraversal) {
2365
2366 // Recurse for affine subregions but go on for basic blocks and non-affine
2367 // subregions.
2368 if (RN->isSubRegion()) {
2369 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002370 if (!isNonAffineSubRegion(SubRegion)) {
2371 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002372 continue;
2373 }
2374 }
2375
2376 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2377 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002378 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002379 isl_set *&Domain = DomainMap[BB];
2380 assert(Domain && "Cannot propagate a nullptr");
2381
Johannes Doerferta3519512016-04-23 13:02:23 +00002382 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002383 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002384 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002385
Johannes Doerferta3519512016-04-23 13:02:23 +00002386 if (!IsInvalidBlock) {
2387 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002388 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002389 isl_set_free(InvalidDomain);
2390 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002391 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2392 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2393 AS_RESTRICTION);
2394 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002395 }
2396
Johannes Doerferta3519512016-04-23 13:02:23 +00002397 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002398 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002399 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002400 }
2401
Johannes Doerferta3519512016-04-23 13:02:23 +00002402 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002403 auto *TI = BB->getTerminator();
2404 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2405 for (unsigned u = 0; u < NumSuccs; u++) {
2406 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002407 auto *SuccStmt = getStmtFor(SuccBB);
2408
2409 // Skip successors outside the SCoP.
2410 if (!SuccStmt)
2411 continue;
2412
Johannes Doerferte4459a22016-04-25 13:34:50 +00002413 // Skip backedges.
2414 if (DT.dominates(SuccBB, BB))
2415 continue;
2416
Johannes Doerferta3519512016-04-23 13:02:23 +00002417 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2418 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2419 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2420 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2421 SuccInvalidDomain =
2422 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2423 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2424 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2425 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002426
Michael Krusebc150122016-05-02 12:25:18 +00002427 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002428 // In case this happens we will bail.
Michael Krusebc150122016-05-02 12:25:18 +00002429 if (NumConjucts < MaxDisjunctionsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002430 continue;
2431
Johannes Doerferta3519512016-04-23 13:02:23 +00002432 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002433 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002434 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002435 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002436
2437 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002438 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002439
2440 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002441}
2442
Johannes Doerfert642594a2016-04-04 07:57:39 +00002443void Scop::propagateDomainConstraintsToRegionExit(
2444 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002445 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002446
2447 // Check if the block @p BB is the entry of a region. If so we propagate it's
2448 // domain to the exit block of the region. Otherwise we are done.
2449 auto *RI = R.getRegionInfo();
2450 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2451 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002452 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002453 return;
2454
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002455 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002456 // Do not propagate the domain if there is a loop backedge inside the region
2457 // that would prevent the exit block from beeing executed.
2458 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002459 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002460 SmallVector<BasicBlock *, 4> LatchBBs;
2461 BBLoop->getLoopLatches(LatchBBs);
2462 for (auto *LatchBB : LatchBBs)
2463 if (BB != LatchBB && BBReg->contains(LatchBB))
2464 return;
2465 L = L->getParentLoop();
2466 }
2467
2468 auto *Domain = DomainMap[BB];
2469 assert(Domain && "Cannot propagate a nullptr");
2470
2471 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2472
2473 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2474 // adjust the domain before we can propagate it.
2475 auto *AdjustedDomain =
2476 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2477 auto *&ExitDomain = DomainMap[ExitBB];
2478
2479 // If the exit domain is not yet created we set it otherwise we "add" the
2480 // current domain.
2481 ExitDomain =
2482 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2483
Johannes Doerferta3519512016-04-23 13:02:23 +00002484 // Initialize the invalid domain.
2485 auto *ExitStmt = getStmtFor(ExitBB);
2486 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2487
Johannes Doerfert642594a2016-04-04 07:57:39 +00002488 FinishedExitBlocks.insert(ExitBB);
2489}
2490
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002491bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2492 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002493 // To create the domain for each block in R we iterate over all blocks and
2494 // subregions in R and propagate the conditions under which the current region
2495 // element is executed. To this end we iterate in reverse post order over R as
2496 // it ensures that we first visit all predecessors of a region node (either a
2497 // basic block or a subregion) before we visit the region node itself.
2498 // Initially, only the domain for the SCoP region entry block is set and from
2499 // there we propagate the current domain to all successors, however we add the
2500 // condition that the successor is actually executed next.
2501 // As we are only interested in non-loop carried constraints here we can
2502 // simply skip loop back edges.
2503
Johannes Doerfert642594a2016-04-04 07:57:39 +00002504 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002505 ReversePostOrderTraversal<Region *> RTraversal(R);
2506 for (auto *RN : RTraversal) {
2507
2508 // Recurse for affine subregions but go on for basic blocks and non-affine
2509 // subregions.
2510 if (RN->isSubRegion()) {
2511 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002512 if (!isNonAffineSubRegion(SubRegion)) {
2513 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002514 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002515 continue;
2516 }
2517 }
2518
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002519 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002520 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002521
Johannes Doerfert96425c22015-08-30 21:13:53 +00002522 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002523 TerminatorInst *TI = BB->getTerminator();
2524
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002525 if (isa<UnreachableInst>(TI))
2526 continue;
2527
Johannes Doerfertf5673802015-10-01 23:48:18 +00002528 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002529 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002530 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002531 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002532
Johannes Doerfert642594a2016-04-04 07:57:39 +00002533 auto *BBLoop = getRegionNodeLoop(RN, LI);
2534 // Propagate the domain from BB directly to blocks that have a superset
2535 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002536 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002537
2538 // If all successors of BB have been set a domain through the propagation
2539 // above we do not need to build condition sets but can just skip this
2540 // block. However, it is important to note that this is a local property
2541 // with regards to the region @p R. To this end FinishedExitBlocks is a
2542 // local variable.
2543 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2544 return FinishedExitBlocks.count(SuccBB);
2545 };
2546 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2547 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002548
2549 // Build the condition sets for the successor nodes of the current region
2550 // node. If it is a non-affine subregion we will always execute the single
2551 // exit node, hence the single entry node domain is the condition set. For
2552 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002553 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002554 if (RN->isSubRegion())
2555 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002556 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2557 ConditionSets))
2558 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002559
2560 // Now iterate over the successors and set their initial domain based on
2561 // their condition set. We skip back edges here and have to be careful when
2562 // we leave a loop not to keep constraints over a dimension that doesn't
2563 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002564 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002565 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002566 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002567 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002568
Johannes Doerfert535de032016-04-19 14:49:05 +00002569 auto *SuccStmt = getStmtFor(SuccBB);
2570 // Skip blocks outside the region.
2571 if (!SuccStmt) {
2572 isl_set_free(CondSet);
2573 continue;
2574 }
2575
Johannes Doerfert642594a2016-04-04 07:57:39 +00002576 // If we propagate the domain of some block to "SuccBB" we do not have to
2577 // adjust the domain.
2578 if (FinishedExitBlocks.count(SuccBB)) {
2579 isl_set_free(CondSet);
2580 continue;
2581 }
2582
Johannes Doerfert96425c22015-08-30 21:13:53 +00002583 // Skip back edges.
2584 if (DT.dominates(SuccBB, BB)) {
2585 isl_set_free(CondSet);
2586 continue;
2587 }
2588
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002589 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002590 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002591 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002592
2593 // Set the domain for the successor or merge it with an existing domain in
2594 // case there are multiple paths (without loop back edges) to the
2595 // successor block.
2596 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002597
Johannes Doerferta3519512016-04-23 13:02:23 +00002598 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002599 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002600 } else {
2601 // Initialize the invalid domain.
2602 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2603 SuccDomain = CondSet;
2604 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002605
Michael Krusebc150122016-05-02 12:25:18 +00002606 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002607 // In case this happens we will clean up and bail.
Michael Krusebc150122016-05-02 12:25:18 +00002608 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctionsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002609 continue;
2610
2611 invalidate(COMPLEXITY, DebugLoc());
2612 while (++u < ConditionSets.size())
2613 isl_set_free(ConditionSets[u]);
2614 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002615 }
2616 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002617
2618 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002619}
2620
Michael Krused56b90a2016-09-01 09:03:27 +00002621__isl_give isl_set *
2622Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2623 __isl_keep isl_set *Domain,
2624 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002625 // If @p BB is the ScopEntry we are done
2626 if (R.getEntry() == BB)
2627 return isl_set_universe(isl_set_get_space(Domain));
2628
2629 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002630 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002631
2632 // The region info of this function.
2633 auto &RI = *R.getRegionInfo();
2634
2635 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2636
2637 // A domain to collect all predecessor domains, thus all conditions under
2638 // which the block is executed. To this end we start with the empty domain.
2639 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2640
2641 // Set of regions of which the entry block domain has been propagated to BB.
2642 // all predecessors inside any of the regions can be skipped.
2643 SmallSet<Region *, 8> PropagatedRegions;
2644
2645 for (auto *PredBB : predecessors(BB)) {
2646 // Skip backedges.
2647 if (DT.dominates(BB, PredBB))
2648 continue;
2649
2650 // If the predecessor is in a region we used for propagation we can skip it.
2651 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2652 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2653 PredBBInRegion)) {
2654 continue;
2655 }
2656
2657 // Check if there is a valid region we can use for propagation, thus look
2658 // for a region that contains the predecessor and has @p BB as exit block.
2659 auto *PredR = RI.getRegionFor(PredBB);
2660 while (PredR->getExit() != BB && !PredR->contains(BB))
2661 PredR->getParent();
2662
2663 // If a valid region for propagation was found use the entry of that region
2664 // for propagation, otherwise the PredBB directly.
2665 if (PredR->getExit() == BB) {
2666 PredBB = PredR->getEntry();
2667 PropagatedRegions.insert(PredR);
2668 }
2669
Johannes Doerfert41cda152016-04-08 10:32:26 +00002670 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002671 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2672 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2673
2674 PredDom = isl_set_union(PredDom, PredBBDom);
2675 }
2676
2677 return PredDom;
2678}
2679
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002680bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2681 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002682 // Iterate over the region R and propagate the domain constrains from the
2683 // predecessors to the current node. In contrast to the
2684 // buildDomainsWithBranchConstraints function, this one will pull the domain
2685 // information from the predecessors instead of pushing it to the successors.
2686 // Additionally, we assume the domains to be already present in the domain
2687 // map here. However, we iterate again in reverse post order so we know all
2688 // predecessors have been visited before a block or non-affine subregion is
2689 // visited.
2690
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002691 ReversePostOrderTraversal<Region *> RTraversal(R);
2692 for (auto *RN : RTraversal) {
2693
2694 // Recurse for affine subregions but go on for basic blocks and non-affine
2695 // subregions.
2696 if (RN->isSubRegion()) {
2697 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002698 if (!isNonAffineSubRegion(SubRegion)) {
2699 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002700 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002701 continue;
2702 }
2703 }
2704
2705 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002706 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002707 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002708
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002709 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002710 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002711 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002712 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002713
Johannes Doerfert642594a2016-04-04 07:57:39 +00002714 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002715 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002716 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2717 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002718 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002719
2720 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002721}
2722
Tobias Grosserc80d6972016-09-02 06:33:33 +00002723/// Create a map to map from a given iteration to a subsequent iteration.
2724///
2725/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2726/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002727/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002728///
2729/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002730static __isl_give isl_map *
2731createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2732 auto *MapSpace = isl_space_map_from_set(SetSpace);
2733 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2734 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2735 if (u != Dim)
2736 NextIterationMap =
2737 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2738 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2739 C = isl_constraint_set_constant_si(C, 1);
2740 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2741 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2742 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2743 return NextIterationMap;
2744}
2745
Johannes Doerfert297c7202016-05-10 13:06:42 +00002746bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002747 int LoopDepth = getRelativeLoopDepth(L);
2748 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002749
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002750 BasicBlock *HeaderBB = L->getHeader();
2751 assert(DomainMap.count(HeaderBB));
2752 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002753
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002754 isl_map *NextIterationMap =
2755 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002756
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002757 isl_set *UnionBackedgeCondition =
2758 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002759
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002760 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2761 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002762
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002763 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002764
2765 // If the latch is only reachable via error statements we skip it.
2766 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2767 if (!LatchBBDom)
2768 continue;
2769
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002770 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002771
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002772 TerminatorInst *TI = LatchBB->getTerminator();
2773 BranchInst *BI = dyn_cast<BranchInst>(TI);
2774 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002775 BackedgeCondition = isl_set_copy(LatchBBDom);
2776 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002777 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002778 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002779 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
2780 ConditionSets))
2781 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002782
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002783 // Free the non back edge condition set as we do not need it.
2784 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002785
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002786 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002787 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002788
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002789 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2790 assert(LatchLoopDepth >= LoopDepth);
2791 BackedgeCondition =
2792 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2793 LatchLoopDepth - LoopDepth);
2794 UnionBackedgeCondition =
2795 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002796 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002797
2798 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2799 for (int i = 0; i < LoopDepth; i++)
2800 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2801
2802 isl_set *UnionBackedgeConditionComplement =
2803 isl_set_complement(UnionBackedgeCondition);
2804 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2805 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2806 UnionBackedgeConditionComplement =
2807 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2808 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2809 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2810
2811 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2812 HeaderBBDom = Parts.second;
2813
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002814 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2815 // the bounded assumptions to the context as they are already implied by the
2816 // <nsw> tag.
2817 if (Affinator.hasNSWAddRecForLoop(L)) {
2818 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002819 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002820 }
2821
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002822 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002823 recordAssumption(INFINITELOOP, UnboundedCtx,
2824 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002825 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002826}
2827
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002828MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
2829 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2830 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2831 if (!PointerBase)
2832 return nullptr;
2833
2834 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase->getValue());
2835 if (!PointerBaseInst)
2836 return nullptr;
2837
2838 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2839 if (!BasePtrStmt)
2840 return nullptr;
2841
2842 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2843}
2844
2845bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2846 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00002847 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
2848 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
2849 bool Hoistable = NHCtx != nullptr;
2850 isl_set_free(NHCtx);
2851 return !Hoistable;
2852 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002853
2854 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2855 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2856 if (auto *BasePtrInst = dyn_cast<Instruction>(PointerBase->getValue()))
2857 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00002858 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002859
2860 return false;
2861}
2862
Johannes Doerfert5210da52016-06-02 11:06:54 +00002863bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002864 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00002865 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002866
2867 if (buildAliasGroups(AA))
Johannes Doerfert5210da52016-06-02 11:06:54 +00002868 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002869
2870 // If a problem occurs while building the alias groups we need to delete
2871 // this SCoP and pretend it wasn't valid in the first place. To this end
2872 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002873 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002874
2875 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2876 << " could not be created as the number of parameters involved "
2877 "is too high. The SCoP will be "
2878 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2879 "the maximal number of parameters but be advised that the "
2880 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00002881 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002882}
2883
Johannes Doerfert9143d672014-09-27 11:02:39 +00002884bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002885 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002886 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002887 // for all memory accesses inside the SCoP.
2888 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002889 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002890 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002891 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002892 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002893 // if their access domains intersect, otherwise they are in different
2894 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002895 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002896 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002897 // and maximal accesses to each array of a group in read only and non
2898 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002899 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2900
2901 AliasSetTracker AST(AA);
2902
2903 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002904 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002905 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002906
2907 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002908 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002909 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2910 isl_set_free(StmtDomain);
2911 if (StmtDomainEmpty)
2912 continue;
2913
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002914 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002915 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002916 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002917 if (!MA->isRead())
2918 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002919 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002920 if (MA->isRead() && isa<MemTransferInst>(Acc))
2921 PtrToAcc[cast<MemTransferInst>(Acc)->getSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002922 else
2923 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002924 AST.add(Acc);
2925 }
2926 }
2927
2928 SmallVector<AliasGroupTy, 4> AliasGroups;
2929 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002930 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002931 continue;
2932 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002933 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002934 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002935 if (AG.size() < 2)
2936 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002937 AliasGroups.push_back(std::move(AG));
2938 }
2939
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002940 // Split the alias groups based on their domain.
2941 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2942 AliasGroupTy NewAG;
2943 AliasGroupTy &AG = AliasGroups[u];
2944 AliasGroupTy::iterator AGI = AG.begin();
2945 isl_set *AGDomain = getAccessDomain(*AGI);
2946 while (AGI != AG.end()) {
2947 MemoryAccess *MA = *AGI;
2948 isl_set *MADomain = getAccessDomain(MA);
2949 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2950 NewAG.push_back(MA);
2951 AGI = AG.erase(AGI);
2952 isl_set_free(MADomain);
2953 } else {
2954 AGDomain = isl_set_union(AGDomain, MADomain);
2955 AGI++;
2956 }
2957 }
2958 if (NewAG.size() > 1)
2959 AliasGroups.push_back(std::move(NewAG));
2960 isl_set_free(AGDomain);
2961 }
2962
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002963 auto &F = getFunction();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002964 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002965 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2966 for (AliasGroupTy &AG : AliasGroups) {
2967 NonReadOnlyBaseValues.clear();
2968 ReadOnlyPairs.clear();
2969
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002970 if (AG.size() < 2) {
2971 AG.clear();
2972 continue;
2973 }
2974
Johannes Doerfert13771732014-10-01 12:40:46 +00002975 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002976 emitOptimizationRemarkAnalysis(
2977 F.getContext(), DEBUG_TYPE, F,
2978 (*II)->getAccessInstruction()->getDebugLoc(),
2979 "Possibly aliasing pointer, use restrict keyword.");
2980
Johannes Doerfert13771732014-10-01 12:40:46 +00002981 Value *BaseAddr = (*II)->getBaseAddr();
2982 if (HasWriteAccess.count(BaseAddr)) {
2983 NonReadOnlyBaseValues.insert(BaseAddr);
2984 II++;
2985 } else {
2986 ReadOnlyPairs[BaseAddr].insert(*II);
2987 II = AG.erase(II);
2988 }
2989 }
2990
2991 // If we don't have read only pointers check if there are at least two
2992 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002993 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002994 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002995 continue;
2996 }
2997
2998 // If we don't have non read only pointers clear the alias group.
2999 if (NonReadOnlyBaseValues.empty()) {
3000 AG.clear();
3001 continue;
3002 }
3003
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003004 // Check if we have non-affine accesses left, if so bail out as we cannot
3005 // generate a good access range yet.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003006 for (auto *MA : AG) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003007 if (!MA->isAffine()) {
3008 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3009 return false;
3010 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003011 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
3012 addRequiredInvariantLoad(
3013 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3014 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003015 for (auto &ReadOnlyPair : ReadOnlyPairs)
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003016 for (auto *MA : ReadOnlyPair.second) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003017 if (!MA->isAffine()) {
3018 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3019 return false;
3020 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003021 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
3022 addRequiredInvariantLoad(
3023 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3024 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003025
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003026 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003027 MinMaxAliasGroups.emplace_back();
3028 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3029 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
3030 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3031 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003032
3033 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003034
3035 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00003036 for (MemoryAccess *MA : AG)
3037 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003038
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003039 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
3040 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003041
3042 // Bail out if the number of values we need to compare is too large.
3043 // This is important as the number of comparisions grows quadratically with
3044 // the number of values we need to compare.
Johannes Doerfert5210da52016-06-02 11:06:54 +00003045 if (!Valid || (MinMaxAccessesNonReadOnly.size() + ReadOnlyPairs.size() >
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003046 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003047 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003048
3049 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003050 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003051 Accesses = isl_union_map_empty(getParamSpace());
3052
3053 for (const auto &ReadOnlyPair : ReadOnlyPairs)
3054 for (MemoryAccess *MA : ReadOnlyPair.second)
3055 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
3056
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003057 Valid =
3058 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003059
3060 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003061 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003062 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003063
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003064 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003065}
3066
Tobias Grosserc80d6972016-09-02 06:33:33 +00003067/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003068static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003069 // Start with the smallest loop containing the entry and expand that
3070 // loop until it contains all blocks in the region. If there is a loop
3071 // containing all blocks in the region check if it is itself contained
3072 // and if so take the parent loop as it will be the smallest containing
3073 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003074 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003075 while (L) {
3076 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003077 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003078 AllContained &= L->contains(BB);
3079 if (AllContained)
3080 break;
3081 L = L->getParentLoop();
3082 }
3083
Johannes Doerfertef744432016-05-23 12:42:38 +00003084 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003085}
3086
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003087Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003088 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003089 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003090 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003091 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3092 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3093 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3094 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003095 if (IslOnErrorAbort)
3096 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003097 buildContext();
3098}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003099
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003100void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT,
3101 LoopInfo &LI) {
3102 buildInvariantEquivalenceClasses();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003103
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003104 if (!buildDomains(&R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003105 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003106
Johannes Doerfertff68f462016-04-19 14:49:42 +00003107 addUserAssumptions(AC, DT, LI);
3108
Johannes Doerfert26404542016-05-10 12:19:47 +00003109 // Remove empty statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003110 // Exit early in case there are no executable statements left in this scop.
Michael Kruse977d38b2016-07-22 17:31:17 +00003111 simplifySCoP(false);
Michael Kruseafe06702015-10-02 16:33:27 +00003112 if (Stmts.empty())
3113 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003114
Michael Krusecac948e2015-10-02 13:53:07 +00003115 // The ScopStmts now have enough information to initialize themselves.
3116 for (ScopStmt &Stmt : Stmts)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003117 Stmt.init(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00003118
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003119 // Check early for profitability. Afterwards it cannot change anymore,
3120 // only the runtime context could become infeasible.
3121 if (!isProfitable()) {
3122 invalidate(PROFITABLE, DebugLoc());
Tobias Grosser8286b832015-11-02 11:29:32 +00003123 return;
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003124 }
3125
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003126 buildSchedule(LI);
Tobias Grosser8286b832015-11-02 11:29:32 +00003127
3128 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003129 realignParams();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003130 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003131
3132 // After the context was fully constructed, thus all our knowledge about
3133 // the parameters is in there, we add all recorded assumptions to the
3134 // assumed/invalid context.
3135 addRecordedAssumptions();
3136
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003137 simplifyContexts();
Johannes Doerfert5210da52016-06-02 11:06:54 +00003138 if (!buildAliasChecks(AA))
3139 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003140
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003141 hoistInvariantLoads();
3142 verifyInvariantLoads();
Michael Kruse977d38b2016-07-22 17:31:17 +00003143 simplifySCoP(true);
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003144
3145 // Check late for a feasible runtime context because profitability did not
3146 // change.
3147 if (!hasFeasibleRuntimeContext()) {
3148 invalidate(PROFITABLE, DebugLoc());
3149 return;
3150 }
Tobias Grosser75805372011-04-29 06:27:02 +00003151}
3152
3153Scop::~Scop() {
3154 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003155 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003156 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003157 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003158
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003159 for (auto &It : ParameterIds)
3160 isl_id_free(It.second);
3161
Johannes Doerfert96425c22015-08-30 21:13:53 +00003162 for (auto It : DomainMap)
3163 isl_set_free(It.second);
3164
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003165 for (auto &AS : RecordedAssumptions)
3166 isl_set_free(AS.Set);
3167
Johannes Doerfertb164c792014-09-18 11:17:17 +00003168 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003169 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003170 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003171 isl_pw_multi_aff_free(MMA.first);
3172 isl_pw_multi_aff_free(MMA.second);
3173 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003174 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003175 isl_pw_multi_aff_free(MMA.first);
3176 isl_pw_multi_aff_free(MMA.second);
3177 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003178 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003179
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003180 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003181 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003182
3183 // Explicitly release all Scop objects and the underlying isl objects before
3184 // we relase the isl context.
3185 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003186 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003187 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003188 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003189 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003190}
3191
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003192void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003193 // Check all array accesses for each base pointer and find a (virtual) element
3194 // size for the base pointer that divides all access functions.
3195 for (auto &Stmt : *this)
3196 for (auto *Access : Stmt) {
3197 if (!Access->isArrayKind())
3198 continue;
3199 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
3200 ScopArrayInfo::MK_Array)];
3201 if (SAI->getNumberOfDimensions() != 1)
3202 continue;
3203 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3204 auto *Subscript = Access->getSubscript(0);
3205 while (!isDivisible(Subscript, DivisibleSize, *SE))
3206 DivisibleSize /= 2;
3207 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3208 SAI->updateElementType(Ty);
3209 }
3210
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003211 for (auto &Stmt : *this)
3212 for (auto &Access : Stmt)
3213 Access->updateDimensionality();
3214}
3215
Michael Kruse977d38b2016-07-22 17:31:17 +00003216void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003217 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3218 ScopStmt &Stmt = *StmtIt;
3219
Johannes Doerfert26404542016-05-10 12:19:47 +00003220 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003221 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003222 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003223
Johannes Doerferteca9e892015-11-03 16:54:49 +00003224 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003225 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003226 bool OnlyRead = true;
3227 for (MemoryAccess *MA : Stmt) {
3228 if (MA->isRead())
3229 continue;
3230
3231 OnlyRead = false;
3232 break;
3233 }
3234
3235 RemoveStmt = OnlyRead;
3236 }
3237
Johannes Doerfert26404542016-05-10 12:19:47 +00003238 if (!RemoveStmt) {
3239 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003240 continue;
3241 }
3242
Johannes Doerfert26404542016-05-10 12:19:47 +00003243 // Remove the statement because it is unnecessary.
3244 if (Stmt.isRegionStmt())
3245 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3246 StmtMap.erase(BB);
3247 else
3248 StmtMap.erase(Stmt.getBasicBlock());
3249
3250 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003251 }
3252}
3253
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003254InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003255 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3256 if (!LInst)
3257 return nullptr;
3258
3259 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3260 LInst = cast<LoadInst>(Rep);
3261
Johannes Doerfert96e54712016-02-07 17:30:13 +00003262 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003263 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003264 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003265 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003266 continue;
3267
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003268 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003269 for (auto *MA : MAs)
3270 if (MA->getAccessInstruction() == Val)
3271 return &IAClass;
3272 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003273
3274 return nullptr;
3275}
3276
Tobias Grosserc80d6972016-09-02 06:33:33 +00003277/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003278static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003279 bool MAInvalidCtxIsEmpty,
3280 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003281 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3282 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3283 // TODO: We can provide more information for better but more expensive
3284 // results.
3285 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3286 LInst->getAlignment(), DL))
3287 return false;
3288
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003289 // If the location might be overwritten we do not hoist it unconditionally.
3290 //
3291 // TODO: This is probably to conservative.
3292 if (!NonHoistableCtxIsEmpty)
3293 return false;
3294
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003295 // If a dereferencable load is in a statement that is modeled precisely we can
3296 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003297 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003298 return true;
3299
3300 // Even if the statement is not modeled precisely we can hoist the load if it
3301 // does not involve any parameters that might have been specilized by the
3302 // statement domain.
3303 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3304 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3305 return false;
3306 return true;
3307}
3308
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003309void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003310
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003311 if (InvMAs.empty())
3312 return;
3313
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003314 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003315 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003316
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003317 // Get the context under which the statement is executed but remove the error
3318 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003319 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003320 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003321
Michael Krusebc150122016-05-02 12:25:18 +00003322 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctionsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003323 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003324 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3325 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003326 for (auto &InvMA : InvMAs)
3327 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003328 return;
3329 }
3330
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003331 // Project out all parameters that relate to loads in the statement. Otherwise
3332 // we could have cyclic dependences on the constraints under which the
3333 // hoisted loads are executed and we could not determine an order in which to
3334 // pre-load them. This happens because not only lower bounds are part of the
3335 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003336 for (auto &InvMA : InvMAs) {
3337 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003338 Instruction *AccInst = MA->getAccessInstruction();
3339 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003340 SetVector<Value *> Values;
3341 for (const SCEV *Parameter : Parameters) {
3342 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003343 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003344 if (!Values.count(AccInst))
3345 continue;
3346
3347 if (isl_id *ParamId = getIdForParam(Parameter)) {
3348 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3349 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3350 isl_id_free(ParamId);
3351 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003352 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003353 }
3354 }
3355
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003356 for (auto &InvMA : InvMAs) {
3357 auto *MA = InvMA.MA;
3358 auto *NHCtx = InvMA.NonHoistableCtx;
3359
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003360 // Check for another invariant access that accesses the same location as
3361 // MA and if found consolidate them. Otherwise create a new equivalence
3362 // class at the end of InvariantEquivClasses.
3363 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003364 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003365 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3366
Johannes Doerfert85676e32016-04-23 14:32:34 +00003367 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003368 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003369 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3370
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003371 isl_set *MACtx;
3372 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003373 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3374 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003375 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003376 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003377 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003378 } else {
3379 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003380 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003381 MACtx = isl_set_gist_params(MACtx, getContext());
3382 }
3383
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003384 bool Consolidated = false;
3385 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003386 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003387 continue;
3388
Johannes Doerfertdf880232016-03-03 12:26:58 +00003389 // If the pointer and the type is equal check if the access function wrt.
3390 // to the domain is equal too. It can happen that the domain fixes
3391 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003392 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003393 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003394 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003395 if (!MAs.empty()) {
3396 auto *LastMA = MAs.front();
3397
3398 auto *AR = isl_map_range(MA->getAccessRelation());
3399 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3400 bool SameAR = isl_set_is_equal(AR, LastAR);
3401 isl_set_free(AR);
3402 isl_set_free(LastAR);
3403
3404 if (!SameAR)
3405 continue;
3406 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003407
3408 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003409 MAs.push_front(MA);
3410
Johannes Doerfertdf880232016-03-03 12:26:58 +00003411 Consolidated = true;
3412
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003413 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003414 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003415 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003416 IAClassDomainCtx =
3417 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003418 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003419 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003420 break;
3421 }
3422
3423 if (Consolidated)
3424 continue;
3425
3426 // If we did not consolidate MA, thus did not find an equivalence class
3427 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003428 InvariantEquivClasses.emplace_back(
3429 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003430 }
3431
3432 isl_set_free(DomainCtx);
3433}
3434
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003435__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3436 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003437 // TODO: Loads that are not loop carried, hence are in a statement with
3438 // zero iterators, are by construction invariant, though we
3439 // currently "hoist" them anyway. This is necessary because we allow
3440 // them to be treated as parameters (e.g., in conditions) and our code
3441 // generation would otherwise use the old value.
3442
3443 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003444 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003445
3446 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003447 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003448
3449 // Skip accesses that have an invariant base pointer which is defined but
3450 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3451 // returns a pointer that is used as a base address. However, as we want
3452 // to hoist indirect pointers, we allow the base pointer to be defined in
3453 // the region if it is also a memory access. Each ScopArrayInfo object
3454 // that has a base pointer origin has a base pointer that is loaded and
3455 // that it is invariant, thus it will be hoisted too. However, if there is
3456 // no base pointer origin we check that the base pointer is defined
3457 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003458 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003459 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003460 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003461
3462 // Skip accesses in non-affine subregions as they might not be executed
3463 // under the same condition as the entry of the non-affine subregion.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003464 if (BB != LI->getParent())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003465 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003466
3467 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003468 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003469
3470 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3471 Stmt.getNumIterators())) {
3472 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003473 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003474 }
3475
3476 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3477 isl_set *AccessRange = isl_map_range(AccessRelation);
3478
3479 isl_union_map *Written = isl_union_map_intersect_range(
3480 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003481 auto *WrittenCtx = isl_union_map_params(Written);
3482 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003483
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003484 if (!IsWritten)
3485 return WrittenCtx;
3486
3487 WrittenCtx = isl_set_remove_divs(WrittenCtx);
3488 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctionsInDomain;
3489 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3490 isl_set_free(WrittenCtx);
3491 return nullptr;
3492 }
3493
3494 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3495 AS_RESTRICTION);
3496 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003497}
3498
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003499void Scop::verifyInvariantLoads() {
3500 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003501 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003502 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003503 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003504 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003505 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3506 return;
3507 }
3508 }
3509}
3510
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003511void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003512 if (!PollyInvariantLoadHoisting)
3513 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003514
Tobias Grosser0865e7752016-02-29 07:29:42 +00003515 isl_union_map *Writes = getWrites();
3516 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003517 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003518
Tobias Grosser0865e7752016-02-29 07:29:42 +00003519 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003520 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3521 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003522
3523 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003524 for (auto InvMA : InvariantAccesses)
3525 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003526 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003527 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003528 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003529}
3530
Roman Gareevd7754a12016-07-30 09:25:51 +00003531const ScopArrayInfo *Scop::getOrCreateScopArrayInfo(
3532 Value *BasePtr, Type *ElementType, ArrayRef<const SCEV *> Sizes,
3533 ScopArrayInfo::MemoryKind Kind, const char *BaseName) {
3534 assert((BasePtr || BaseName) &&
3535 "BasePtr and BaseName can not be nullptr at the same time.");
3536 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3537 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3538 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003539 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003540 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003541 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003542 DL, this, BaseName));
3543 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003544 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003545 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003546 // In case of mismatching array sizes, we bail out by setting the run-time
3547 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003548 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003549 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003550 }
Tobias Grosserab671442015-05-23 05:58:27 +00003551 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003552}
3553
Roman Gareevd7754a12016-07-30 09:25:51 +00003554const ScopArrayInfo *
3555Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3556 const std::vector<unsigned> &Sizes) {
3557 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3558 std::vector<const SCEV *> SCEVSizes;
3559
3560 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003561 if (size)
3562 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3563 else
3564 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003565
3566 auto *SAI =
3567 getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3568 ScopArrayInfo::MK_Array, BaseName.c_str());
3569 return SAI;
3570}
3571
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003572const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003573 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003574 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003575 assert(SAI && "No ScopArrayInfo available for this base pointer");
3576 return SAI;
3577}
3578
Tobias Grosser74394f02013-01-14 22:40:23 +00003579std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003580
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003581std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003582 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003583 return stringFromIslObj(AssumedContext);
3584}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003585
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003586std::string Scop::getInvalidContextStr() const {
3587 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003588}
Tobias Grosser75805372011-04-29 06:27:02 +00003589
3590std::string Scop::getNameStr() const {
3591 std::string ExitName, EntryName;
3592 raw_string_ostream ExitStr(ExitName);
3593 raw_string_ostream EntryStr(EntryName);
3594
Tobias Grosserf240b482014-01-09 10:42:15 +00003595 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003596 EntryStr.str();
3597
3598 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003599 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003600 ExitStr.str();
3601 } else
3602 ExitName = "FunctionExit";
3603
3604 return EntryName + "---" + ExitName;
3605}
3606
Tobias Grosser74394f02013-01-14 22:40:23 +00003607__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003608__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003609 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003610}
3611
Tobias Grossere86109f2013-10-29 21:05:49 +00003612__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003613 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003614 return isl_set_copy(AssumedContext);
3615}
3616
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003617bool Scop::isProfitable() const {
3618 if (PollyProcessUnprofitable)
3619 return true;
3620
3621 if (!hasFeasibleRuntimeContext())
3622 return false;
3623
3624 if (isEmpty())
3625 return false;
3626
3627 unsigned OptimizableStmtsOrLoops = 0;
3628 for (auto &Stmt : *this) {
3629 if (Stmt.getNumIterators() == 0)
3630 continue;
3631
3632 bool ContainsArrayAccs = false;
3633 bool ContainsScalarAccs = false;
3634 for (auto *MA : Stmt) {
3635 if (MA->isRead())
3636 continue;
3637 ContainsArrayAccs |= MA->isArrayKind();
3638 ContainsScalarAccs |= MA->isScalarKind();
3639 }
3640
3641 if (ContainsArrayAccs && !ContainsScalarAccs)
3642 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3643 }
3644
3645 return OptimizableStmtsOrLoops > 1;
3646}
3647
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003648bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003649 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003650 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003651 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3652 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3653 isl_set_is_subset(PositiveContext, NegativeContext));
3654 isl_set_free(PositiveContext);
3655 if (!IsFeasible) {
3656 isl_set_free(NegativeContext);
3657 return false;
3658 }
3659
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003660 auto *DomainContext = isl_union_set_params(getDomains());
3661 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003662 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003663 isl_set_free(NegativeContext);
3664 isl_set_free(DomainContext);
3665
Johannes Doerfert43788c52015-08-20 05:58:56 +00003666 return IsFeasible;
3667}
3668
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003669static std::string toString(AssumptionKind Kind) {
3670 switch (Kind) {
3671 case ALIASING:
3672 return "No-aliasing";
3673 case INBOUNDS:
3674 return "Inbounds";
3675 case WRAPPING:
3676 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00003677 case UNSIGNED:
3678 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003679 case COMPLEXITY:
3680 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003681 case PROFITABLE:
3682 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003683 case ERRORBLOCK:
3684 return "No-error";
3685 case INFINITELOOP:
3686 return "Finite loop";
3687 case INVARIANTLOAD:
3688 return "Invariant load";
3689 case DELINEARIZATION:
3690 return "Delinearization";
3691 }
3692 llvm_unreachable("Unknown AssumptionKind!");
3693}
3694
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003695bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
3696 if (Sign == AS_ASSUMPTION) {
3697 if (isl_set_is_subset(Context, Set))
3698 return false;
3699
3700 if (isl_set_is_subset(AssumedContext, Set))
3701 return false;
3702 } else {
3703 if (isl_set_is_disjoint(Set, Context))
3704 return false;
3705
3706 if (isl_set_is_subset(Set, InvalidContext))
3707 return false;
3708 }
3709 return true;
3710}
3711
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003712bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3713 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003714 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
3715 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003716
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003717 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003718 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3719 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003720 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003721 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003722}
3723
3724void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003725 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003726 // Simplify the assumptions/restrictions first.
3727 Set = isl_set_gist_params(Set, getContext());
3728
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003729 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3730 isl_set_free(Set);
3731 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003732 }
3733
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003734 if (Sign == AS_ASSUMPTION) {
3735 AssumedContext = isl_set_intersect(AssumedContext, Set);
3736 AssumedContext = isl_set_coalesce(AssumedContext);
3737 } else {
3738 InvalidContext = isl_set_union(InvalidContext, Set);
3739 InvalidContext = isl_set_coalesce(InvalidContext);
3740 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003741}
3742
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003743void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003744 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
3745 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003746}
3747
3748void Scop::addRecordedAssumptions() {
3749 while (!RecordedAssumptions.empty()) {
3750 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003751
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003752 if (!AS.BB) {
3753 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
3754 continue;
3755 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003756
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003757 // If the domain was deleted the assumptions are void.
3758 isl_set *Dom = getDomainConditions(AS.BB);
3759 if (!Dom) {
3760 isl_set_free(AS.Set);
3761 continue;
3762 }
3763
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003764 // If a basic block was given use its domain to simplify the assumption.
3765 // In case of restrictions we know they only have to hold on the domain,
3766 // thus we can intersect them with the domain of the block. However, for
3767 // assumptions the domain has to imply them, thus:
3768 // _ _____
3769 // Dom => S <==> A v B <==> A - B
3770 //
3771 // To avoid the complement we will register A - B as a restricton not an
3772 // assumption.
3773 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003774 if (AS.Sign == AS_RESTRICTION)
3775 S = isl_set_params(isl_set_intersect(S, Dom));
3776 else /* (AS.Sign == AS_ASSUMPTION) */
3777 S = isl_set_params(isl_set_subtract(Dom, S));
3778
3779 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003780 }
3781}
3782
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003783void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003784 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003785}
3786
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003787__isl_give isl_set *Scop::getInvalidContext() const {
3788 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003789}
3790
Tobias Grosser75805372011-04-29 06:27:02 +00003791void Scop::printContext(raw_ostream &OS) const {
3792 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003793 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003794
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003795 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003796 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003797
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003798 OS.indent(4) << "Invalid Context:\n";
3799 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003800
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003801 unsigned Dim = 0;
3802 for (const SCEV *Parameter : Parameters)
3803 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003804}
3805
Johannes Doerfertb164c792014-09-18 11:17:17 +00003806void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003807 int noOfGroups = 0;
3808 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003809 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003810 noOfGroups += 1;
3811 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003812 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003813 }
3814
Tobias Grosserbb853c22015-07-25 12:31:03 +00003815 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003816 if (MinMaxAliasGroups.empty()) {
3817 OS.indent(8) << "n/a\n";
3818 return;
3819 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003820
Tobias Grosserbb853c22015-07-25 12:31:03 +00003821 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003822
3823 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003824 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003825 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003826 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003827 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3828 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003829 }
3830 OS << " ]]\n";
3831 }
3832
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003833 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003834 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003835 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003836 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003837 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3838 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003839 }
3840 OS << " ]]\n";
3841 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003842 }
3843}
3844
Tobias Grosser75805372011-04-29 06:27:02 +00003845void Scop::printStatements(raw_ostream &OS) const {
3846 OS << "Statements {\n";
3847
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003848 for (const ScopStmt &Stmt : *this)
3849 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003850
3851 OS.indent(4) << "}\n";
3852}
3853
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003854void Scop::printArrayInfo(raw_ostream &OS) const {
3855 OS << "Arrays {\n";
3856
Tobias Grosserab671442015-05-23 05:58:27 +00003857 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00003858 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003859
3860 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003861
3862 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3863
3864 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00003865 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003866
3867 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003868}
3869
Tobias Grosser75805372011-04-29 06:27:02 +00003870void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003871 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003872 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003873 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003874 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003875 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003876 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003877 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003878 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003879 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003880 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003881 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
3882 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003883 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003884 }
3885 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003886 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003887 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003888 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003889 printStatements(OS.indent(4));
3890}
3891
3892void Scop::dump() const { print(dbgs()); }
3893
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003894isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003895
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003896__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
3897 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003898 // First try to use the SCEVAffinator to generate a piecewise defined
3899 // affine function from @p E in the context of @p BB. If that tasks becomes to
3900 // complex the affinator might return a nullptr. In such a case we invalidate
3901 // the SCoP and return a dummy value. This way we do not need to add error
3902 // handling cdoe to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003903 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003904 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00003905 // TODO: We could use a heuristic and either use:
3906 // SCEVAffinator::takeNonNegativeAssumption
3907 // or
3908 // SCEVAffinator::interpretAsUnsigned
3909 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003910 if (NonNegative)
3911 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003912 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003913 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003914
3915 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
3916 invalidate(COMPLEXITY, DL);
3917 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003918}
3919
Tobias Grosser808cd692015-07-14 09:33:13 +00003920__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003921 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003922
Tobias Grosser808cd692015-07-14 09:33:13 +00003923 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003924 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003925
3926 return Domain;
3927}
3928
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003929__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
3930 PWACtx PWAC = getPwAff(E, BB);
3931 isl_set_free(PWAC.second);
3932 return PWAC.first;
3933}
3934
Tobias Grossere5a35142015-11-12 14:07:09 +00003935__isl_give isl_union_map *
3936Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3937 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003938
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003939 for (ScopStmt &Stmt : *this) {
3940 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003941 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003942 continue;
3943
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003944 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003945 isl_map *AccessDomain = MA->getAccessRelation();
3946 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003947 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003948 }
3949 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003950 return isl_union_map_coalesce(Accesses);
3951}
3952
3953__isl_give isl_union_map *Scop::getMustWrites() {
3954 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003955}
3956
3957__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003958 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003959}
3960
Tobias Grosser37eb4222014-02-20 21:43:54 +00003961__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003962 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003963}
3964
3965__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003966 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003967}
3968
Tobias Grosser2ac23382015-11-12 14:07:13 +00003969__isl_give isl_union_map *Scop::getAccesses() {
3970 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3971}
3972
Roman Gareevb3224ad2016-09-14 06:26:09 +00003973// Check whether @p Node is an extension node.
3974//
3975// @return true if @p Node is an extension node.
3976isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
3977 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
3978 return isl_bool_error;
3979 else
3980 return isl_bool_true;
3981}
3982
3983bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
3984 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
3985 nullptr) == isl_stat_error;
3986}
3987
Tobias Grosser808cd692015-07-14 09:33:13 +00003988__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003989 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00003990 if (containsExtensionNode(Tree)) {
3991 isl_schedule_free(Tree);
3992 return nullptr;
3993 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00003994 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00003995 isl_schedule_free(Tree);
3996 return S;
3997}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003998
Tobias Grosser808cd692015-07-14 09:33:13 +00003999__isl_give isl_schedule *Scop::getScheduleTree() const {
4000 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4001 getDomains());
4002}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004003
Tobias Grosser808cd692015-07-14 09:33:13 +00004004void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4005 auto *S = isl_schedule_from_domain(getDomains());
4006 S = isl_schedule_insert_partial_schedule(
4007 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4008 isl_schedule_free(Schedule);
4009 Schedule = S;
4010}
4011
4012void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4013 isl_schedule_free(Schedule);
4014 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004015}
4016
4017bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4018 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004019 for (ScopStmt &Stmt : *this) {
4020 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004021 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4022 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4023
4024 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4025 isl_union_set_free(StmtDomain);
4026 isl_union_set_free(NewStmtDomain);
4027 continue;
4028 }
4029
4030 Changed = true;
4031
4032 isl_union_set_free(StmtDomain);
4033 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4034
4035 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004036 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004037 isl_union_set_free(NewStmtDomain);
4038 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004039 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004040 }
4041 isl_union_set_free(Domain);
4042 return Changed;
4043}
4044
Tobias Grosser75805372011-04-29 06:27:02 +00004045ScalarEvolution *Scop::getSE() const { return SE; }
4046
Tobias Grosser808cd692015-07-14 09:33:13 +00004047struct MapToDimensionDataTy {
4048 int N;
4049 isl_union_pw_multi_aff *Res;
4050};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004051
Tobias Grosserc80d6972016-09-02 06:33:33 +00004052// Create a function that maps the elements of 'Set' to its N-th dimension and
4053// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004054//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004055// @param Set The input set.
4056// @param User->N The dimension to map to.
4057// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004058//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004059// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004060static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4061 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4062 int Dim;
4063 isl_space *Space;
4064 isl_pw_multi_aff *PMA;
4065
4066 Dim = isl_set_dim(Set, isl_dim_set);
4067 Space = isl_set_get_space(Set);
4068 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4069 Dim - Data->N);
4070 if (Data->N > 1)
4071 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4072 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4073
4074 isl_set_free(Set);
4075
4076 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004077}
4078
Tobias Grosserc80d6972016-09-02 06:33:33 +00004079// Create an isl_multi_union_aff that defines an identity mapping from the
4080// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004081//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004082// # Example:
4083//
4084// Domain: { A[i,j]; B[i,j,k] }
4085// N: 1
4086//
4087// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4088//
4089// @param USet A union set describing the elements for which to generate a
4090// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004091// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004092// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004093static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004094mapToDimension(__isl_take isl_union_set *USet, int N) {
4095 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004096 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004097 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004098
Tobias Grosser808cd692015-07-14 09:33:13 +00004099 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004100
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004101 auto *Space = isl_union_set_get_space(USet);
4102 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004103
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004104 Data = {N, PwAff};
4105
4106 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004107 (void)Res;
4108
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004109 assert(Res == isl_stat_ok);
4110
4111 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004112 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4113}
4114
Tobias Grosser316b5b22015-11-11 19:28:14 +00004115void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00004116 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00004117 Stmts.emplace_back(*this, *BB);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004118 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004119 StmtMap[BB] = Stmt;
4120 } else {
4121 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00004122 Stmts.emplace_back(*this, *R);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004123 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004124 for (BasicBlock *BB : R->blocks())
4125 StmtMap[BB] = Stmt;
4126 }
Tobias Grosser808cd692015-07-14 09:33:13 +00004127}
4128
Roman Gareevb3224ad2016-09-14 06:26:09 +00004129ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4130 __isl_take isl_map *TargetRel,
4131 __isl_take isl_set *Domain) {
4132 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4133 CopyStmtsNum++;
4134 return &(Stmts.back());
4135}
4136
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004137void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004138 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004139 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004140 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004141 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4142 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004143}
4144
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004145/// To generate a schedule for the elements in a Region we traverse the Region
4146/// in reverse-post-order and add the contained RegionNodes in traversal order
4147/// to the schedule of the loop that is currently at the top of the LoopStack.
4148/// For loop-free codes, this results in a correct sequential ordering.
4149///
4150/// Example:
4151/// bb1(0)
4152/// / \.
4153/// bb2(1) bb3(2)
4154/// \ / \.
4155/// bb4(3) bb5(4)
4156/// \ /
4157/// bb6(5)
4158///
4159/// Including loops requires additional processing. Whenever a loop header is
4160/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4161/// from an empty schedule, we first process all RegionNodes that are within
4162/// this loop and complete the sequential schedule at this loop-level before
4163/// processing about any other nodes. To implement this
4164/// loop-nodes-first-processing, the reverse post-order traversal is
4165/// insufficient. Hence, we additionally check if the traversal yields
4166/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4167/// These region-nodes are then queue and only traverse after the all nodes
4168/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004169void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004170 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004171
4172 ReversePostOrderTraversal<Region *> RTraversal(R);
4173 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4174 std::deque<RegionNode *> DelayList;
4175 bool LastRNWaiting = false;
4176
4177 // Iterate over the region @p R in reverse post-order but queue
4178 // sub-regions/blocks iff they are not part of the last encountered but not
4179 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4180 // that we queued the last sub-region/block from the reverse post-order
4181 // iterator. If it is set we have to explore the next sub-region/block from
4182 // the iterator (if any) to guarantee progress. If it is not set we first try
4183 // the next queued sub-region/blocks.
4184 while (!WorkList.empty() || !DelayList.empty()) {
4185 RegionNode *RN;
4186
4187 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4188 RN = WorkList.front();
4189 WorkList.pop_front();
4190 LastRNWaiting = false;
4191 } else {
4192 RN = DelayList.front();
4193 DelayList.pop_front();
4194 }
4195
4196 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004197 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004198 L = OuterScopLoop;
4199
Tobias Grosser151ae322016-04-03 19:36:52 +00004200 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004201 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004202 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004203 LastRNWaiting = true;
4204 DelayList.push_back(RN);
4205 continue;
4206 }
4207 LoopStack.push_back({L, nullptr, 0});
4208 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004209 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004210 }
4211
4212 return;
4213}
4214
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004215void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004216
Tobias Grosser8362c262016-01-06 15:30:06 +00004217 if (RN->isSubRegion()) {
4218 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004219 if (!isNonAffineSubRegion(LocalRegion)) {
4220 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004221 return;
4222 }
4223 }
Michael Kruse046dde42015-08-10 13:01:57 +00004224
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004225 auto &LoopData = LoopStack.back();
4226 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004227
Michael Kruse6f7721f2016-02-24 22:08:19 +00004228 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004229 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4230 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004231 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004232 }
4233
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004234 // Check if we just processed the last node in this loop. If we did, finalize
4235 // the loop by:
4236 //
4237 // - adding new schedule dimensions
4238 // - folding the resulting schedule into the parent loop schedule
4239 // - dropping the loop schedule from the LoopStack.
4240 //
4241 // Then continue to check surrounding loops, which might also have been
4242 // completed by this node.
4243 while (LoopData.L &&
4244 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004245 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004246 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004247
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004248 LoopStack.pop_back();
4249 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004250
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004251 if (Schedule) {
4252 auto *Domain = isl_schedule_get_domain(Schedule);
4253 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4254 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4255 NextLoopData.Schedule =
4256 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004257 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004258
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004259 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4260 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004261 }
Tobias Grosser75805372011-04-29 06:27:02 +00004262}
4263
Michael Kruse6f7721f2016-02-24 22:08:19 +00004264ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004265 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004266 if (StmtMapIt == StmtMap.end())
4267 return nullptr;
4268 return StmtMapIt->second;
4269}
4270
Michael Kruse6f7721f2016-02-24 22:08:19 +00004271ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4272 if (RN->isSubRegion())
4273 return getStmtFor(RN->getNodeAs<Region>());
4274 return getStmtFor(RN->getNodeAs<BasicBlock>());
4275}
4276
4277ScopStmt *Scop::getStmtFor(Region *R) const {
4278 ScopStmt *Stmt = getStmtFor(R->getEntry());
4279 assert(!Stmt || Stmt->getRegion() == R);
4280 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004281}
4282
Johannes Doerfert96425c22015-08-30 21:13:53 +00004283int Scop::getRelativeLoopDepth(const Loop *L) const {
4284 Loop *OuterLoop =
4285 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4286 if (!OuterLoop)
4287 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004288 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4289}
4290
Roman Gareevd7754a12016-07-30 09:25:51 +00004291ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4292 for (auto &SAI : arrays()) {
4293 if (SAI->getName() == BaseName)
4294 return SAI;
4295 }
4296 return nullptr;
4297}
4298
Johannes Doerfert99191c72016-05-31 09:41:04 +00004299//===----------------------------------------------------------------------===//
4300void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4301 AU.addRequired<LoopInfoWrapperPass>();
4302 AU.addRequired<RegionInfoPass>();
4303 AU.addRequired<DominatorTreeWrapperPass>();
4304 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4305 AU.addRequiredTransitive<ScopDetection>();
4306 AU.addRequired<AAResultsWrapperPass>();
4307 AU.addRequired<AssumptionCacheTracker>();
4308 AU.setPreservesAll();
4309}
4310
4311bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4312 auto &SD = getAnalysis<ScopDetection>();
4313
4314 if (!SD.isMaxRegionInScop(*R))
4315 return false;
4316
4317 Function *F = R->getEntry()->getParent();
4318 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4319 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4320 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4321 auto const &DL = F->getParent()->getDataLayout();
4322 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4323 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
4324
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004325 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4326 S = SB.getScop(); // take ownership of scop object
Tobias Grosser75805372011-04-29 06:27:02 +00004327 return false;
4328}
4329
Johannes Doerfert99191c72016-05-31 09:41:04 +00004330void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004331 if (S)
4332 S->print(OS);
4333 else
4334 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004335}
Tobias Grosser75805372011-04-29 06:27:02 +00004336
Johannes Doerfert99191c72016-05-31 09:41:04 +00004337char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004338
Johannes Doerfert99191c72016-05-31 09:41:04 +00004339Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4340
4341INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004342 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004343 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004344INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004345INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004346INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004347INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004348INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004349INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004350INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004351INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004352 "Polly - Create polyhedral description of Scops", false,
4353 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004354
4355//===----------------------------------------------------------------------===//
4356void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4357 AU.addRequired<LoopInfoWrapperPass>();
4358 AU.addRequired<RegionInfoPass>();
4359 AU.addRequired<DominatorTreeWrapperPass>();
4360 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4361 AU.addRequiredTransitive<ScopDetection>();
4362 AU.addRequired<AAResultsWrapperPass>();
4363 AU.addRequired<AssumptionCacheTracker>();
4364 AU.setPreservesAll();
4365}
4366
4367bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4368 auto &SD = getAnalysis<ScopDetection>();
4369
4370 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4371 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4372 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4373 auto const &DL = F.getParent()->getDataLayout();
4374 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4375 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4376
4377 /// Create polyhedral descripton of scops for all the valid regions of a
4378 /// function.
4379 for (auto &It : SD) {
4380 Region *R = const_cast<Region *>(It);
4381 if (!SD.isMaxRegionInScop(*R))
4382 continue;
4383
4384 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004385 std::unique_ptr<Scop> S = SB.getScop();
4386 if (!S)
4387 continue;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004388 bool Inserted =
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004389 RegionToScopMap.insert(std::make_pair(R, std::move(S))).second;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004390 assert(Inserted && "Building Scop for the same region twice!");
4391 (void)Inserted;
4392 }
4393 return false;
4394}
4395
4396void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4397 for (auto &It : RegionToScopMap) {
4398 if (It.second)
4399 It.second->print(OS);
4400 else
4401 OS << "Invalid Scop!\n";
4402 }
4403}
4404
4405char ScopInfoWrapperPass::ID = 0;
4406
4407Pass *polly::createScopInfoWrapperPassPass() {
4408 return new ScopInfoWrapperPass();
4409}
4410
4411INITIALIZE_PASS_BEGIN(
4412 ScopInfoWrapperPass, "polly-function-scops",
4413 "Polly - Create polyhedral description of all Scops of a function", false,
4414 false);
4415INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
4416INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
4417INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4418INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4419INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4420INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4421INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4422INITIALIZE_PASS_END(
4423 ScopInfoWrapperPass, "polly-function-scops",
4424 "Polly - Create polyhedral description of all Scops of a function", false,
4425 false)