blob: 0c37e2682132c2eb36d100f49d9bc785e2fcd276 [file] [log] [blame]
Johannes Doerfert58a7c752015-09-28 09:48:53 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
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"
Tobias Grosser75805372011-04-29 06:27:02 +000023#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000024#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000025#include "polly/Support/ScopHelper.h"
Tobias Grosser9737c7b2015-11-22 11:06:51 +000026#include "llvm/ADT/DepthFirstIterator.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000027#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000028#include "llvm/ADT/PostOrderIterator.h"
29#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000030#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000031#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000032#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000033#include "llvm/Analysis/AliasAnalysis.h"
Johannes Doerfert2af10e22015-11-12 03:25:01 +000034#include "llvm/Analysis/AssumptionCache.h"
Johannes Doerfert1dc12af2016-04-23 12:59:18 +000035#include "llvm/Analysis/Loads.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000036#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000037#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000038#include "llvm/Analysis/RegionIterator.h"
39#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000040#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000041#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000042#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000043#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000044#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000045#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000046#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000047#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000048#include "isl/schedule.h"
49#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000050#include "isl/set.h"
51#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000052#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000053#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000054#include <sstream>
55#include <string>
56#include <vector>
57
58using namespace llvm;
59using namespace polly;
60
Chandler Carruth95fef942014-04-22 03:30:19 +000061#define DEBUG_TYPE "polly-scops"
62
Tobias Grosser74394f02013-01-14 22:40:23 +000063STATISTIC(ScopFound, "Number of valid Scops");
64STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000065
Tobias Grosser75dc40c2015-12-20 13:31:48 +000066// The maximal number of basic sets we allow during domain construction to
67// be created. More complex scops will result in very high compile time and
68// are also unlikely to result in good code
Michael Krusebc150122016-05-02 12:25:18 +000069static int const MaxDisjunctionsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +000070
Johannes Doerfert2f705842016-04-12 16:09:44 +000071static cl::opt<bool> PollyRemarksMinimal(
72 "polly-remarks-minimal",
73 cl::desc("Do not emit remarks about assumptions that are known"),
74 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
75
Michael Kruse7bf39442015-09-10 12:46:52 +000076static cl::opt<bool> ModelReadOnlyScalars(
77 "polly-analyze-read-only-scalars",
78 cl::desc("Model read-only scalar values in the scop description"),
79 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
80
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000081// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000082// operations can overflow easily. Additive reductions and bit operations
83// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000084static cl::opt<bool> DisableMultiplicativeReductions(
85 "polly-disable-multiplicative-reductions",
86 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
87 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000088
Johannes Doerfert9143d672014-09-27 11:02:39 +000089static cl::opt<unsigned> RunTimeChecksMaxParameters(
90 "polly-rtc-max-parameters",
91 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
92 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
93
Tobias Grosser71500722015-03-28 15:11:14 +000094static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
95 "polly-rtc-max-arrays-per-group",
96 cl::desc("The maximal number of arrays to compare in each alias group."),
97 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +000098
Tobias Grosser8a9c2352015-08-16 10:19:29 +000099static cl::opt<std::string> UserContextStr(
100 "polly-context", cl::value_desc("isl parameter set"),
101 cl::desc("Provide additional constraints on the context parameters"),
102 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000103
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000104static cl::opt<bool> DetectReductions("polly-detect-reductions",
105 cl::desc("Detect and exploit reductions"),
106 cl::Hidden, cl::ZeroOrMore,
107 cl::init(true), cl::cat(PollyCategory));
108
Tobias Grosser2937b592016-04-29 11:43:20 +0000109static cl::opt<bool>
110 IslOnErrorAbort("polly-on-isl-error-abort",
111 cl::desc("Abort if an isl error is encountered"),
112 cl::init(true), cl::cat(PollyCategory));
113
Michael Kruse7bf39442015-09-10 12:46:52 +0000114//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000115
Michael Kruse046dde42015-08-10 13:01:57 +0000116// Create a sequence of two schedules. Either argument may be null and is
117// interpreted as the empty schedule. Can also return null if both schedules are
118// empty.
119static __isl_give isl_schedule *
120combineInSequence(__isl_take isl_schedule *Prev,
121 __isl_take isl_schedule *Succ) {
122 if (!Prev)
123 return Succ;
124 if (!Succ)
125 return Prev;
126
127 return isl_schedule_sequence(Prev, Succ);
128}
129
Johannes Doerferte7044942015-02-24 11:58:30 +0000130static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
131 const ConstantRange &Range,
132 int dim,
133 enum isl_dim_type type) {
134 isl_val *V;
135 isl_ctx *ctx = isl_set_get_ctx(S);
136
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000137 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
138 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000139 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000140 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
141
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000142 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000143 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000144 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000145 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000146 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
147
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000148 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000149 return isl_set_union(SLB, SUB);
150 else
151 return isl_set_intersect(SLB, SUB);
152}
153
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000154static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
155 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
156 if (!BasePtrLI)
157 return nullptr;
158
Johannes Doerfert952b5302016-05-23 12:40:48 +0000159 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000160 return nullptr;
161
162 ScalarEvolution &SE = *S->getSE();
163
164 auto *OriginBaseSCEV =
165 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
166 if (!OriginBaseSCEV)
167 return nullptr;
168
169 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
170 if (!OriginBaseSCEVUnknown)
171 return nullptr;
172
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000173 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000174 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000175}
176
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000177ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000178 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000179 const DataLayout &DL, Scop *S)
180 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000181 std::string BasePtrName =
Tobias Grossera535dff2015-12-13 19:59:01 +0000182 getIslCompatibleName("MemRef_", BasePtr, Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000183 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000184
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000185 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000186 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
187 if (BasePtrOriginSAI)
188 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000189}
190
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000191__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000192 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000193 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
194 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
195 return Space;
196}
197
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000198void ScopArrayInfo::updateElementType(Type *NewElementType) {
199 if (NewElementType == ElementType)
200 return;
201
Tobias Grosserd840fc72016-02-04 13:18:42 +0000202 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
203 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
204
Johannes Doerferta7920982016-02-25 14:08:48 +0000205 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000206 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000207
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000208 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
209 ElementType = NewElementType;
210 } else {
211 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
212 ElementType = IntegerType::get(ElementType->getContext(), GCD);
213 }
214}
215
216bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000217 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
218 int ExtraDimsNew = NewSizes.size() - SharedDims;
219 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000220 for (int i = 0; i < SharedDims; i++)
221 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
222 return false;
223
224 if (DimensionSizes.size() >= NewSizes.size())
225 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000226
227 DimensionSizes.clear();
228 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
229 NewSizes.end());
230 for (isl_pw_aff *Size : DimensionSizesPw)
231 isl_pw_aff_free(Size);
232 DimensionSizesPw.clear();
233 for (const SCEV *Expr : DimensionSizes) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000234 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000235 DimensionSizesPw.push_back(Size);
236 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000237 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000238}
239
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000240ScopArrayInfo::~ScopArrayInfo() {
241 isl_id_free(Id);
242 for (isl_pw_aff *Size : DimensionSizesPw)
243 isl_pw_aff_free(Size);
244}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000245
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000246std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
247
248int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000249 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000250}
251
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000252__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
253 return isl_id_copy(Id);
254}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000255
256void ScopArrayInfo::dump() const { print(errs()); }
257
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000258void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000259 OS.indent(8) << *getElementType() << " " << getName();
260 if (getNumberOfDimensions() > 0)
261 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000262 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000263 OS << "[";
264
Tobias Grosser26253842015-11-10 14:24:21 +0000265 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000266 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000267 OS << " " << Size << " ";
268 isl_pw_aff_free(Size);
269 } else {
270 OS << *getDimensionSize(u);
271 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000272
273 OS << "]";
274 }
275
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000276 OS << ";";
277
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000278 if (BasePtrOriginSAI)
279 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
280
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000281 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000282}
283
284const ScopArrayInfo *
285ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
286 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
287 assert(Id && "Output dimension didn't have an ID");
288 return getFromId(Id);
289}
290
291const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
292 void *User = isl_id_get_user(Id);
293 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
294 isl_id_free(Id);
295 return SAI;
296}
297
Michael Kruse3b425ff2016-04-11 14:34:08 +0000298void MemoryAccess::wrapConstantDimensions() {
299 auto *SAI = getScopArrayInfo();
300 auto *ArraySpace = SAI->getSpace();
301 auto *Ctx = isl_space_get_ctx(ArraySpace);
302 unsigned DimsArray = SAI->getNumberOfDimensions();
303
304 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
305 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
306 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
307
308 // Begin with last dimension, to iteratively carry into higher dimensions.
309 for (int i = DimsArray - 1; i > 0; i--) {
310 auto *DimSize = SAI->getDimensionSize(i);
311 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
312
313 // This transformation is not applicable to dimensions with dynamic size.
314 if (!DimSizeCst)
315 continue;
316
317 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
318 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
319 isl_dim_set, i);
320 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
321 isl_dim_set, i - 1);
322
323 // Compute: index % size
324 // Modulo must apply in the divide of the previous iteration, if any.
325 auto *Modulo = isl_aff_copy(Var);
326 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
327 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
328
329 // Compute: floor(index / size)
330 auto *Divide = Var;
331 Divide = isl_aff_div(
332 Divide,
333 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
334 Divide = isl_aff_floor(Divide);
335 Divide = isl_aff_add(Divide, PrevVar);
336 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
337
338 // Apply Modulo and Divide.
339 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
340 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
341 }
342
343 // Apply all modulo/divides on the accesses.
344 AccessRelation =
345 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
346 AccessRelation = isl_map_detect_equalities(AccessRelation);
347 isl_local_space_free(LArraySpace);
348}
349
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000350void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000351 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000352 auto *ArraySpace = SAI->getSpace();
353 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000354 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000355
356 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
357 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
358 auto DimsMissing = DimsArray - DimsAccess;
359
Michael Kruse375cb5f2016-02-24 22:08:24 +0000360 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000361 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000362 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000363 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000364
Johannes Doerferta90943d2016-02-21 16:37:25 +0000365 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000366 isl_set_universe(AccessSpace),
367 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000368
369 for (unsigned i = 0; i < DimsMissing; i++)
370 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
371
372 for (unsigned i = DimsMissing; i < DimsArray; i++)
373 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
374
375 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000376
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000377 // For the non delinearized arrays, divide the access function of the last
378 // subscript by the size of the elements in the array.
379 //
380 // A stride one array access in C expressed as A[i] is expressed in
381 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
382 // two subsequent values of 'i' index two values that are stored next to
383 // each other in memory. By this division we make this characteristic
384 // obvious again. If the base pointer was accessed with offsets not divisible
385 // by the accesses element size, we will have choosen a smaller ArrayElemSize
386 // that divides the offsets of all accesses to this base pointer.
387 if (DimsAccess == 1) {
388 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
389 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
390 }
391
Michael Kruse3b425ff2016-04-11 14:34:08 +0000392 // We currently do this only if we added at least one dimension, which means
393 // some dimension's indices have not been specified, an indicator that some
394 // index values have been added together.
395 // TODO: Investigate general usefulness; Effect on unit tests is to make index
396 // expressions more complicated.
397 if (DimsMissing)
398 wrapConstantDimensions();
399
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000400 if (!isAffine())
401 computeBoundsOnAccessRelation(ArrayElemSize);
402
Tobias Grosserd840fc72016-02-04 13:18:42 +0000403 // Introduce multi-element accesses in case the type loaded by this memory
404 // access is larger than the canonical element type of the array.
405 //
406 // An access ((float *)A)[i] to an array char *A is modeled as
407 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000408 if (ElemBytes > ArrayElemSize) {
409 assert(ElemBytes % ArrayElemSize == 0 &&
410 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000411 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000412 isl_set_universe(isl_space_copy(ArraySpace)),
413 isl_set_universe(isl_space_copy(ArraySpace)));
414 for (unsigned i = 0; i < DimsArray - 1; i++)
415 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
416
Tobias Grosserd840fc72016-02-04 13:18:42 +0000417 isl_constraint *C;
418 isl_local_space *LS;
419
420 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000421 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
422
423 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
424 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000425 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000426 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
427 Map = isl_map_add_constraint(Map, C);
428
429 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000430 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000431 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
432 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
433 Map = isl_map_add_constraint(Map, C);
434 AccessRelation = isl_map_apply_range(AccessRelation, Map);
435 }
436
437 isl_space_free(ArraySpace);
438
Roman Gareev10595a12016-01-08 14:01:59 +0000439 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000440}
441
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000442const std::string
443MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
444 switch (RT) {
445 case MemoryAccess::RT_NONE:
446 llvm_unreachable("Requested a reduction operator string for a memory "
447 "access which isn't a reduction");
448 case MemoryAccess::RT_ADD:
449 return "+";
450 case MemoryAccess::RT_MUL:
451 return "*";
452 case MemoryAccess::RT_BOR:
453 return "|";
454 case MemoryAccess::RT_BXOR:
455 return "^";
456 case MemoryAccess::RT_BAND:
457 return "&";
458 }
459 llvm_unreachable("Unknown reduction type");
460 return "";
461}
462
Johannes Doerfertf6183392014-07-01 20:52:51 +0000463/// @brief Return the reduction type for a given binary operator
464static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
465 const Instruction *Load) {
466 if (!BinOp)
467 return MemoryAccess::RT_NONE;
468 switch (BinOp->getOpcode()) {
469 case Instruction::FAdd:
470 if (!BinOp->hasUnsafeAlgebra())
471 return MemoryAccess::RT_NONE;
472 // Fall through
473 case Instruction::Add:
474 return MemoryAccess::RT_ADD;
475 case Instruction::Or:
476 return MemoryAccess::RT_BOR;
477 case Instruction::Xor:
478 return MemoryAccess::RT_BXOR;
479 case Instruction::And:
480 return MemoryAccess::RT_BAND;
481 case Instruction::FMul:
482 if (!BinOp->hasUnsafeAlgebra())
483 return MemoryAccess::RT_NONE;
484 // Fall through
485 case Instruction::Mul:
486 if (DisableMultiplicativeReductions)
487 return MemoryAccess::RT_NONE;
488 return MemoryAccess::RT_MUL;
489 default:
490 return MemoryAccess::RT_NONE;
491 }
492}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000493
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000494/// @brief Derive the individual index expressions from a GEP instruction
495///
496/// This function optimistically assumes the GEP references into a fixed size
497/// array. If this is actually true, this function returns a list of array
498/// subscript expressions as SCEV as well as a list of integers describing
499/// the size of the individual array dimensions. Both lists have either equal
500/// length of the size list is one element shorter in case there is no known
501/// size available for the outermost array dimension.
502///
503/// @param GEP The GetElementPtr instruction to analyze.
504///
505/// @return A tuple with the subscript expressions and the dimension sizes.
506static std::tuple<std::vector<const SCEV *>, std::vector<int>>
507getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
508 std::vector<const SCEV *> Subscripts;
509 std::vector<int> Sizes;
510
511 Type *Ty = GEP->getPointerOperandType();
512
513 bool DroppedFirstDim = false;
514
Michael Kruse26ed65e2015-09-24 17:32:49 +0000515 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000516
517 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
518
519 if (i == 1) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000520 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000521 Ty = PtrTy->getElementType();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000522 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000523 Ty = ArrayTy->getElementType();
524 } else {
525 Subscripts.clear();
526 Sizes.clear();
527 break;
528 }
Johannes Doerferta90943d2016-02-21 16:37:25 +0000529 if (auto *Const = dyn_cast<SCEVConstant>(Expr))
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000530 if (Const->getValue()->isZero()) {
531 DroppedFirstDim = true;
532 continue;
533 }
534 Subscripts.push_back(Expr);
535 continue;
536 }
537
Johannes Doerferta90943d2016-02-21 16:37:25 +0000538 auto *ArrayTy = dyn_cast<ArrayType>(Ty);
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000539 if (!ArrayTy) {
540 Subscripts.clear();
541 Sizes.clear();
542 break;
543 }
544
545 Subscripts.push_back(Expr);
546 if (!(DroppedFirstDim && i == 2))
547 Sizes.push_back(ArrayTy->getNumElements());
548
549 Ty = ArrayTy->getElementType();
550 }
551
552 return std::make_tuple(Subscripts, Sizes);
553}
554
Tobias Grosser75805372011-04-29 06:27:02 +0000555MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000556 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000557 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000558 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000559 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000560}
561
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000562const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
563 isl_id *ArrayId = getArrayId();
564 void *User = isl_id_get_user(ArrayId);
565 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
566 isl_id_free(ArrayId);
567 return SAI;
568}
569
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000570__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000571 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
572}
573
Tobias Grosserd840fc72016-02-04 13:18:42 +0000574__isl_give isl_map *MemoryAccess::getAddressFunction() const {
575 return isl_map_lexmin(getAccessRelation());
576}
577
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000578__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
579 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000580 isl_map *Schedule, *ScheduledAccRel;
581 isl_union_set *UDomain;
582
583 UDomain = isl_union_set_from_set(getStatement()->getDomain());
584 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
585 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000586 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000587 return isl_pw_multi_aff_from_map(ScheduledAccRel);
588}
589
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000590__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000591 return isl_map_copy(AccessRelation);
592}
593
Johannes Doerferta99130f2014-10-13 12:58:03 +0000594std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000595 return stringFromIslObj(AccessRelation);
596}
597
Johannes Doerferta99130f2014-10-13 12:58:03 +0000598__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000599 return isl_map_get_space(AccessRelation);
600}
601
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000602__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000603 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000604}
605
Tobias Grosser6f730082015-09-05 07:46:47 +0000606std::string MemoryAccess::getNewAccessRelationStr() const {
607 return stringFromIslObj(NewAccessRelation);
608}
609
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000610__isl_give isl_basic_map *
611MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000612 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000613 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000614
Tobias Grosser084d8f72012-05-29 09:29:44 +0000615 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000616 isl_basic_set_universe(Statement->getDomainSpace()),
617 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000618}
619
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000620// Formalize no out-of-bound access assumption
621//
622// When delinearizing array accesses we optimistically assume that the
623// delinearized accesses do not access out of bound locations (the subscript
624// expression of each array evaluates for each statement instance that is
625// executed to a value that is larger than zero and strictly smaller than the
626// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000627// dimension for which we do not need to assume any upper bound. At this point
628// we formalize this assumption to ensure that at code generation time the
629// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000630//
631// To find the set of constraints necessary to avoid out of bound accesses, we
632// first build the set of data locations that are not within array bounds. We
633// then apply the reverse access relation to obtain the set of iterations that
634// may contain invalid accesses and reduce this set of iterations to the ones
635// that are actually executed by intersecting them with the domain of the
636// statement. If we now project out all loop dimensions, we obtain a set of
637// parameters that may cause statement instances to be executed that may
638// possibly yield out of bound memory accesses. The complement of these
639// constraints is the set of constraints that needs to be assumed to ensure such
640// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000641void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000642 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000643 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000644 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000645 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000646 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
647 isl_pw_aff *Var =
648 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
649 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
650
651 isl_set *DimOutside;
652
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000653 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000654 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000655 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
656 isl_space_dim(Space, isl_dim_set));
657 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
658 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000659
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000660 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000661
662 Outside = isl_set_union(Outside, DimOutside);
663 }
664
665 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
666 Outside = isl_set_intersect(Outside, Statement->getDomain());
667 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000668
669 // Remove divs to avoid the construction of overly complicated assumptions.
670 // Doing so increases the set of parameter combinations that are assumed to
671 // not appear. This is always save, but may make the resulting run-time check
672 // bail out more often than strictly necessary.
673 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000674 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000675 const auto &Loc = getAccessInstruction()
676 ? getAccessInstruction()->getDebugLoc()
677 : DebugLoc();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000678 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
679 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000680 isl_space_free(Space);
681}
682
Johannes Doerfertcea61932016-02-21 19:13:19 +0000683void MemoryAccess::buildMemIntrinsicAccessRelation() {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000684 assert(isa<MemIntrinsic>(getAccessInstruction()));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000685 assert(Subscripts.size() == 2 && Sizes.size() == 0);
686
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000687 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000688 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000689
690 isl_map *LengthMap;
691 if (Subscripts[1] == nullptr) {
692 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
693 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000694 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000695 LengthMap = isl_map_from_pw_aff(LengthPWA);
696 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
697 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
698 }
699 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
700 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000701 SubscriptMap =
702 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000703 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
704 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
705 getStatement()->getDomainId());
706}
707
Johannes Doerferte7044942015-02-24 11:58:30 +0000708void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
709 ScalarEvolution *SE = Statement->getParent()->getSE();
710
Johannes Doerfertcea61932016-02-21 19:13:19 +0000711 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000712 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000713 return;
714
715 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000716 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
717 return;
718
719 auto *PtrSCEV = SE->getSCEV(Ptr);
720 if (isa<SCEVCouldNotCompute>(PtrSCEV))
721 return;
722
723 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
724 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
725 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
726
727 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
728 if (Range.isFullSet())
729 return;
730
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000731 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000732 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000733 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000734 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000735 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000736
737 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000738 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000739
740 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
741 AccessRange =
742 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
743 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
744}
745
Michael Krusee2bccbb2015-09-18 19:59:43 +0000746__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000747 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000748 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000749
750 for (int i = Size - 2; i >= 0; --i) {
751 isl_space *Space;
752 isl_map *MapOne, *MapTwo;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000753 isl_pw_aff *DimSize = getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000754
755 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
756 isl_pw_aff_free(DimSize);
757 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
758
759 Space = isl_map_get_space(AccessRelation);
760 Space = isl_space_map_from_set(isl_space_range(Space));
761 Space = isl_space_align_params(Space, SpaceSize);
762
763 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
764 isl_id_free(ParamId);
765
766 MapOne = isl_map_universe(isl_space_copy(Space));
767 for (int j = 0; j < Size; ++j)
768 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
769 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
770
771 MapTwo = isl_map_universe(isl_space_copy(Space));
772 for (int j = 0; j < Size; ++j)
773 if (j < i || j > i + 1)
774 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
775
776 isl_local_space *LS = isl_local_space_from_space(Space);
777 isl_constraint *C;
778 C = isl_equality_alloc(isl_local_space_copy(LS));
779 C = isl_constraint_set_constant_si(C, -1);
780 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
781 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
782 MapTwo = isl_map_add_constraint(MapTwo, C);
783 C = isl_equality_alloc(LS);
784 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
785 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
786 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
787 MapTwo = isl_map_add_constraint(MapTwo, C);
788 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
789
790 MapOne = isl_map_union(MapOne, MapTwo);
791 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
792 }
793 return AccessRelation;
794}
795
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000796/// @brief Check if @p Expr is divisible by @p Size.
797static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000798 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000799 if (Size == 1)
800 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000801
802 // Only one factor needs to be divisible.
803 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
804 for (auto *FactorExpr : MulExpr->operands())
805 if (isDivisible(FactorExpr, Size, SE))
806 return true;
807 return false;
808 }
809
810 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
811 // to be divisble.
812 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
813 for (auto *OpExpr : NAryExpr->operands())
814 if (!isDivisible(OpExpr, Size, SE))
815 return false;
816 return true;
817 }
818
819 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
820 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
821 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
822 return MulSCEV == Expr;
823}
824
Michael Krusee2bccbb2015-09-18 19:59:43 +0000825void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
826 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000827
Johannes Doerfert85676e32016-04-23 14:32:34 +0000828 // Initialize the invalid domain which describes all iterations for which the
829 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000830 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
831 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
832 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000833
Michael Krusee2bccbb2015-09-18 19:59:43 +0000834 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000835 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000836
Michael Krusee2bccbb2015-09-18 19:59:43 +0000837 if (!isAffine()) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000838 if (isa<MemIntrinsic>(getAccessInstruction()))
839 buildMemIntrinsicAccessRelation();
840
Tobias Grosser4f967492013-06-23 05:21:18 +0000841 // We overapproximate non-affine accesses with a possible access to the
842 // whole array. For read accesses it does not make a difference, if an
843 // access must or may happen. However, for write accesses it is important to
844 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000845 if (!AccessRelation)
846 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
847
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000848 AccessRelation =
849 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000850 return;
851 }
852
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000853 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000854 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000855
Michael Krusee2bccbb2015-09-18 19:59:43 +0000856 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000857 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000858 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000859 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000860 }
861
Tobias Grosser5d51afe2016-02-02 16:46:45 +0000862 if (Sizes.size() >= 1 && !isa<SCEVConstant>(Sizes[0]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000863 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000864
Tobias Grosser79baa212014-04-10 08:38:02 +0000865 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000866 AccessRelation = isl_map_set_tuple_id(
867 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000868 AccessRelation =
869 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
870
Tobias Grosseraa660a92015-03-30 00:07:50 +0000871 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000872 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000873}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000874
Michael Krusecac948e2015-10-02 13:53:07 +0000875MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000876 AccessType AccType, Value *BaseAddress,
877 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000878 ArrayRef<const SCEV *> Subscripts,
879 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000880 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000881 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Johannes Doerfert85676e32016-04-23 14:32:34 +0000882 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
883 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()),
884 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000885 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000886 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000887 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000888 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000889
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000890 std::string IdName =
891 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000892 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
893}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000894
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000895void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +0000896 auto *Ctx = Statement->getParent()->getContext();
897 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
898 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +0000899}
900
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000901const std::string MemoryAccess::getReductionOperatorStr() const {
902 return MemoryAccess::getReductionOperatorStr(getReductionType());
903}
904
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000905__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
906
Johannes Doerfertf6183392014-07-01 20:52:51 +0000907raw_ostream &polly::operator<<(raw_ostream &OS,
908 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000909 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000910 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000911 else
912 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000913 return OS;
914}
915
Tobias Grosser75805372011-04-29 06:27:02 +0000916void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000917 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000918 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000919 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000920 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000921 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000922 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000923 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000924 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000925 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000926 break;
927 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000928 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000929 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000930 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000931 if (hasNewAccessRelation())
932 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000933}
934
Tobias Grosser74394f02013-01-14 22:40:23 +0000935void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000936
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000937__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
938 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000939 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
940 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
941 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000942}
943
Tobias Grosser75805372011-04-29 06:27:02 +0000944// Create a map in the size of the provided set domain, that maps from the
945// one element of the provided set domain to another element of the provided
946// set domain.
947// The mapping is limited to all points that are equal in all but the last
948// dimension and for which the last dimension of the input is strict smaller
949// than the last dimension of the output.
950//
951// getEqualAndLarger(set[i0, i1, ..., iX]):
952//
953// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
954// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
955//
Tobias Grosserf5338802011-10-06 00:03:35 +0000956static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000957 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000958 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000959 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000960
961 // Set all but the last dimension to be equal for the input and output
962 //
963 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
964 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000965 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000966 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000967
968 // Set the last dimension of the input to be strict smaller than the
969 // last dimension of the output.
970 //
971 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000972 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
973 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000974 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000975}
976
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000977__isl_give isl_set *
978MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000979 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000980 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000981 isl_space *Space = isl_space_range(isl_map_get_space(S));
982 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000983
Sebastian Popa00a0292012-12-18 07:46:06 +0000984 S = isl_map_reverse(S);
985 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000986
Sebastian Popa00a0292012-12-18 07:46:06 +0000987 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
988 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
989 NextScatt = isl_map_apply_domain(NextScatt, S);
990 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000991
Sebastian Popa00a0292012-12-18 07:46:06 +0000992 isl_set *Deltas = isl_map_deltas(NextScatt);
993 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000994}
995
Sebastian Popa00a0292012-12-18 07:46:06 +0000996bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000997 int StrideWidth) const {
998 isl_set *Stride, *StrideX;
999 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001000
Sebastian Popa00a0292012-12-18 07:46:06 +00001001 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001002 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001003 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1004 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1005 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1006 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001007 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001008
Tobias Grosser28dd4862012-01-24 16:42:16 +00001009 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001010 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001011
Tobias Grosser28dd4862012-01-24 16:42:16 +00001012 return IsStrideX;
1013}
1014
Sebastian Popa00a0292012-12-18 07:46:06 +00001015bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
1016 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001017}
1018
Sebastian Popa00a0292012-12-18 07:46:06 +00001019bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
1020 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001021}
1022
Tobias Grosser166c4222015-09-05 07:46:40 +00001023void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
1024 isl_map_free(NewAccessRelation);
1025 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001026}
Tobias Grosser75805372011-04-29 06:27:02 +00001027
1028//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001029
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001030__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001031 isl_set *Domain = getDomain();
1032 if (isl_set_is_empty(Domain)) {
1033 isl_set_free(Domain);
1034 return isl_map_from_aff(
1035 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1036 }
1037 auto *Schedule = getParent()->getSchedule();
1038 Schedule = isl_union_map_intersect_domain(
1039 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1040 if (isl_union_map_is_empty(Schedule)) {
1041 isl_set_free(Domain);
1042 isl_union_map_free(Schedule);
1043 return isl_map_from_aff(
1044 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1045 }
1046 auto *M = isl_map_from_union_map(Schedule);
1047 M = isl_map_coalesce(M);
1048 M = isl_map_gist_domain(M, Domain);
1049 M = isl_map_coalesce(M);
1050 return M;
1051}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001052
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001053__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1054 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001055 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1056 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001057}
1058
Tobias Grosser37eb4222014-02-20 21:43:54 +00001059void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1060 assert(isl_set_is_subset(NewDomain, Domain) &&
1061 "New domain is not a subset of old domain!");
1062 isl_set_free(Domain);
1063 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001064}
1065
Michael Krusecac948e2015-10-02 13:53:07 +00001066void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001067 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001068 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001069 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001070
Tobias Grossera535dff2015-12-13 19:59:01 +00001071 ScopArrayInfo::MemoryKind Ty;
1072 if (Access->isPHIKind())
1073 Ty = ScopArrayInfo::MK_PHI;
1074 else if (Access->isExitPHIKind())
1075 Ty = ScopArrayInfo::MK_ExitPHI;
1076 else if (Access->isValueKind())
1077 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001078 else
Tobias Grossera535dff2015-12-13 19:59:01 +00001079 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001080
Johannes Doerfertadeab372016-02-07 13:57:32 +00001081 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1082 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001083 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001084 }
1085}
1086
Michael Krusecac948e2015-10-02 13:53:07 +00001087void ScopStmt::addAccess(MemoryAccess *Access) {
1088 Instruction *AccessInst = Access->getAccessInstruction();
1089
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001090 if (Access->isArrayKind()) {
1091 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1092 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001093 } else if (Access->isValueKind() && Access->isWrite()) {
1094 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001095 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001096 assert(!ValueWrites.lookup(AccessVal));
1097
1098 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001099 } else if (Access->isValueKind() && Access->isRead()) {
1100 Value *AccessVal = Access->getAccessValue();
1101 assert(!ValueReads.lookup(AccessVal));
1102
1103 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001104 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1105 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1106 assert(!PHIWrites.lookup(PHI));
1107
1108 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001109 }
1110
1111 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001112}
1113
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001114void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001115 for (MemoryAccess *MA : *this)
1116 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001117
Johannes Doerferta60ad842016-05-10 12:18:22 +00001118 auto *Ctx = Parent.getContext();
1119 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1120 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001121}
1122
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001123/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
1124static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1125 void *User) {
1126 isl_set **BoundedParts = static_cast<isl_set **>(User);
1127 if (isl_basic_set_is_bounded(BSet))
1128 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1129 else
1130 isl_basic_set_free(BSet);
1131 return isl_stat_ok;
1132}
1133
1134/// @brief Return the bounded parts of @p S.
1135static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1136 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1137 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1138 isl_set_free(S);
1139 return BoundedParts;
1140}
1141
1142/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
1143///
1144/// @returns A separation of @p S into first an unbounded then a bounded subset,
1145/// both with regards to the dimension @p Dim.
1146static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1147partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1148
1149 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001150 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001151
1152 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001153 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001154
1155 // Remove dimensions that are greater than Dim as they are not interesting.
1156 assert(NumDimsS >= Dim + 1);
1157 OnlyDimS =
1158 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1159
1160 // Create artificial parametric upper bounds for dimensions smaller than Dim
1161 // as we are not interested in them.
1162 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1163 for (unsigned u = 0; u < Dim; u++) {
1164 isl_constraint *C = isl_inequality_alloc(
1165 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1166 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1167 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1168 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1169 }
1170
1171 // Collect all bounded parts of OnlyDimS.
1172 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1173
1174 // Create the dimensions greater than Dim again.
1175 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1176 NumDimsS - Dim - 1);
1177
1178 // Remove the artificial upper bound parameters again.
1179 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1180
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001181 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001182 return std::make_pair(UnboundedParts, BoundedParts);
1183}
1184
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001185/// @brief Set the dimension Ids from @p From in @p To.
1186static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1187 __isl_take isl_set *To) {
1188 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1189 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1190 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1191 }
1192 return To;
1193}
1194
1195/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001196static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001197 __isl_take isl_pw_aff *L,
1198 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001199 switch (Pred) {
1200 case ICmpInst::ICMP_EQ:
1201 return isl_pw_aff_eq_set(L, R);
1202 case ICmpInst::ICMP_NE:
1203 return isl_pw_aff_ne_set(L, R);
1204 case ICmpInst::ICMP_SLT:
1205 return isl_pw_aff_lt_set(L, R);
1206 case ICmpInst::ICMP_SLE:
1207 return isl_pw_aff_le_set(L, R);
1208 case ICmpInst::ICMP_SGT:
1209 return isl_pw_aff_gt_set(L, R);
1210 case ICmpInst::ICMP_SGE:
1211 return isl_pw_aff_ge_set(L, R);
1212 case ICmpInst::ICMP_ULT:
1213 return isl_pw_aff_lt_set(L, R);
1214 case ICmpInst::ICMP_UGT:
1215 return isl_pw_aff_gt_set(L, R);
1216 case ICmpInst::ICMP_ULE:
1217 return isl_pw_aff_le_set(L, R);
1218 case ICmpInst::ICMP_UGE:
1219 return isl_pw_aff_ge_set(L, R);
1220 default:
1221 llvm_unreachable("Non integer predicate not supported");
1222 }
1223}
1224
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001225/// @brief Create the conditions under which @p L @p Pred @p R is true.
1226///
1227/// Helper function that will make sure the dimensions of the result have the
1228/// same isl_id's as the @p Domain.
1229static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1230 __isl_take isl_pw_aff *L,
1231 __isl_take isl_pw_aff *R,
1232 __isl_keep isl_set *Domain) {
1233 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1234 return setDimensionIds(Domain, ConsequenceCondSet);
1235}
1236
1237/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001238///
1239/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001240/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1241/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001242static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001243buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1244 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001245 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1246
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001247 Value *Condition = getConditionFromTerminator(SI);
1248 assert(Condition && "No condition for switch");
1249
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001250 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001251 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001252 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001253 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001254
1255 unsigned NumSuccessors = SI->getNumSuccessors();
1256 ConditionSets.resize(NumSuccessors);
1257 for (auto &Case : SI->cases()) {
1258 unsigned Idx = Case.getSuccessorIndex();
1259 ConstantInt *CaseValue = Case.getCaseValue();
1260
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001261 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001262 isl_set *CaseConditionSet =
1263 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1264 ConditionSets[Idx] = isl_set_coalesce(
1265 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1266 }
1267
1268 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1269 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1270 for (unsigned u = 2; u < NumSuccessors; u++)
1271 ConditionSetUnion =
1272 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1273 ConditionSets[0] = setDimensionIds(
1274 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1275
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001276 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001277
1278 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001279}
1280
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001281/// @brief Build the conditions sets for the branch condition @p Condition in
1282/// the @p Domain.
1283///
1284/// This will fill @p ConditionSets with the conditions under which control
1285/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001286/// have as many elements as @p TI has successors. If @p TI is nullptr the
1287/// context under which @p Condition is true/false will be returned as the
1288/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001289static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001290buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1291 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001292 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1293
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001294 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001295 isl_set *ConsequenceCondSet = nullptr;
1296 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1297 if (CCond->isZero())
1298 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1299 else
1300 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1301 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1302 auto Opcode = BinOp->getOpcode();
1303 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1304
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001305 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1306 ConditionSets) &&
1307 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1308 ConditionSets);
1309 if (!Valid) {
1310 while (!ConditionSets.empty())
1311 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001312 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001313 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001314
1315 isl_set_free(ConditionSets.pop_back_val());
1316 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1317 isl_set_free(ConditionSets.pop_back_val());
1318 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1319
1320 if (Opcode == Instruction::And)
1321 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1322 else
1323 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1324 } else {
1325 auto *ICond = dyn_cast<ICmpInst>(Condition);
1326 assert(ICond &&
1327 "Condition of exiting branch was neither constant nor ICmp!");
1328
1329 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001330 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001331 // For unsigned comparisons we assumed the signed bit of neither operand
1332 // to be set. The comparison is equal to a signed comparison under this
1333 // assumption.
1334 bool NonNeg = ICond->isUnsigned();
1335 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1336 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001337 ConsequenceCondSet =
1338 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1339 }
1340
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001341 // If no terminator was given we are only looking for parameter constraints
1342 // under which @p Condition is true/false.
1343 if (!TI)
1344 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001345 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001346 ConsequenceCondSet = isl_set_coalesce(
1347 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001348
Johannes Doerfertb2885792016-04-26 09:20:41 +00001349 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001350 bool TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001351 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001352
Michael Krusef7a4a942016-05-02 12:25:36 +00001353 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001354 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1355 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001356 TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001357 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001358 }
1359
Michael Krusef7a4a942016-05-02 12:25:36 +00001360 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001361 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001362 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001363 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001364 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001365 }
1366
1367 ConditionSets.push_back(ConsequenceCondSet);
1368 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001369
1370 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001371}
1372
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001373/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1374///
1375/// This will fill @p ConditionSets with the conditions under which control
1376/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1377/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001378static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001379buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001380 __isl_keep isl_set *Domain,
1381 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1382
1383 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001384 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001385
1386 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1387
1388 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001389 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001390 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001391 }
1392
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001393 Value *Condition = getConditionFromTerminator(TI);
1394 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001395
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001396 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001397}
1398
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001399void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001400 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001401
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001402 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001403 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001404}
1405
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001406void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP, LoopInfo &LI) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001407 isl_ctx *Ctx = Parent.getIslCtx();
1408 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001409 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001410
1411 // The set of loads that are required to be invariant.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001412 auto &ScopRIL = Parent.getRequiredInvariantLoads();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001413
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001414 std::vector<const SCEV *> Subscripts;
1415 std::vector<int> Sizes;
1416
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001417 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001418
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001419 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001420
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001421 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001422
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001423 auto *NotExecuted = isl_set_complement(isl_set_params(getDomain()));
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001424 for (size_t i = 0; i < Sizes.size(); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001425 auto *Expr = Subscripts[i + IndexOffset];
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001426 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001427
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001428 auto *Scope = LI.getLoopFor(getEntryBlock());
Johannes Doerfert09e36972015-10-07 20:17:36 +00001429 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +00001430 if (!isAffineExpr(&Parent.getRegion(), Scope, Expr, SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +00001431 continue;
1432
1433 bool NonAffine = false;
1434 for (LoadInst *LInst : AccessILS)
1435 if (!ScopRIL.count(LInst))
1436 NonAffine = true;
1437
1438 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001439 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001440
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001441 isl_pw_aff *AccessOffset = getPwAff(Expr);
1442 AccessOffset =
1443 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001444
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001445 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1446 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001447
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001448 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1449 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1450 OutOfBound = isl_set_params(OutOfBound);
1451 isl_set *InBound = isl_set_complement(OutOfBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001452
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001453 // A => B == !A or B
1454 isl_set *InBoundIfExecuted =
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001455 isl_set_union(isl_set_copy(NotExecuted), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001456
Roman Gareev10595a12016-01-08 14:01:59 +00001457 InBoundIfExecuted = isl_set_coalesce(InBoundIfExecuted);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00001458 Parent.recordAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc(),
1459 AS_ASSUMPTION);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001460 }
1461
1462 isl_local_space_free(LSpace);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001463 isl_set_free(NotExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001464}
1465
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001466void ScopStmt::deriveAssumptions(LoopInfo &LI) {
Johannes Doerfertd5c369f2016-04-25 18:55:15 +00001467 for (auto *MA : *this) {
1468 if (!MA->isArrayKind())
1469 continue;
1470
1471 MemAccInst Acc(MA->getAccessInstruction());
1472 auto *GEP = dyn_cast_or_null<GetElementPtrInst>(Acc.getPointerOperand());
1473
1474 if (GEP)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001475 deriveAssumptionsFromGEP(GEP, LI);
Johannes Doerfertd5c369f2016-04-25 18:55:15 +00001476 }
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001477}
1478
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001479void ScopStmt::collectSurroundingLoops() {
1480 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1481 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1482 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1483 isl_id_free(DimId);
1484 }
1485}
1486
Michael Kruse9d080092015-09-11 21:41:48 +00001487ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerferta3519512016-04-23 13:02:23 +00001488 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1489 R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001490
Tobias Grosser16c44032015-07-09 07:31:45 +00001491 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001492}
1493
Michael Kruse9d080092015-09-11 21:41:48 +00001494ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerferta3519512016-04-23 13:02:23 +00001495 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1496 R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001497
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001498 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001499}
1500
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001501void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001502 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001503
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001504 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001505 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001506 buildAccessRelations();
1507
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001508 deriveAssumptions(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00001509
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001510 if (DetectReductions)
1511 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001512}
1513
Johannes Doerferte58a0122014-06-27 20:31:28 +00001514/// @brief Collect loads which might form a reduction chain with @p StoreMA
1515///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001516/// Check if the stored value for @p StoreMA is a binary operator with one or
1517/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001518/// used only once (by @p StoreMA) and its load operands are also used only
1519/// once, we have found a possible reduction chain. It starts at an operand
1520/// load and includes the binary operator and @p StoreMA.
1521///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001522/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001523/// escape this block or into any other store except @p StoreMA.
1524void ScopStmt::collectCandiateReductionLoads(
1525 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1526 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1527 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001528 return;
1529
1530 // Skip if there is not one binary operator between the load and the store
1531 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001532 if (!BinOp)
1533 return;
1534
1535 // Skip if the binary operators has multiple uses
1536 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001537 return;
1538
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001539 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001540 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1541 return;
1542
Johannes Doerfert9890a052014-07-01 00:32:29 +00001543 // Skip if the binary operator is outside the current SCoP
1544 if (BinOp->getParent() != Store->getParent())
1545 return;
1546
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001547 // Skip if it is a multiplicative reduction and we disabled them
1548 if (DisableMultiplicativeReductions &&
1549 (BinOp->getOpcode() == Instruction::Mul ||
1550 BinOp->getOpcode() == Instruction::FMul))
1551 return;
1552
Johannes Doerferte58a0122014-06-27 20:31:28 +00001553 // Check the binary operator operands for a candidate load
1554 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1555 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1556 if (!PossibleLoad0 && !PossibleLoad1)
1557 return;
1558
1559 // A load is only a candidate if it cannot escape (thus has only this use)
1560 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001561 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001562 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001563 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001564 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001565 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001566}
1567
1568/// @brief Check for reductions in this ScopStmt
1569///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001570/// Iterate over all store memory accesses and check for valid binary reduction
1571/// like chains. For all candidates we check if they have the same base address
1572/// and there are no other accesses which overlap with them. The base address
1573/// check rules out impossible reductions candidates early. The overlap check,
1574/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001575/// guarantees that none of the intermediate results will escape during
1576/// execution of the loop nest. We basically check here that no other memory
1577/// access can access the same memory as the potential reduction.
1578void ScopStmt::checkForReductions() {
1579 SmallVector<MemoryAccess *, 2> Loads;
1580 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1581
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001582 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001583 // stores and collecting possible reduction loads.
1584 for (MemoryAccess *StoreMA : MemAccs) {
1585 if (StoreMA->isRead())
1586 continue;
1587
1588 Loads.clear();
1589 collectCandiateReductionLoads(StoreMA, Loads);
1590 for (MemoryAccess *LoadMA : Loads)
1591 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1592 }
1593
1594 // Then check each possible candidate pair.
1595 for (const auto &CandidatePair : Candidates) {
1596 bool Valid = true;
1597 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1598 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1599
1600 // Skip those with obviously unequal base addresses.
1601 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1602 isl_map_free(LoadAccs);
1603 isl_map_free(StoreAccs);
1604 continue;
1605 }
1606
1607 // And check if the remaining for overlap with other memory accesses.
1608 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1609 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1610 isl_set *AllAccs = isl_map_range(AllAccsRel);
1611
1612 for (MemoryAccess *MA : MemAccs) {
1613 if (MA == CandidatePair.first || MA == CandidatePair.second)
1614 continue;
1615
1616 isl_map *AccRel =
1617 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1618 isl_set *Accs = isl_map_range(AccRel);
1619
1620 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1621 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1622 Valid = Valid && isl_set_is_empty(OverlapAccs);
1623 isl_set_free(OverlapAccs);
1624 }
1625 }
1626
1627 isl_set_free(AllAccs);
1628 if (!Valid)
1629 continue;
1630
Johannes Doerfertf6183392014-07-01 20:52:51 +00001631 const LoadInst *Load =
1632 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1633 MemoryAccess::ReductionType RT =
1634 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1635
Johannes Doerferte58a0122014-06-27 20:31:28 +00001636 // If no overlapping access was found we mark the load and store as
1637 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001638 CandidatePair.first->markAsReductionLike(RT);
1639 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001640 }
Tobias Grosser75805372011-04-29 06:27:02 +00001641}
1642
Tobias Grosser74394f02013-01-14 22:40:23 +00001643std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001644
Tobias Grosser54839312015-04-21 11:37:25 +00001645std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001646 auto *S = getSchedule();
1647 auto Str = stringFromIslObj(S);
1648 isl_map_free(S);
1649 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001650}
1651
Johannes Doerferta3519512016-04-23 13:02:23 +00001652void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1653 isl_set_free(InvalidDomain);
1654 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001655}
1656
Michael Kruse375cb5f2016-02-24 22:08:24 +00001657BasicBlock *ScopStmt::getEntryBlock() const {
1658 if (isBlockStmt())
1659 return getBasicBlock();
1660 return getRegion()->getEntry();
1661}
1662
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001663unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001664
Tobias Grosser75805372011-04-29 06:27:02 +00001665const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1666
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001667Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001668 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001669}
1670
Tobias Grosser74394f02013-01-14 22:40:23 +00001671isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001672
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001673__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001674
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001675__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001676 return isl_set_get_space(Domain);
1677}
1678
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001679__isl_give isl_id *ScopStmt::getDomainId() const {
1680 return isl_set_get_tuple_id(Domain);
1681}
Tobias Grossercd95b772012-08-30 11:49:38 +00001682
Johannes Doerfert7c013572016-04-12 09:57:34 +00001683ScopStmt::~ScopStmt() {
1684 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001685 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001686}
Tobias Grosser75805372011-04-29 06:27:02 +00001687
1688void ScopStmt::print(raw_ostream &OS) const {
1689 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001690 OS.indent(12) << "Domain :=\n";
1691
1692 if (Domain) {
1693 OS.indent(16) << getDomainStr() << ";\n";
1694 } else
1695 OS.indent(16) << "n/a\n";
1696
Tobias Grosser54839312015-04-21 11:37:25 +00001697 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001698
1699 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001700 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001701 } else
1702 OS.indent(16) << "n/a\n";
1703
Tobias Grosser083d3d32014-06-28 08:59:45 +00001704 for (MemoryAccess *Access : MemAccs)
1705 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001706}
1707
1708void ScopStmt::dump() const { print(dbgs()); }
1709
Michael Kruse10071822016-05-23 14:45:58 +00001710void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
1711 // Remove the memory accesses from this statement
1712 // together with all scalar accesses that were caused by it.
Michael Krusead28e5a2016-01-26 13:33:15 +00001713 // MK_Value READs have no access instruction, hence would not be removed by
1714 // this function. However, it is only used for invariant LoadInst accesses,
1715 // its arguments are always affine, hence synthesizable, and therefore there
1716 // are no MK_Value READ accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001717 auto Predicate = [&](MemoryAccess *Acc) {
1718 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1719 };
1720 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1721 MemAccs.end());
1722 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001723}
1724
Tobias Grosser75805372011-04-29 06:27:02 +00001725//===----------------------------------------------------------------------===//
1726/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001727
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001728void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001729 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1730 isl_set_free(Context);
1731 Context = NewContext;
1732}
1733
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001734/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1735struct SCEVSensitiveParameterRewriter
1736 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1737 ValueToValueMap &VMap;
1738 ScalarEvolution &SE;
1739
1740public:
1741 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1742 : VMap(VMap), SE(SE) {}
1743
1744 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1745 ValueToValueMap &VMap) {
1746 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1747 return SSPR.visit(E);
1748 }
1749
1750 const SCEV *visit(const SCEV *E) {
1751 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1752 }
1753
1754 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1755
1756 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1757 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1758 }
1759
1760 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1761 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1762 }
1763
1764 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1765 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1766 }
1767
1768 const SCEV *visitAddExpr(const SCEVAddExpr *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.getAddExpr(Operands);
1773 }
1774
1775 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1776 SmallVector<const SCEV *, 4> Operands;
1777 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1778 Operands.push_back(visit(E->getOperand(i)));
1779 return SE.getMulExpr(Operands);
1780 }
1781
1782 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1783 SmallVector<const SCEV *, 4> Operands;
1784 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1785 Operands.push_back(visit(E->getOperand(i)));
1786 return SE.getSMaxExpr(Operands);
1787 }
1788
1789 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1790 SmallVector<const SCEV *, 4> Operands;
1791 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1792 Operands.push_back(visit(E->getOperand(i)));
1793 return SE.getUMaxExpr(Operands);
1794 }
1795
1796 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1797 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1798 }
1799
1800 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1801 auto *Start = visit(E->getStart());
1802 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1803 visit(E->getStepRecurrence(SE)),
1804 E->getLoop(), SCEV::FlagAnyWrap);
1805 return SE.getAddExpr(Start, AddRec);
1806 }
1807
1808 const SCEV *visitUnknown(const SCEVUnknown *E) {
1809 if (auto *NewValue = VMap.lookup(E->getValue()))
1810 return SE.getUnknown(NewValue);
1811 return E;
1812 }
1813};
1814
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001815const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001816 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001817}
1818
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001819void Scop::createParameterId(const SCEV *Parameter) {
1820 assert(Parameters.count(Parameter));
1821 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001822
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001823 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001824
Tobias Grosser8f99c162011-11-15 11:38:55 +00001825 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1826 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001827
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001828 // If this parameter references a specific Value and this value has a name
1829 // we use this name as it is likely to be unique and more useful than just
1830 // a number.
1831 if (Val->hasName())
1832 ParameterName = Val->getName();
1833 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001834 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001835 if (LoadOrigin->hasName()) {
1836 ParameterName += "_loaded_from_";
1837 ParameterName +=
1838 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1839 }
1840 }
1841 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001842
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001843 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1844 const_cast<void *>((const void *)Parameter));
1845 ParameterIds[Parameter] = Id;
1846}
1847
1848void Scop::addParams(const ParameterSetTy &NewParameters) {
1849 for (const SCEV *Parameter : NewParameters) {
1850 // Normalize the SCEV to get the representing element for an invariant load.
1851 Parameter = extractConstantFactor(Parameter, *SE).second;
1852 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1853
1854 if (Parameters.insert(Parameter))
1855 createParameterId(Parameter);
1856 }
1857}
1858
1859__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1860 // Normalize the SCEV to get the representing element for an invariant load.
1861 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1862 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001863}
Tobias Grosser75805372011-04-29 06:27:02 +00001864
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001865__isl_give isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001866 isl_set *DomainContext = isl_union_set_params(getDomains());
1867 return isl_set_intersect_params(C, DomainContext);
1868}
1869
Johannes Doerferte0b08072016-05-23 12:43:44 +00001870bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1871 return DT.dominates(BB, getEntry());
1872}
1873
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001874void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1875 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001876 auto &F = getFunction();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001877 for (auto &Assumption : AC.assumptions()) {
1878 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1879 if (!CI || CI->getNumArgOperands() != 1)
1880 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001881
Johannes Doerfert952b5302016-05-23 12:40:48 +00001882 bool InScop = contains(CI);
Johannes Doerferte0b08072016-05-23 12:43:44 +00001883 if (!InScop && !isDominatedBy(DT, CI->getParent()))
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001884 continue;
1885
Michael Kruse09eb4452016-03-03 22:10:47 +00001886 auto *L = LI.getLoopFor(CI->getParent());
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001887 auto *Val = CI->getArgOperand(0);
Johannes Doerfertf560b3d2016-04-25 13:33:07 +00001888 ParameterSetTy DetectedParams;
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001889 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001890 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1891 CI->getDebugLoc(),
1892 "Non-affine user assumption ignored.");
1893 continue;
1894 }
1895
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001896 // Collect all newly introduced parameters.
1897 ParameterSetTy NewParams;
1898 for (auto *Param : DetectedParams) {
1899 Param = extractConstantFactor(Param, *SE).second;
1900 Param = getRepresentingInvariantLoadSCEV(Param);
1901 if (Parameters.count(Param))
1902 continue;
1903 NewParams.insert(Param);
1904 }
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001905
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001906 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001907 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
1908 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
1909 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001910 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
1911 isl_set_free(Dom);
1912
1913 if (!Valid)
Johannes Doerfert297c7202016-05-10 13:06:42 +00001914 continue;
1915
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001916 isl_set *AssumptionCtx = nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001917 if (InScop) {
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001918 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
1919 isl_set_free(ConditionSets[0]);
1920 } else {
1921 AssumptionCtx = isl_set_complement(ConditionSets[1]);
1922 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
1923 }
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001924
1925 // Project out newly introduced parameters as they are not otherwise useful.
1926 if (!NewParams.empty()) {
1927 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
1928 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
1929 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
1930 isl_id_free(Id);
1931
1932 if (!NewParams.count(Param))
1933 continue;
1934
1935 AssumptionCtx =
1936 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
1937 }
1938 }
1939
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001940 emitOptimizationRemarkAnalysis(
1941 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1942 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1943 Context = isl_set_intersect(Context, AssumptionCtx);
1944 }
1945}
1946
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001947void Scop::addUserContext() {
1948 if (UserContextStr.empty())
1949 return;
1950
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001951 isl_set *UserContext =
1952 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001953 isl_space *Space = getParamSpace();
1954 if (isl_space_dim(Space, isl_dim_param) !=
1955 isl_set_dim(UserContext, isl_dim_param)) {
1956 auto SpaceStr = isl_space_to_str(Space);
1957 errs() << "Error: the context provided in -polly-context has not the same "
1958 << "number of dimensions than the computed context. Due to this "
1959 << "mismatch, the -polly-context option is ignored. Please provide "
1960 << "the context in the parameter space: " << SpaceStr << ".\n";
1961 free(SpaceStr);
1962 isl_set_free(UserContext);
1963 isl_space_free(Space);
1964 return;
1965 }
1966
1967 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001968 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1969 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001970
1971 if (strcmp(NameContext, NameUserContext) != 0) {
1972 auto SpaceStr = isl_space_to_str(Space);
1973 errs() << "Error: the name of dimension " << i
1974 << " provided in -polly-context "
1975 << "is '" << NameUserContext << "', but the name in the computed "
1976 << "context is '" << NameContext
1977 << "'. Due to this name mismatch, "
1978 << "the -polly-context option is ignored. Please provide "
1979 << "the context in the parameter space: " << SpaceStr << ".\n";
1980 free(SpaceStr);
1981 isl_set_free(UserContext);
1982 isl_space_free(Space);
1983 return;
1984 }
1985
1986 UserContext =
1987 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1988 isl_space_get_dim_id(Space, isl_dim_param, i));
1989 }
1990
1991 Context = isl_set_intersect(Context, UserContext);
1992 isl_space_free(Space);
1993}
1994
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001995void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001996 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001997
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001998 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001999 for (LoadInst *LInst : RIL) {
2000 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2001
Johannes Doerfert96e54712016-02-07 17:30:13 +00002002 Type *Ty = LInst->getType();
2003 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002004 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002005 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002006 continue;
2007 }
2008
2009 ClassRep = LInst;
Johannes Doerfert96e54712016-02-07 17:30:13 +00002010 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(), nullptr,
2011 Ty);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002012 }
2013}
2014
Tobias Grosser6be480c2011-11-08 15:41:13 +00002015void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002016 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002017 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002018 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002019 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002020}
2021
Tobias Grosser18daaca2012-05-22 10:47:27 +00002022void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002023 unsigned PDim = 0;
2024 for (auto *Parameter : Parameters) {
2025 ConstantRange SRange = SE->getSignedRange(Parameter);
2026 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002027 }
2028}
2029
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002030void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002031 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002032 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002033
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002034 unsigned PDim = 0;
2035 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002036 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002037 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002038 }
2039
2040 // Align the parameters of all data structures to the model.
2041 Context = isl_set_align_params(Context, Space);
2042
Johannes Doerferta60ad842016-05-10 12:18:22 +00002043 // As all parameters are known add bounds to them.
2044 addParameterBounds();
2045
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002046 for (ScopStmt &Stmt : *this)
2047 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002048}
2049
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002050static __isl_give isl_set *
2051simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2052 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002053 // If we modelt all blocks in the SCoP that have side effects we can simplify
2054 // the context with the constraints that are needed for anything to be
2055 // executed at all. However, if we have error blocks in the SCoP we already
2056 // assumed some parameter combinations cannot occure and removed them from the
2057 // domains, thus we cannot use the remaining domain to simplify the
2058 // assumptions.
2059 if (!S.hasErrorBlock()) {
2060 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2061 AssumptionContext =
2062 isl_set_gist_params(AssumptionContext, DomainParameters);
2063 }
2064
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002065 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2066 return AssumptionContext;
2067}
2068
2069void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002070 // The parameter constraints of the iteration domains give us a set of
2071 // constraints that need to hold for all cases where at least a single
2072 // statement iteration is executed in the whole scop. We now simplify the
2073 // assumed context under the assumption that such constraints hold and at
2074 // least a single statement iteration is executed. For cases where no
2075 // statement instances are executed, the assumptions we have taken about
2076 // the executed code do not matter and can be changed.
2077 //
2078 // WARNING: This only holds if the assumptions we have taken do not reduce
2079 // the set of statement instances that are executed. Otherwise we
2080 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002081 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002082 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002083 // performed. In such a case, modifying the run-time conditions and
2084 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002085 // to not be executed.
2086 //
2087 // Example:
2088 //
2089 // When delinearizing the following code:
2090 //
2091 // for (long i = 0; i < 100; i++)
2092 // for (long j = 0; j < m; j++)
2093 // A[i+p][j] = 1.0;
2094 //
2095 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002096 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002097 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002098 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002099 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002100}
2101
Johannes Doerfertb164c792014-09-18 11:17:17 +00002102/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002103static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002104 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2105 isl_pw_multi_aff *MinPMA, *MaxPMA;
2106 isl_pw_aff *LastDimAff;
2107 isl_aff *OneAff;
2108 unsigned Pos;
2109
Johannes Doerfert6296d952016-04-22 11:38:19 +00002110 Set = isl_set_remove_divs(Set);
2111
Michael Krusebc150122016-05-02 12:25:18 +00002112 if (isl_set_n_basic_set(Set) >= MaxDisjunctionsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002113 isl_set_free(Set);
2114 return isl_stat_error;
2115 }
2116
Johannes Doerfert9143d672014-09-27 11:02:39 +00002117 // Restrict the number of parameters involved in the access as the lexmin/
2118 // lexmax computation will take too long if this number is high.
2119 //
2120 // Experiments with a simple test case using an i7 4800MQ:
2121 //
2122 // #Parameters involved | Time (in sec)
2123 // 6 | 0.01
2124 // 7 | 0.04
2125 // 8 | 0.12
2126 // 9 | 0.40
2127 // 10 | 1.54
2128 // 11 | 6.78
2129 // 12 | 30.38
2130 //
2131 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2132 unsigned InvolvedParams = 0;
2133 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2134 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2135 InvolvedParams++;
2136
2137 if (InvolvedParams > RunTimeChecksMaxParameters) {
2138 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002139 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002140 }
2141 }
2142
Johannes Doerfertb164c792014-09-18 11:17:17 +00002143 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2144 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2145
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002146 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2147 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2148
Johannes Doerfertb164c792014-09-18 11:17:17 +00002149 // Adjust the last dimension of the maximal access by one as we want to
2150 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2151 // we test during code generation might now point after the end of the
2152 // allocated array but we will never dereference it anyway.
2153 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2154 "Assumed at least one output dimension");
2155 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2156 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2157 OneAff = isl_aff_zero_on_domain(
2158 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2159 OneAff = isl_aff_add_constant_si(OneAff, 1);
2160 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2161 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2162
2163 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2164
2165 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002166 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002167}
2168
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002169static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2170 isl_set *Domain = MA->getStatement()->getDomain();
2171 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2172 return isl_set_reset_tuple_id(Domain);
2173}
2174
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002175/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
2176static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002177 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002178 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002179
2180 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2181 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002182 Locations = isl_union_set_coalesce(Locations);
2183 Locations = isl_union_set_detect_equalities(Locations);
2184 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002185 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002186 isl_union_set_free(Locations);
2187 return Valid;
2188}
2189
Johannes Doerfert96425c22015-08-30 21:13:53 +00002190/// @brief Helper to treat non-affine regions and basic blocks the same.
2191///
2192///{
2193
2194/// @brief Return the block that is the representing block for @p RN.
2195static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2196 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2197 : RN->getNodeAs<BasicBlock>();
2198}
2199
2200/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002201static inline BasicBlock *
2202getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002203 if (RN->isSubRegion()) {
2204 assert(idx == 0);
2205 return RN->getNodeAs<Region>()->getExit();
2206 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002207 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002208}
2209
2210/// @brief Return the smallest loop surrounding @p RN.
2211static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2212 if (!RN->isSubRegion())
2213 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2214
2215 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2216 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2217 while (L && NonAffineSubRegion->contains(L))
2218 L = L->getParentLoop();
2219 return L;
2220}
2221
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002222static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2223 if (!RN->isSubRegion())
2224 return 1;
2225
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002226 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002227 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002228}
2229
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002230static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2231 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002232 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002233 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002234 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002235 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002236 return true;
2237 return false;
2238}
2239
Johannes Doerfert96425c22015-08-30 21:13:53 +00002240///}
2241
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002242static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2243 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002244 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002245 isl_id *DimId =
2246 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2247 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2248}
2249
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002250__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002251 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002252}
2253
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002254__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002255 auto DIt = DomainMap.find(BB);
2256 if (DIt != DomainMap.end())
2257 return isl_set_copy(DIt->getSecond());
2258
2259 auto &RI = *R.getRegionInfo();
2260 auto *BBR = RI.getRegionFor(BB);
2261 while (BBR->getEntry() == BB)
2262 BBR = BBR->getParent();
2263 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002264}
2265
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002266bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002267
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002268 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002269 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002270 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2271 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002272 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002273
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002274 while (LD-- >= 0) {
2275 S = addDomainDimId(S, LD + 1, L);
2276 L = L->getParentLoop();
2277 }
2278
Johannes Doerferta3519512016-04-23 13:02:23 +00002279 // Initialize the invalid domain.
2280 auto *EntryStmt = getStmtFor(EntryBB);
2281 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2282
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002283 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002284
Johannes Doerfert432658d2016-01-26 11:01:41 +00002285 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002286 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002287
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002288 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002289 return false;
2290
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002291 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002292 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002293
2294 // Error blocks and blocks dominated by them have been assumed to never be
2295 // executed. Representing them in the Scop does not add any value. In fact,
2296 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002297 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002298 // will cause problems when building up a ScopStmt for them.
2299 // Furthermore, basic blocks dominated by error blocks may reference
2300 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002301 // can themselves not be constructed properly. To this end we will replace
2302 // the domains of error blocks and those only reachable via error blocks
2303 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002304 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002305 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002306 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002307 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002308
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002309 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002310}
2311
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002312static Loop *getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI,
2313 const BoxedLoopsSetTy &BoxedLoops) {
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002314 auto *L = LI.getLoopFor(BB);
2315 while (BoxedLoops.count(L))
2316 L = L->getParentLoop();
2317 return L;
2318}
2319
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002320/// @brief Adjust the dimensions of @p Dom that was constructed for @p OldL
2321/// to be compatible to domains constructed for loop @p NewL.
2322///
2323/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2324/// edge from @p OldL to @p NewL.
2325static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2326 __isl_take isl_set *Dom,
2327 Loop *OldL, Loop *NewL) {
2328
2329 // If the loops are the same there is nothing to do.
2330 if (NewL == OldL)
2331 return Dom;
2332
2333 int OldDepth = S.getRelativeLoopDepth(OldL);
2334 int NewDepth = S.getRelativeLoopDepth(NewL);
2335 // If both loops are non-affine loops there is nothing to do.
2336 if (OldDepth == -1 && NewDepth == -1)
2337 return Dom;
2338
2339 // Distinguish three cases:
2340 // 1) The depth is the same but the loops are not.
2341 // => One loop was left one was entered.
2342 // 2) The depth increased from OldL to NewL.
2343 // => One loop was entered, none was left.
2344 // 3) The depth decreased from OldL to NewL.
2345 // => Loops were left were difference of the depths defines how many.
2346 if (OldDepth == NewDepth) {
2347 assert(OldL->getParentLoop() == NewL->getParentLoop());
2348 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2349 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2350 Dom = addDomainDimId(Dom, NewDepth, NewL);
2351 } else if (OldDepth < NewDepth) {
2352 assert(OldDepth + 1 == NewDepth);
2353 auto &R = S.getRegion();
2354 (void)R;
2355 assert(NewL->getParentLoop() == OldL ||
2356 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2357 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2358 Dom = addDomainDimId(Dom, NewDepth, NewL);
2359 } else {
2360 assert(OldDepth > NewDepth);
2361 int Diff = OldDepth - NewDepth;
2362 int NumDim = isl_set_n_dim(Dom);
2363 assert(NumDim >= Diff);
2364 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2365 }
2366
2367 return Dom;
2368}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002369
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002370bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2371 LoopInfo &LI) {
2372 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002373
2374 ReversePostOrderTraversal<Region *> RTraversal(R);
2375 for (auto *RN : RTraversal) {
2376
2377 // Recurse for affine subregions but go on for basic blocks and non-affine
2378 // subregions.
2379 if (RN->isSubRegion()) {
2380 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002381 if (!isNonAffineSubRegion(SubRegion)) {
2382 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002383 continue;
2384 }
2385 }
2386
2387 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2388 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002389 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002390 isl_set *&Domain = DomainMap[BB];
2391 assert(Domain && "Cannot propagate a nullptr");
2392
Johannes Doerferta3519512016-04-23 13:02:23 +00002393 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002394 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002395 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002396
Johannes Doerferta3519512016-04-23 13:02:23 +00002397 if (!IsInvalidBlock) {
2398 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002399 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002400 isl_set_free(InvalidDomain);
2401 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002402 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2403 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2404 AS_RESTRICTION);
2405 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002406 }
2407
Johannes Doerferta3519512016-04-23 13:02:23 +00002408 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002409 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002410 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002411 }
2412
Johannes Doerferta3519512016-04-23 13:02:23 +00002413 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002414 auto *TI = BB->getTerminator();
2415 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2416 for (unsigned u = 0; u < NumSuccs; u++) {
2417 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002418 auto *SuccStmt = getStmtFor(SuccBB);
2419
2420 // Skip successors outside the SCoP.
2421 if (!SuccStmt)
2422 continue;
2423
Johannes Doerferte4459a22016-04-25 13:34:50 +00002424 // Skip backedges.
2425 if (DT.dominates(SuccBB, BB))
2426 continue;
2427
Johannes Doerferta3519512016-04-23 13:02:23 +00002428 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2429 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2430 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2431 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2432 SuccInvalidDomain =
2433 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2434 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2435 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2436 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002437
Michael Krusebc150122016-05-02 12:25:18 +00002438 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002439 // In case this happens we will bail.
Michael Krusebc150122016-05-02 12:25:18 +00002440 if (NumConjucts < MaxDisjunctionsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002441 continue;
2442
Johannes Doerferta3519512016-04-23 13:02:23 +00002443 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002444 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002445 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002446 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002447
2448 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002449 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002450
2451 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002452}
2453
Johannes Doerfert642594a2016-04-04 07:57:39 +00002454void Scop::propagateDomainConstraintsToRegionExit(
2455 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002456 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002457
2458 // Check if the block @p BB is the entry of a region. If so we propagate it's
2459 // domain to the exit block of the region. Otherwise we are done.
2460 auto *RI = R.getRegionInfo();
2461 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2462 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002463 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002464 return;
2465
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002466 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002467 // Do not propagate the domain if there is a loop backedge inside the region
2468 // that would prevent the exit block from beeing executed.
2469 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002470 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002471 SmallVector<BasicBlock *, 4> LatchBBs;
2472 BBLoop->getLoopLatches(LatchBBs);
2473 for (auto *LatchBB : LatchBBs)
2474 if (BB != LatchBB && BBReg->contains(LatchBB))
2475 return;
2476 L = L->getParentLoop();
2477 }
2478
2479 auto *Domain = DomainMap[BB];
2480 assert(Domain && "Cannot propagate a nullptr");
2481
2482 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2483
2484 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2485 // adjust the domain before we can propagate it.
2486 auto *AdjustedDomain =
2487 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2488 auto *&ExitDomain = DomainMap[ExitBB];
2489
2490 // If the exit domain is not yet created we set it otherwise we "add" the
2491 // current domain.
2492 ExitDomain =
2493 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2494
Johannes Doerferta3519512016-04-23 13:02:23 +00002495 // Initialize the invalid domain.
2496 auto *ExitStmt = getStmtFor(ExitBB);
2497 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2498
Johannes Doerfert642594a2016-04-04 07:57:39 +00002499 FinishedExitBlocks.insert(ExitBB);
2500}
2501
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002502bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2503 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002504 // To create the domain for each block in R we iterate over all blocks and
2505 // subregions in R and propagate the conditions under which the current region
2506 // element is executed. To this end we iterate in reverse post order over R as
2507 // it ensures that we first visit all predecessors of a region node (either a
2508 // basic block or a subregion) before we visit the region node itself.
2509 // Initially, only the domain for the SCoP region entry block is set and from
2510 // there we propagate the current domain to all successors, however we add the
2511 // condition that the successor is actually executed next.
2512 // As we are only interested in non-loop carried constraints here we can
2513 // simply skip loop back edges.
2514
Johannes Doerfert642594a2016-04-04 07:57:39 +00002515 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002516 ReversePostOrderTraversal<Region *> RTraversal(R);
2517 for (auto *RN : RTraversal) {
2518
2519 // Recurse for affine subregions but go on for basic blocks and non-affine
2520 // subregions.
2521 if (RN->isSubRegion()) {
2522 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002523 if (!isNonAffineSubRegion(SubRegion)) {
2524 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002525 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002526 continue;
2527 }
2528 }
2529
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002530 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002531 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002532
Johannes Doerfert96425c22015-08-30 21:13:53 +00002533 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002534 TerminatorInst *TI = BB->getTerminator();
2535
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002536 if (isa<UnreachableInst>(TI))
2537 continue;
2538
Johannes Doerfertf5673802015-10-01 23:48:18 +00002539 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002540 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002541 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002542 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002543
Johannes Doerfert642594a2016-04-04 07:57:39 +00002544 auto *BBLoop = getRegionNodeLoop(RN, LI);
2545 // Propagate the domain from BB directly to blocks that have a superset
2546 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002547 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002548
2549 // If all successors of BB have been set a domain through the propagation
2550 // above we do not need to build condition sets but can just skip this
2551 // block. However, it is important to note that this is a local property
2552 // with regards to the region @p R. To this end FinishedExitBlocks is a
2553 // local variable.
2554 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2555 return FinishedExitBlocks.count(SuccBB);
2556 };
2557 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2558 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002559
2560 // Build the condition sets for the successor nodes of the current region
2561 // node. If it is a non-affine subregion we will always execute the single
2562 // exit node, hence the single entry node domain is the condition set. For
2563 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002564 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002565 if (RN->isSubRegion())
2566 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002567 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2568 ConditionSets))
2569 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002570
2571 // Now iterate over the successors and set their initial domain based on
2572 // their condition set. We skip back edges here and have to be careful when
2573 // we leave a loop not to keep constraints over a dimension that doesn't
2574 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002575 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002576 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002577 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002578 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002579
Johannes Doerfert535de032016-04-19 14:49:05 +00002580 auto *SuccStmt = getStmtFor(SuccBB);
2581 // Skip blocks outside the region.
2582 if (!SuccStmt) {
2583 isl_set_free(CondSet);
2584 continue;
2585 }
2586
Johannes Doerfert642594a2016-04-04 07:57:39 +00002587 // If we propagate the domain of some block to "SuccBB" we do not have to
2588 // adjust the domain.
2589 if (FinishedExitBlocks.count(SuccBB)) {
2590 isl_set_free(CondSet);
2591 continue;
2592 }
2593
Johannes Doerfert96425c22015-08-30 21:13:53 +00002594 // Skip back edges.
2595 if (DT.dominates(SuccBB, BB)) {
2596 isl_set_free(CondSet);
2597 continue;
2598 }
2599
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002600 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002601 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002602 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002603
2604 // Set the domain for the successor or merge it with an existing domain in
2605 // case there are multiple paths (without loop back edges) to the
2606 // successor block.
2607 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002608
Johannes Doerferta3519512016-04-23 13:02:23 +00002609 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002610 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002611 } else {
2612 // Initialize the invalid domain.
2613 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2614 SuccDomain = CondSet;
2615 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002616
Michael Krusebc150122016-05-02 12:25:18 +00002617 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002618 // In case this happens we will clean up and bail.
Michael Krusebc150122016-05-02 12:25:18 +00002619 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctionsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002620 continue;
2621
2622 invalidate(COMPLEXITY, DebugLoc());
2623 while (++u < ConditionSets.size())
2624 isl_set_free(ConditionSets[u]);
2625 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002626 }
2627 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002628
2629 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002630}
2631
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00002632__isl_give isl_set *Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2633 isl_set *Domain,
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00002634 DominatorTree &DT,
2635 LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002636 // If @p BB is the ScopEntry we are done
2637 if (R.getEntry() == BB)
2638 return isl_set_universe(isl_set_get_space(Domain));
2639
2640 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002641 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002642
2643 // The region info of this function.
2644 auto &RI = *R.getRegionInfo();
2645
2646 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2647
2648 // A domain to collect all predecessor domains, thus all conditions under
2649 // which the block is executed. To this end we start with the empty domain.
2650 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2651
2652 // Set of regions of which the entry block domain has been propagated to BB.
2653 // all predecessors inside any of the regions can be skipped.
2654 SmallSet<Region *, 8> PropagatedRegions;
2655
2656 for (auto *PredBB : predecessors(BB)) {
2657 // Skip backedges.
2658 if (DT.dominates(BB, PredBB))
2659 continue;
2660
2661 // If the predecessor is in a region we used for propagation we can skip it.
2662 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2663 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2664 PredBBInRegion)) {
2665 continue;
2666 }
2667
2668 // Check if there is a valid region we can use for propagation, thus look
2669 // for a region that contains the predecessor and has @p BB as exit block.
2670 auto *PredR = RI.getRegionFor(PredBB);
2671 while (PredR->getExit() != BB && !PredR->contains(BB))
2672 PredR->getParent();
2673
2674 // If a valid region for propagation was found use the entry of that region
2675 // for propagation, otherwise the PredBB directly.
2676 if (PredR->getExit() == BB) {
2677 PredBB = PredR->getEntry();
2678 PropagatedRegions.insert(PredR);
2679 }
2680
Johannes Doerfert41cda152016-04-08 10:32:26 +00002681 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002682 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2683 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2684
2685 PredDom = isl_set_union(PredDom, PredBBDom);
2686 }
2687
2688 return PredDom;
2689}
2690
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002691bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2692 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002693 // Iterate over the region R and propagate the domain constrains from the
2694 // predecessors to the current node. In contrast to the
2695 // buildDomainsWithBranchConstraints function, this one will pull the domain
2696 // information from the predecessors instead of pushing it to the successors.
2697 // Additionally, we assume the domains to be already present in the domain
2698 // map here. However, we iterate again in reverse post order so we know all
2699 // predecessors have been visited before a block or non-affine subregion is
2700 // visited.
2701
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002702 ReversePostOrderTraversal<Region *> RTraversal(R);
2703 for (auto *RN : RTraversal) {
2704
2705 // Recurse for affine subregions but go on for basic blocks and non-affine
2706 // subregions.
2707 if (RN->isSubRegion()) {
2708 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002709 if (!isNonAffineSubRegion(SubRegion)) {
2710 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002711 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002712 continue;
2713 }
2714 }
2715
2716 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002717 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002718 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002719
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002720 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002721 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002722 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002723 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002724
Johannes Doerfert642594a2016-04-04 07:57:39 +00002725 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002726 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002727 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2728 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002729 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002730
2731 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002732}
2733
2734/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2735/// is incremented by one and all other dimensions are equal, e.g.,
2736/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2737/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2738static __isl_give isl_map *
2739createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2740 auto *MapSpace = isl_space_map_from_set(SetSpace);
2741 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2742 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2743 if (u != Dim)
2744 NextIterationMap =
2745 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2746 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2747 C = isl_constraint_set_constant_si(C, 1);
2748 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2749 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2750 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2751 return NextIterationMap;
2752}
2753
Johannes Doerfert297c7202016-05-10 13:06:42 +00002754bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002755 int LoopDepth = getRelativeLoopDepth(L);
2756 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002757
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002758 BasicBlock *HeaderBB = L->getHeader();
2759 assert(DomainMap.count(HeaderBB));
2760 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002761
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002762 isl_map *NextIterationMap =
2763 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002764
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002765 isl_set *UnionBackedgeCondition =
2766 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002767
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002768 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2769 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002770
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002771 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002772
2773 // If the latch is only reachable via error statements we skip it.
2774 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2775 if (!LatchBBDom)
2776 continue;
2777
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002778 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002779
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002780 TerminatorInst *TI = LatchBB->getTerminator();
2781 BranchInst *BI = dyn_cast<BranchInst>(TI);
2782 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002783 BackedgeCondition = isl_set_copy(LatchBBDom);
2784 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002785 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002786 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002787 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
2788 ConditionSets))
2789 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002790
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002791 // Free the non back edge condition set as we do not need it.
2792 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002793
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002794 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002795 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002796
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002797 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2798 assert(LatchLoopDepth >= LoopDepth);
2799 BackedgeCondition =
2800 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2801 LatchLoopDepth - LoopDepth);
2802 UnionBackedgeCondition =
2803 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002804 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002805
2806 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2807 for (int i = 0; i < LoopDepth; i++)
2808 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2809
2810 isl_set *UnionBackedgeConditionComplement =
2811 isl_set_complement(UnionBackedgeCondition);
2812 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2813 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2814 UnionBackedgeConditionComplement =
2815 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2816 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2817 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2818
2819 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2820 HeaderBBDom = Parts.second;
2821
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002822 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2823 // the bounded assumptions to the context as they are already implied by the
2824 // <nsw> tag.
2825 if (Affinator.hasNSWAddRecForLoop(L)) {
2826 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002827 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002828 }
2829
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002830 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002831 recordAssumption(INFINITELOOP, UnboundedCtx,
2832 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002833 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002834}
2835
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002836MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
2837 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2838 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2839 if (!PointerBase)
2840 return nullptr;
2841
2842 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase->getValue());
2843 if (!PointerBaseInst)
2844 return nullptr;
2845
2846 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2847 if (!BasePtrStmt)
2848 return nullptr;
2849
2850 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2851}
2852
2853bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2854 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00002855 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
2856 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
2857 bool Hoistable = NHCtx != nullptr;
2858 isl_set_free(NHCtx);
2859 return !Hoistable;
2860 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002861
2862 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2863 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2864 if (auto *BasePtrInst = dyn_cast<Instruction>(PointerBase->getValue()))
2865 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00002866 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002867
2868 return false;
2869}
2870
Johannes Doerfert5210da52016-06-02 11:06:54 +00002871bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002872 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00002873 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002874
2875 if (buildAliasGroups(AA))
Johannes Doerfert5210da52016-06-02 11:06:54 +00002876 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002877
2878 // If a problem occurs while building the alias groups we need to delete
2879 // this SCoP and pretend it wasn't valid in the first place. To this end
2880 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002881 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002882
2883 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2884 << " could not be created as the number of parameters involved "
2885 "is too high. The SCoP will be "
2886 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2887 "the maximal number of parameters but be advised that the "
2888 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00002889 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002890}
2891
Johannes Doerfert9143d672014-09-27 11:02:39 +00002892bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002893 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002894 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002895 // for all memory accesses inside the SCoP.
2896 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002897 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002898 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002899 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002900 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002901 // if their access domains intersect, otherwise they are in different
2902 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002903 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002904 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002905 // and maximal accesses to each array of a group in read only and non
2906 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002907 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2908
2909 AliasSetTracker AST(AA);
2910
2911 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002912 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002913 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002914
2915 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002916 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002917 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2918 isl_set_free(StmtDomain);
2919 if (StmtDomainEmpty)
2920 continue;
2921
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002922 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002923 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002924 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002925 if (!MA->isRead())
2926 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002927 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002928 if (MA->isRead() && isa<MemTransferInst>(Acc))
2929 PtrToAcc[cast<MemTransferInst>(Acc)->getSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002930 else
2931 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002932 AST.add(Acc);
2933 }
2934 }
2935
2936 SmallVector<AliasGroupTy, 4> AliasGroups;
2937 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002938 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002939 continue;
2940 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002941 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002942 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002943 if (AG.size() < 2)
2944 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002945 AliasGroups.push_back(std::move(AG));
2946 }
2947
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002948 // Split the alias groups based on their domain.
2949 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2950 AliasGroupTy NewAG;
2951 AliasGroupTy &AG = AliasGroups[u];
2952 AliasGroupTy::iterator AGI = AG.begin();
2953 isl_set *AGDomain = getAccessDomain(*AGI);
2954 while (AGI != AG.end()) {
2955 MemoryAccess *MA = *AGI;
2956 isl_set *MADomain = getAccessDomain(MA);
2957 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2958 NewAG.push_back(MA);
2959 AGI = AG.erase(AGI);
2960 isl_set_free(MADomain);
2961 } else {
2962 AGDomain = isl_set_union(AGDomain, MADomain);
2963 AGI++;
2964 }
2965 }
2966 if (NewAG.size() > 1)
2967 AliasGroups.push_back(std::move(NewAG));
2968 isl_set_free(AGDomain);
2969 }
2970
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002971 auto &F = getFunction();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002972 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002973 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2974 for (AliasGroupTy &AG : AliasGroups) {
2975 NonReadOnlyBaseValues.clear();
2976 ReadOnlyPairs.clear();
2977
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002978 if (AG.size() < 2) {
2979 AG.clear();
2980 continue;
2981 }
2982
Johannes Doerfert13771732014-10-01 12:40:46 +00002983 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002984 emitOptimizationRemarkAnalysis(
2985 F.getContext(), DEBUG_TYPE, F,
2986 (*II)->getAccessInstruction()->getDebugLoc(),
2987 "Possibly aliasing pointer, use restrict keyword.");
2988
Johannes Doerfert13771732014-10-01 12:40:46 +00002989 Value *BaseAddr = (*II)->getBaseAddr();
2990 if (HasWriteAccess.count(BaseAddr)) {
2991 NonReadOnlyBaseValues.insert(BaseAddr);
2992 II++;
2993 } else {
2994 ReadOnlyPairs[BaseAddr].insert(*II);
2995 II = AG.erase(II);
2996 }
2997 }
2998
2999 // If we don't have read only pointers check if there are at least two
3000 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00003001 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003002 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00003003 continue;
3004 }
3005
3006 // If we don't have non read only pointers clear the alias group.
3007 if (NonReadOnlyBaseValues.empty()) {
3008 AG.clear();
3009 continue;
3010 }
3011
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003012 // Check if we have non-affine accesses left, if so bail out as we cannot
3013 // generate a good access range yet.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003014 for (auto *MA : AG) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003015 if (!MA->isAffine()) {
3016 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3017 return false;
3018 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003019 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
3020 addRequiredInvariantLoad(
3021 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3022 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003023 for (auto &ReadOnlyPair : ReadOnlyPairs)
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003024 for (auto *MA : ReadOnlyPair.second) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003025 if (!MA->isAffine()) {
3026 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3027 return false;
3028 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003029 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
3030 addRequiredInvariantLoad(
3031 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3032 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003033
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003034 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003035 MinMaxAliasGroups.emplace_back();
3036 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3037 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
3038 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3039 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003040
3041 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003042
3043 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00003044 for (MemoryAccess *MA : AG)
3045 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003046
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003047 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
3048 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003049
3050 // Bail out if the number of values we need to compare is too large.
3051 // This is important as the number of comparisions grows quadratically with
3052 // the number of values we need to compare.
Johannes Doerfert5210da52016-06-02 11:06:54 +00003053 if (!Valid || (MinMaxAccessesNonReadOnly.size() + ReadOnlyPairs.size() >
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003054 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003055 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003056
3057 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003058 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003059 Accesses = isl_union_map_empty(getParamSpace());
3060
3061 for (const auto &ReadOnlyPair : ReadOnlyPairs)
3062 for (MemoryAccess *MA : ReadOnlyPair.second)
3063 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
3064
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003065 Valid =
3066 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003067
3068 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003069 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003070 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003071
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003072 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003073}
3074
Johannes Doerfertef744432016-05-23 12:42:38 +00003075/// @brief Get the smallest loop that contains @p S but is not in @p S.
3076static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003077 // Start with the smallest loop containing the entry and expand that
3078 // loop until it contains all blocks in the region. If there is a loop
3079 // containing all blocks in the region check if it is itself contained
3080 // and if so take the parent loop as it will be the smallest containing
3081 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003082 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003083 while (L) {
3084 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003085 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003086 AllContained &= L->contains(BB);
3087 if (AllContained)
3088 break;
3089 L = L->getParentLoop();
3090 }
3091
Johannes Doerfertef744432016-05-23 12:42:38 +00003092 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003093}
3094
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003095Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003096 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003097 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003098 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003099 MaxLoopDepth(0), DC(DC), IslCtx(isl_ctx_alloc(), isl_ctx_free),
3100 Context(nullptr), Affinator(this, LI), AssumedContext(nullptr),
3101 InvalidContext(nullptr), Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003102 if (IslOnErrorAbort)
3103 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003104 buildContext();
3105}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003106
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003107void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT,
3108 LoopInfo &LI) {
3109 buildInvariantEquivalenceClasses();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003110
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003111 if (!buildDomains(&R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003112 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003113
Johannes Doerfertff68f462016-04-19 14:49:42 +00003114 addUserAssumptions(AC, DT, LI);
3115
Johannes Doerfert26404542016-05-10 12:19:47 +00003116 // Remove empty statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003117 // Exit early in case there are no executable statements left in this scop.
Johannes Doerfert26404542016-05-10 12:19:47 +00003118 simplifySCoP(false, DT, LI);
Michael Kruseafe06702015-10-02 16:33:27 +00003119 if (Stmts.empty())
3120 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003121
Michael Krusecac948e2015-10-02 13:53:07 +00003122 // The ScopStmts now have enough information to initialize themselves.
3123 for (ScopStmt &Stmt : Stmts)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003124 Stmt.init(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00003125
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003126 // Check early for profitability. Afterwards it cannot change anymore,
3127 // only the runtime context could become infeasible.
3128 if (!isProfitable()) {
3129 invalidate(PROFITABLE, DebugLoc());
Tobias Grosser8286b832015-11-02 11:29:32 +00003130 return;
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003131 }
3132
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003133 buildSchedule(LI);
Tobias Grosser8286b832015-11-02 11:29:32 +00003134
3135 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003136 realignParams();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003137 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003138
3139 // After the context was fully constructed, thus all our knowledge about
3140 // the parameters is in there, we add all recorded assumptions to the
3141 // assumed/invalid context.
3142 addRecordedAssumptions();
3143
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003144 simplifyContexts();
Johannes Doerfert5210da52016-06-02 11:06:54 +00003145 if (!buildAliasChecks(AA))
3146 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003147
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003148 hoistInvariantLoads();
3149 verifyInvariantLoads();
Johannes Doerfert26404542016-05-10 12:19:47 +00003150 simplifySCoP(true, DT, LI);
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003151
3152 // Check late for a feasible runtime context because profitability did not
3153 // change.
3154 if (!hasFeasibleRuntimeContext()) {
3155 invalidate(PROFITABLE, DebugLoc());
3156 return;
3157 }
Tobias Grosser75805372011-04-29 06:27:02 +00003158}
3159
3160Scop::~Scop() {
3161 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003162 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003163 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003164 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003165
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003166 for (auto &It : ParameterIds)
3167 isl_id_free(It.second);
3168
Johannes Doerfert96425c22015-08-30 21:13:53 +00003169 for (auto It : DomainMap)
3170 isl_set_free(It.second);
3171
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003172 for (auto &AS : RecordedAssumptions)
3173 isl_set_free(AS.Set);
3174
Johannes Doerfertb164c792014-09-18 11:17:17 +00003175 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003176 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003177 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003178 isl_pw_multi_aff_free(MMA.first);
3179 isl_pw_multi_aff_free(MMA.second);
3180 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003181 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003182 isl_pw_multi_aff_free(MMA.first);
3183 isl_pw_multi_aff_free(MMA.second);
3184 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003185 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003186
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003187 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003188 isl_set_free(std::get<2>(IAClass));
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003189
3190 // Explicitly release all Scop objects and the underlying isl objects before
3191 // we relase the isl context.
3192 Stmts.clear();
3193 ScopArrayInfoMap.clear();
3194 AccFuncMap.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003195}
3196
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003197void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003198 // Check all array accesses for each base pointer and find a (virtual) element
3199 // size for the base pointer that divides all access functions.
3200 for (auto &Stmt : *this)
3201 for (auto *Access : Stmt) {
3202 if (!Access->isArrayKind())
3203 continue;
3204 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
3205 ScopArrayInfo::MK_Array)];
3206 if (SAI->getNumberOfDimensions() != 1)
3207 continue;
3208 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3209 auto *Subscript = Access->getSubscript(0);
3210 while (!isDivisible(Subscript, DivisibleSize, *SE))
3211 DivisibleSize /= 2;
3212 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3213 SAI->updateElementType(Ty);
3214 }
3215
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003216 for (auto &Stmt : *this)
3217 for (auto &Access : Stmt)
3218 Access->updateDimensionality();
3219}
3220
Johannes Doerfert26404542016-05-10 12:19:47 +00003221void Scop::simplifySCoP(bool AfterHoisting, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003222 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3223 ScopStmt &Stmt = *StmtIt;
3224
Johannes Doerfert26404542016-05-10 12:19:47 +00003225 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003226 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003227 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003228
Johannes Doerferteca9e892015-11-03 16:54:49 +00003229 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003230 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003231 bool OnlyRead = true;
3232 for (MemoryAccess *MA : Stmt) {
3233 if (MA->isRead())
3234 continue;
3235
3236 OnlyRead = false;
3237 break;
3238 }
3239
3240 RemoveStmt = OnlyRead;
3241 }
3242
Johannes Doerfert26404542016-05-10 12:19:47 +00003243 if (!RemoveStmt) {
3244 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003245 continue;
3246 }
3247
Johannes Doerfert26404542016-05-10 12:19:47 +00003248 // Remove the statement because it is unnecessary.
3249 if (Stmt.isRegionStmt())
3250 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3251 StmtMap.erase(BB);
3252 else
3253 StmtMap.erase(Stmt.getBasicBlock());
3254
3255 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003256 }
3257}
3258
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003259InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003260 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3261 if (!LInst)
3262 return nullptr;
3263
3264 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3265 LInst = cast<LoadInst>(Rep);
3266
Johannes Doerfert96e54712016-02-07 17:30:13 +00003267 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003268 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003269 for (auto &IAClass : InvariantEquivClasses) {
3270 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
3271 continue;
3272
3273 auto &MAs = std::get<1>(IAClass);
3274 for (auto *MA : MAs)
3275 if (MA->getAccessInstruction() == Val)
3276 return &IAClass;
3277 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003278
3279 return nullptr;
3280}
3281
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003282/// @brief Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003283static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003284 bool MAInvalidCtxIsEmpty,
3285 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003286 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3287 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3288 // TODO: We can provide more information for better but more expensive
3289 // results.
3290 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3291 LInst->getAlignment(), DL))
3292 return false;
3293
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003294 // If the location might be overwritten we do not hoist it unconditionally.
3295 //
3296 // TODO: This is probably to conservative.
3297 if (!NonHoistableCtxIsEmpty)
3298 return false;
3299
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003300 // If a dereferencable load is in a statement that is modeled precisely we can
3301 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003302 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003303 return true;
3304
3305 // Even if the statement is not modeled precisely we can hoist the load if it
3306 // does not involve any parameters that might have been specilized by the
3307 // statement domain.
3308 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3309 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3310 return false;
3311 return true;
3312}
3313
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003314void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003315
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003316 if (InvMAs.empty())
3317 return;
3318
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003319 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003320 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003321
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003322 // Get the context under which the statement is executed but remove the error
3323 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003324 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003325 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003326
Michael Krusebc150122016-05-02 12:25:18 +00003327 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctionsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003328 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003329 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3330 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003331 for (auto &InvMA : InvMAs)
3332 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003333 return;
3334 }
3335
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003336 // Project out all parameters that relate to loads in the statement. Otherwise
3337 // we could have cyclic dependences on the constraints under which the
3338 // hoisted loads are executed and we could not determine an order in which to
3339 // pre-load them. This happens because not only lower bounds are part of the
3340 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003341 for (auto &InvMA : InvMAs) {
3342 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003343 Instruction *AccInst = MA->getAccessInstruction();
3344 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003345 SetVector<Value *> Values;
3346 for (const SCEV *Parameter : Parameters) {
3347 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003348 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003349 if (!Values.count(AccInst))
3350 continue;
3351
3352 if (isl_id *ParamId = getIdForParam(Parameter)) {
3353 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3354 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3355 isl_id_free(ParamId);
3356 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003357 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003358 }
3359 }
3360
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003361 for (auto &InvMA : InvMAs) {
3362 auto *MA = InvMA.MA;
3363 auto *NHCtx = InvMA.NonHoistableCtx;
3364
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003365 // Check for another invariant access that accesses the same location as
3366 // MA and if found consolidate them. Otherwise create a new equivalence
3367 // class at the end of InvariantEquivClasses.
3368 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003369 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003370 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3371
Johannes Doerfert85676e32016-04-23 14:32:34 +00003372 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003373 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003374 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3375
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003376 isl_set *MACtx;
3377 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003378 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3379 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003380 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003381 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003382 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003383 } else {
3384 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003385 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003386 MACtx = isl_set_gist_params(MACtx, getContext());
3387 }
3388
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003389 bool Consolidated = false;
3390 for (auto &IAClass : InvariantEquivClasses) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00003391 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003392 continue;
3393
Johannes Doerfertdf880232016-03-03 12:26:58 +00003394 // If the pointer and the type is equal check if the access function wrt.
3395 // to the domain is equal too. It can happen that the domain fixes
3396 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003397 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003398 // create a new invariant load equivalence class.
3399 auto &MAs = std::get<1>(IAClass);
3400 if (!MAs.empty()) {
3401 auto *LastMA = MAs.front();
3402
3403 auto *AR = isl_map_range(MA->getAccessRelation());
3404 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3405 bool SameAR = isl_set_is_equal(AR, LastAR);
3406 isl_set_free(AR);
3407 isl_set_free(LastAR);
3408
3409 if (!SameAR)
3410 continue;
3411 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003412
3413 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003414 MAs.push_front(MA);
3415
Johannes Doerfertdf880232016-03-03 12:26:58 +00003416 Consolidated = true;
3417
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003418 // Unify the execution context of the class and this statement.
3419 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003420 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003421 IAClassDomainCtx =
3422 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003423 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003424 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003425 break;
3426 }
3427
3428 if (Consolidated)
3429 continue;
3430
3431 // If we did not consolidate MA, thus did not find an equivalence class
3432 // for it, we create a new one.
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003433 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA}, MACtx,
3434 Ty);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003435 }
3436
3437 isl_set_free(DomainCtx);
3438}
3439
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003440__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3441 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003442 // TODO: Loads that are not loop carried, hence are in a statement with
3443 // zero iterators, are by construction invariant, though we
3444 // currently "hoist" them anyway. This is necessary because we allow
3445 // them to be treated as parameters (e.g., in conditions) and our code
3446 // generation would otherwise use the old value.
3447
3448 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003449 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003450
3451 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003452 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003453
3454 // Skip accesses that have an invariant base pointer which is defined but
3455 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3456 // returns a pointer that is used as a base address. However, as we want
3457 // to hoist indirect pointers, we allow the base pointer to be defined in
3458 // the region if it is also a memory access. Each ScopArrayInfo object
3459 // that has a base pointer origin has a base pointer that is loaded and
3460 // that it is invariant, thus it will be hoisted too. However, if there is
3461 // no base pointer origin we check that the base pointer is defined
3462 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003463 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003464 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003465 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003466
3467 // Skip accesses in non-affine subregions as they might not be executed
3468 // under the same condition as the entry of the non-affine subregion.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003469 if (BB != LI->getParent())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003470 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003471
3472 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003473 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003474
3475 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3476 Stmt.getNumIterators())) {
3477 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003478 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003479 }
3480
3481 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3482 isl_set *AccessRange = isl_map_range(AccessRelation);
3483
3484 isl_union_map *Written = isl_union_map_intersect_range(
3485 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003486 auto *WrittenCtx = isl_union_map_params(Written);
3487 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003488
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003489 if (!IsWritten)
3490 return WrittenCtx;
3491
3492 WrittenCtx = isl_set_remove_divs(WrittenCtx);
3493 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctionsInDomain;
3494 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3495 isl_set_free(WrittenCtx);
3496 return nullptr;
3497 }
3498
3499 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3500 AS_RESTRICTION);
3501 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003502}
3503
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003504void Scop::verifyInvariantLoads() {
3505 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003506 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003507 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003508 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003509 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003510 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3511 return;
3512 }
3513 }
3514}
3515
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003516void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003517 if (!PollyInvariantLoadHoisting)
3518 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003519
Tobias Grosser0865e7752016-02-29 07:29:42 +00003520 isl_union_map *Writes = getWrites();
3521 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003522 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003523
Tobias Grosser0865e7752016-02-29 07:29:42 +00003524 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003525 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3526 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003527
3528 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003529 for (auto InvMA : InvariantAccesses)
3530 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003531 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003532 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003533 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003534}
3535
Johannes Doerfert80ef1102014-11-07 08:31:31 +00003536const ScopArrayInfo *
Tobias Grossercc779502016-02-02 13:22:54 +00003537Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003538 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003539 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003540 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003541 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003542 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003543 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003544 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003545 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003546 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003547 // In case of mismatching array sizes, we bail out by setting the run-time
3548 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003549 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003550 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003551 }
Tobias Grosserab671442015-05-23 05:58:27 +00003552 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003553}
3554
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003555const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003556 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003557 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003558 assert(SAI && "No ScopArrayInfo available for this base pointer");
3559 return SAI;
3560}
3561
Tobias Grosser74394f02013-01-14 22:40:23 +00003562std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003563
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003564std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003565 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003566 return stringFromIslObj(AssumedContext);
3567}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003568
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003569std::string Scop::getInvalidContextStr() const {
3570 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003571}
Tobias Grosser75805372011-04-29 06:27:02 +00003572
3573std::string Scop::getNameStr() const {
3574 std::string ExitName, EntryName;
3575 raw_string_ostream ExitStr(ExitName);
3576 raw_string_ostream EntryStr(EntryName);
3577
Tobias Grosserf240b482014-01-09 10:42:15 +00003578 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003579 EntryStr.str();
3580
3581 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003582 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003583 ExitStr.str();
3584 } else
3585 ExitName = "FunctionExit";
3586
3587 return EntryName + "---" + ExitName;
3588}
3589
Tobias Grosser74394f02013-01-14 22:40:23 +00003590__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003591__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003592 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003593}
3594
Tobias Grossere86109f2013-10-29 21:05:49 +00003595__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003596 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003597 return isl_set_copy(AssumedContext);
3598}
3599
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003600bool Scop::isProfitable() const {
3601 if (PollyProcessUnprofitable)
3602 return true;
3603
3604 if (!hasFeasibleRuntimeContext())
3605 return false;
3606
3607 if (isEmpty())
3608 return false;
3609
3610 unsigned OptimizableStmtsOrLoops = 0;
3611 for (auto &Stmt : *this) {
3612 if (Stmt.getNumIterators() == 0)
3613 continue;
3614
3615 bool ContainsArrayAccs = false;
3616 bool ContainsScalarAccs = false;
3617 for (auto *MA : Stmt) {
3618 if (MA->isRead())
3619 continue;
3620 ContainsArrayAccs |= MA->isArrayKind();
3621 ContainsScalarAccs |= MA->isScalarKind();
3622 }
3623
3624 if (ContainsArrayAccs && !ContainsScalarAccs)
3625 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3626 }
3627
3628 return OptimizableStmtsOrLoops > 1;
3629}
3630
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003631bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003632 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003633 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003634 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3635 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3636 isl_set_is_subset(PositiveContext, NegativeContext));
3637 isl_set_free(PositiveContext);
3638 if (!IsFeasible) {
3639 isl_set_free(NegativeContext);
3640 return false;
3641 }
3642
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003643 auto *DomainContext = isl_union_set_params(getDomains());
3644 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003645 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003646 isl_set_free(NegativeContext);
3647 isl_set_free(DomainContext);
3648
Johannes Doerfert43788c52015-08-20 05:58:56 +00003649 return IsFeasible;
3650}
3651
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003652static std::string toString(AssumptionKind Kind) {
3653 switch (Kind) {
3654 case ALIASING:
3655 return "No-aliasing";
3656 case INBOUNDS:
3657 return "Inbounds";
3658 case WRAPPING:
3659 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00003660 case UNSIGNED:
3661 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003662 case COMPLEXITY:
3663 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003664 case PROFITABLE:
3665 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003666 case ERRORBLOCK:
3667 return "No-error";
3668 case INFINITELOOP:
3669 return "Finite loop";
3670 case INVARIANTLOAD:
3671 return "Invariant load";
3672 case DELINEARIZATION:
3673 return "Delinearization";
3674 }
3675 llvm_unreachable("Unknown AssumptionKind!");
3676}
3677
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003678bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3679 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert2f705842016-04-12 16:09:44 +00003680 if (PollyRemarksMinimal) {
3681 if (Sign == AS_ASSUMPTION) {
3682 if (isl_set_is_subset(Context, Set))
3683 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003684
Johannes Doerfert2f705842016-04-12 16:09:44 +00003685 if (isl_set_is_subset(AssumedContext, Set))
3686 return false;
3687 } else {
3688 if (isl_set_is_disjoint(Set, Context))
3689 return false;
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003690
Johannes Doerfert2f705842016-04-12 16:09:44 +00003691 if (isl_set_is_subset(Set, InvalidContext))
3692 return false;
3693 }
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003694 }
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003695
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003696 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003697 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3698 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003699 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003700 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003701}
3702
3703void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003704 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003705 // Simplify the assumptions/restrictions first.
3706 Set = isl_set_gist_params(Set, getContext());
3707
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003708 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3709 isl_set_free(Set);
3710 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003711 }
3712
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003713 if (Sign == AS_ASSUMPTION) {
3714 AssumedContext = isl_set_intersect(AssumedContext, Set);
3715 AssumedContext = isl_set_coalesce(AssumedContext);
3716 } else {
3717 InvalidContext = isl_set_union(InvalidContext, Set);
3718 InvalidContext = isl_set_coalesce(InvalidContext);
3719 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003720}
3721
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003722void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003723 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
3724 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003725}
3726
3727void Scop::addRecordedAssumptions() {
3728 while (!RecordedAssumptions.empty()) {
3729 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003730
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003731 if (!AS.BB) {
3732 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
3733 continue;
3734 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003735
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003736 // If the domain was deleted the assumptions are void.
3737 isl_set *Dom = getDomainConditions(AS.BB);
3738 if (!Dom) {
3739 isl_set_free(AS.Set);
3740 continue;
3741 }
3742
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003743 // If a basic block was given use its domain to simplify the assumption.
3744 // In case of restrictions we know they only have to hold on the domain,
3745 // thus we can intersect them with the domain of the block. However, for
3746 // assumptions the domain has to imply them, thus:
3747 // _ _____
3748 // Dom => S <==> A v B <==> A - B
3749 //
3750 // To avoid the complement we will register A - B as a restricton not an
3751 // assumption.
3752 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003753 if (AS.Sign == AS_RESTRICTION)
3754 S = isl_set_params(isl_set_intersect(S, Dom));
3755 else /* (AS.Sign == AS_ASSUMPTION) */
3756 S = isl_set_params(isl_set_subtract(Dom, S));
3757
3758 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003759 }
3760}
3761
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003762void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003763 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003764}
3765
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003766__isl_give isl_set *Scop::getInvalidContext() const {
3767 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003768}
3769
Tobias Grosser75805372011-04-29 06:27:02 +00003770void Scop::printContext(raw_ostream &OS) const {
3771 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003772 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003773
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003774 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003775 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003776
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003777 OS.indent(4) << "Invalid Context:\n";
3778 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003779
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003780 unsigned Dim = 0;
3781 for (const SCEV *Parameter : Parameters)
3782 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003783}
3784
Johannes Doerfertb164c792014-09-18 11:17:17 +00003785void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003786 int noOfGroups = 0;
3787 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003788 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003789 noOfGroups += 1;
3790 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003791 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003792 }
3793
Tobias Grosserbb853c22015-07-25 12:31:03 +00003794 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003795 if (MinMaxAliasGroups.empty()) {
3796 OS.indent(8) << "n/a\n";
3797 return;
3798 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003799
Tobias Grosserbb853c22015-07-25 12:31:03 +00003800 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003801
3802 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003803 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003804 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003805 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003806 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3807 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003808 }
3809 OS << " ]]\n";
3810 }
3811
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003812 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003813 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003814 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003815 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003816 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3817 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003818 }
3819 OS << " ]]\n";
3820 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003821 }
3822}
3823
Tobias Grosser75805372011-04-29 06:27:02 +00003824void Scop::printStatements(raw_ostream &OS) const {
3825 OS << "Statements {\n";
3826
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003827 for (const ScopStmt &Stmt : *this)
3828 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003829
3830 OS.indent(4) << "}\n";
3831}
3832
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003833void Scop::printArrayInfo(raw_ostream &OS) const {
3834 OS << "Arrays {\n";
3835
Tobias Grosserab671442015-05-23 05:58:27 +00003836 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003837 Array.second->print(OS);
3838
3839 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003840
3841 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3842
3843 for (auto &Array : arrays())
3844 Array.second->print(OS, /* SizeAsPwAff */ true);
3845
3846 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003847}
3848
Tobias Grosser75805372011-04-29 06:27:02 +00003849void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003850 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003851 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003852 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003853 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003854 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003855 const auto &MAs = std::get<1>(IAClass);
3856 if (MAs.empty()) {
3857 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003858 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003859 MAs.front()->print(OS);
3860 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003861 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003862 }
3863 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003864 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003865 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003866 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003867 printStatements(OS.indent(4));
3868}
3869
3870void Scop::dump() const { print(dbgs()); }
3871
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003872isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003873
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003874__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
3875 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003876 // First try to use the SCEVAffinator to generate a piecewise defined
3877 // affine function from @p E in the context of @p BB. If that tasks becomes to
3878 // complex the affinator might return a nullptr. In such a case we invalidate
3879 // the SCoP and return a dummy value. This way we do not need to add error
3880 // handling cdoe to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003881 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003882 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00003883 // TODO: We could use a heuristic and either use:
3884 // SCEVAffinator::takeNonNegativeAssumption
3885 // or
3886 // SCEVAffinator::interpretAsUnsigned
3887 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003888 if (NonNegative)
3889 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003890 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003891 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003892
3893 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
3894 invalidate(COMPLEXITY, DL);
3895 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003896}
3897
Tobias Grosser808cd692015-07-14 09:33:13 +00003898__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003899 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003900
Tobias Grosser808cd692015-07-14 09:33:13 +00003901 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003902 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003903
3904 return Domain;
3905}
3906
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003907__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
3908 PWACtx PWAC = getPwAff(E, BB);
3909 isl_set_free(PWAC.second);
3910 return PWAC.first;
3911}
3912
Tobias Grossere5a35142015-11-12 14:07:09 +00003913__isl_give isl_union_map *
3914Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3915 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003916
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003917 for (ScopStmt &Stmt : *this) {
3918 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003919 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003920 continue;
3921
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003922 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003923 isl_map *AccessDomain = MA->getAccessRelation();
3924 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003925 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003926 }
3927 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003928 return isl_union_map_coalesce(Accesses);
3929}
3930
3931__isl_give isl_union_map *Scop::getMustWrites() {
3932 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003933}
3934
3935__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003936 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003937}
3938
Tobias Grosser37eb4222014-02-20 21:43:54 +00003939__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003940 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003941}
3942
3943__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003944 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003945}
3946
Tobias Grosser2ac23382015-11-12 14:07:13 +00003947__isl_give isl_union_map *Scop::getAccesses() {
3948 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3949}
3950
Tobias Grosser808cd692015-07-14 09:33:13 +00003951__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003952 auto *Tree = getScheduleTree();
3953 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00003954 isl_schedule_free(Tree);
3955 return S;
3956}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003957
Tobias Grosser808cd692015-07-14 09:33:13 +00003958__isl_give isl_schedule *Scop::getScheduleTree() const {
3959 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3960 getDomains());
3961}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003962
Tobias Grosser808cd692015-07-14 09:33:13 +00003963void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3964 auto *S = isl_schedule_from_domain(getDomains());
3965 S = isl_schedule_insert_partial_schedule(
3966 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3967 isl_schedule_free(Schedule);
3968 Schedule = S;
3969}
3970
3971void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3972 isl_schedule_free(Schedule);
3973 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003974}
3975
3976bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3977 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003978 for (ScopStmt &Stmt : *this) {
3979 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003980 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3981 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3982
3983 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3984 isl_union_set_free(StmtDomain);
3985 isl_union_set_free(NewStmtDomain);
3986 continue;
3987 }
3988
3989 Changed = true;
3990
3991 isl_union_set_free(StmtDomain);
3992 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3993
3994 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003995 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003996 isl_union_set_free(NewStmtDomain);
3997 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003998 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003999 }
4000 isl_union_set_free(Domain);
4001 return Changed;
4002}
4003
Tobias Grosser75805372011-04-29 06:27:02 +00004004ScalarEvolution *Scop::getSE() const { return SE; }
4005
Tobias Grosser808cd692015-07-14 09:33:13 +00004006struct MapToDimensionDataTy {
4007 int N;
4008 isl_union_pw_multi_aff *Res;
4009};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004010
Tobias Grosser808cd692015-07-14 09:33:13 +00004011// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004012// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004013//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004014// @param Set The input set.
4015// @param User->N The dimension to map to.
4016// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004017//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004018// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004019static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4020 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4021 int Dim;
4022 isl_space *Space;
4023 isl_pw_multi_aff *PMA;
4024
4025 Dim = isl_set_dim(Set, isl_dim_set);
4026 Space = isl_set_get_space(Set);
4027 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4028 Dim - Data->N);
4029 if (Data->N > 1)
4030 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4031 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4032
4033 isl_set_free(Set);
4034
4035 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004036}
4037
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004038// @brief Create an isl_multi_union_aff that defines an identity mapping
4039// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004040//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004041// # Example:
4042//
4043// Domain: { A[i,j]; B[i,j,k] }
4044// N: 1
4045//
4046// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4047//
4048// @param USet A union set describing the elements for which to generate a
4049// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004050// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004051// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004052static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004053mapToDimension(__isl_take isl_union_set *USet, int N) {
4054 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004055 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004056 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004057
Tobias Grosser808cd692015-07-14 09:33:13 +00004058 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004059
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004060 auto *Space = isl_union_set_get_space(USet);
4061 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004062
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004063 Data = {N, PwAff};
4064
4065 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004066 (void)Res;
4067
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004068 assert(Res == isl_stat_ok);
4069
4070 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004071 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4072}
4073
Tobias Grosser316b5b22015-11-11 19:28:14 +00004074void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00004075 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00004076 Stmts.emplace_back(*this, *BB);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004077 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004078 StmtMap[BB] = Stmt;
4079 } else {
4080 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00004081 Stmts.emplace_back(*this, *R);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004082 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004083 for (BasicBlock *BB : R->blocks())
4084 StmtMap[BB] = Stmt;
4085 }
Tobias Grosser808cd692015-07-14 09:33:13 +00004086}
4087
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004088void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004089 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004090 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004091 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004092 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4093 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004094}
4095
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004096/// To generate a schedule for the elements in a Region we traverse the Region
4097/// in reverse-post-order and add the contained RegionNodes in traversal order
4098/// to the schedule of the loop that is currently at the top of the LoopStack.
4099/// For loop-free codes, this results in a correct sequential ordering.
4100///
4101/// Example:
4102/// bb1(0)
4103/// / \.
4104/// bb2(1) bb3(2)
4105/// \ / \.
4106/// bb4(3) bb5(4)
4107/// \ /
4108/// bb6(5)
4109///
4110/// Including loops requires additional processing. Whenever a loop header is
4111/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4112/// from an empty schedule, we first process all RegionNodes that are within
4113/// this loop and complete the sequential schedule at this loop-level before
4114/// processing about any other nodes. To implement this
4115/// loop-nodes-first-processing, the reverse post-order traversal is
4116/// insufficient. Hence, we additionally check if the traversal yields
4117/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4118/// These region-nodes are then queue and only traverse after the all nodes
4119/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004120void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004121 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004122
4123 ReversePostOrderTraversal<Region *> RTraversal(R);
4124 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4125 std::deque<RegionNode *> DelayList;
4126 bool LastRNWaiting = false;
4127
4128 // Iterate over the region @p R in reverse post-order but queue
4129 // sub-regions/blocks iff they are not part of the last encountered but not
4130 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4131 // that we queued the last sub-region/block from the reverse post-order
4132 // iterator. If it is set we have to explore the next sub-region/block from
4133 // the iterator (if any) to guarantee progress. If it is not set we first try
4134 // the next queued sub-region/blocks.
4135 while (!WorkList.empty() || !DelayList.empty()) {
4136 RegionNode *RN;
4137
4138 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4139 RN = WorkList.front();
4140 WorkList.pop_front();
4141 LastRNWaiting = false;
4142 } else {
4143 RN = DelayList.front();
4144 DelayList.pop_front();
4145 }
4146
4147 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004148 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004149 L = OuterScopLoop;
4150
Tobias Grosser151ae322016-04-03 19:36:52 +00004151 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004152 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004153 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004154 LastRNWaiting = true;
4155 DelayList.push_back(RN);
4156 continue;
4157 }
4158 LoopStack.push_back({L, nullptr, 0});
4159 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004160 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004161 }
4162
4163 return;
4164}
4165
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004166void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004167
Tobias Grosser8362c262016-01-06 15:30:06 +00004168 if (RN->isSubRegion()) {
4169 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004170 if (!isNonAffineSubRegion(LocalRegion)) {
4171 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004172 return;
4173 }
4174 }
Michael Kruse046dde42015-08-10 13:01:57 +00004175
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004176 auto &LoopData = LoopStack.back();
4177 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004178
Michael Kruse6f7721f2016-02-24 22:08:19 +00004179 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004180 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4181 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004182 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004183 }
4184
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004185 // Check if we just processed the last node in this loop. If we did, finalize
4186 // the loop by:
4187 //
4188 // - adding new schedule dimensions
4189 // - folding the resulting schedule into the parent loop schedule
4190 // - dropping the loop schedule from the LoopStack.
4191 //
4192 // Then continue to check surrounding loops, which might also have been
4193 // completed by this node.
4194 while (LoopData.L &&
4195 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004196 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004197 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004198
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004199 LoopStack.pop_back();
4200 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004201
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004202 if (Schedule) {
4203 auto *Domain = isl_schedule_get_domain(Schedule);
4204 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4205 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4206 NextLoopData.Schedule =
4207 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004208 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004209
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004210 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4211 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004212 }
Tobias Grosser75805372011-04-29 06:27:02 +00004213}
4214
Michael Kruse6f7721f2016-02-24 22:08:19 +00004215ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004216 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004217 if (StmtMapIt == StmtMap.end())
4218 return nullptr;
4219 return StmtMapIt->second;
4220}
4221
Michael Kruse6f7721f2016-02-24 22:08:19 +00004222ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4223 if (RN->isSubRegion())
4224 return getStmtFor(RN->getNodeAs<Region>());
4225 return getStmtFor(RN->getNodeAs<BasicBlock>());
4226}
4227
4228ScopStmt *Scop::getStmtFor(Region *R) const {
4229 ScopStmt *Stmt = getStmtFor(R->getEntry());
4230 assert(!Stmt || Stmt->getRegion() == R);
4231 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004232}
4233
Johannes Doerfert96425c22015-08-30 21:13:53 +00004234int Scop::getRelativeLoopDepth(const Loop *L) const {
4235 Loop *OuterLoop =
4236 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4237 if (!OuterLoop)
4238 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004239 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4240}
4241
Johannes Doerfert57a73172016-05-23 12:45:17 +00004242void ScopInfo::buildPHIAccesses(PHINode *PHI, Region *NonAffineSubRegion,
4243 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00004244
4245 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
4246 // true, are not modeled as ordinary PHI nodes as they are not part of the
4247 // region. However, we model the operands in the predecessor blocks that are
4248 // part of the region as regular scalar accesses.
4249
4250 // If we can synthesize a PHI we can skip it, however only if it is in
4251 // the region. If it is not it can only be in the exit block of the region.
4252 // In this case we model the operands but not the PHI itself.
Johannes Doerfert99191c72016-05-31 09:41:04 +00004253 auto *Scope = LI.getLoopFor(PHI->getParent());
4254 if (!IsExitBlock && canSynthesize(PHI, *scop, &LI, &SE, Scope))
Michael Kruse7bf39442015-09-10 12:46:52 +00004255 return;
4256
4257 // PHI nodes are modeled as if they had been demoted prior to the SCoP
4258 // detection. Hence, the PHI is a load of a new memory location in which the
4259 // incoming value was written at the end of the incoming basic block.
4260 bool OnlyNonAffineSubRegionOperands = true;
4261 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
4262 Value *Op = PHI->getIncomingValue(u);
4263 BasicBlock *OpBB = PHI->getIncomingBlock(u);
4264
4265 // Do not build scalar dependences inside a non-affine subregion.
4266 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
4267 continue;
4268
4269 OnlyNonAffineSubRegionOperands = false;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004270 ensurePHIWrite(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00004271 }
4272
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004273 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
4274 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00004275 }
4276}
4277
Michael Kruse2e02d562016-02-06 09:19:40 +00004278void ScopInfo::buildScalarDependences(Instruction *Inst) {
4279 assert(!isa<PHINode>(Inst));
Michael Kruse7bf39442015-09-10 12:46:52 +00004280
Michael Kruse2e02d562016-02-06 09:19:40 +00004281 // Pull-in required operands.
4282 for (Use &Op : Inst->operands())
4283 ensureValueRead(Op.get(), Inst->getParent());
4284}
Michael Kruse7bf39442015-09-10 12:46:52 +00004285
Michael Kruse2e02d562016-02-06 09:19:40 +00004286void ScopInfo::buildEscapingDependences(Instruction *Inst) {
Michael Kruse2e02d562016-02-06 09:19:40 +00004287 // Check for uses of this instruction outside the scop. Because we do not
4288 // iterate over such instructions and therefore did not "ensure" the existence
4289 // of a write, we must determine such use here.
4290 for (Use &U : Inst->uses()) {
4291 Instruction *UI = dyn_cast<Instruction>(U.getUser());
4292 if (!UI)
Michael Kruse7bf39442015-09-10 12:46:52 +00004293 continue;
4294
Michael Kruse2e02d562016-02-06 09:19:40 +00004295 BasicBlock *UseParent = getUseBlock(U);
4296 BasicBlock *UserParent = UI->getParent();
Michael Kruse7bf39442015-09-10 12:46:52 +00004297
Michael Kruse2e02d562016-02-06 09:19:40 +00004298 // An escaping value is either used by an instruction not within the scop,
4299 // or (when the scop region's exit needs to be simplified) by a PHI in the
4300 // scop's exit block. This is because region simplification before code
4301 // generation inserts new basic blocks before the PHI such that its incoming
4302 // blocks are not in the scop anymore.
Johannes Doerfert952b5302016-05-23 12:40:48 +00004303 if (!scop->contains(UseParent) ||
Johannes Doerfertef744432016-05-23 12:42:38 +00004304 (isa<PHINode>(UI) && scop->isExit(UserParent) &&
4305 scop->hasSingleExitEdge())) {
Michael Kruse2e02d562016-02-06 09:19:40 +00004306 // At least one escaping use found.
4307 ensureValueWrite(Inst);
4308 break;
Michael Kruse7bf39442015-09-10 12:46:52 +00004309 }
4310 }
Michael Kruse7bf39442015-09-10 12:46:52 +00004311}
4312
Johannes Doerfert57a73172016-05-23 12:45:17 +00004313bool ScopInfo::buildAccessMultiDimFixed(MemAccInst Inst, Loop *L) {
Michael Kruse70131d32016-01-27 17:09:17 +00004314 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004315 Type *ElementType = Val->getType();
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004316 Value *Address = Inst.getPointerOperand();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004317 const SCEV *AccessFunction = SE.getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00004318 const SCEVUnknown *BasePointer =
Johannes Doerfert99191c72016-05-31 09:41:04 +00004319 dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004320 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004321 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00004322
Michael Kruse37d136e2016-02-26 16:08:24 +00004323 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
4324 auto *Src = BitCast->getOperand(0);
4325 auto *SrcTy = Src->getType();
4326 auto *DstTy = BitCast->getType();
Johannes Doerfert41725a12016-04-08 19:20:03 +00004327 // Do not try to delinearize non-sized (opaque) pointers.
4328 if ((SrcTy->isPointerTy() && !SrcTy->getPointerElementType()->isSized()) ||
4329 (DstTy->isPointerTy() && !DstTy->getPointerElementType()->isSized())) {
4330 return false;
4331 }
Michael Kruse436c9062016-04-08 16:20:08 +00004332 if (SrcTy->isPointerTy() && DstTy->isPointerTy() &&
Johannes Doerfert99191c72016-05-31 09:41:04 +00004333 DL.getTypeAllocSize(SrcTy->getPointerElementType()) ==
4334 DL.getTypeAllocSize(DstTy->getPointerElementType()))
Michael Kruse37d136e2016-02-26 16:08:24 +00004335 Address = Src;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00004336 }
Michael Kruse37d136e2016-02-26 16:08:24 +00004337
4338 auto *GEP = dyn_cast<GetElementPtrInst>(Address);
4339 if (!GEP)
4340 return false;
4341
4342 std::vector<const SCEV *> Subscripts;
4343 std::vector<int> Sizes;
Johannes Doerfert99191c72016-05-31 09:41:04 +00004344 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Michael Kruse37d136e2016-02-26 16:08:24 +00004345 auto *BasePtr = GEP->getOperand(0);
4346
Tobias Grosser535afd82016-04-05 06:23:45 +00004347 if (auto *BasePtrCast = dyn_cast<BitCastInst>(BasePtr))
4348 BasePtr = BasePtrCast->getOperand(0);
4349
4350 // Check for identical base pointers to ensure that we do not miss index
4351 // offsets that have been added before this GEP is applied.
4352 if (BasePtr != BasePointer->getValue())
4353 return false;
4354
Michael Kruse37d136e2016-02-26 16:08:24 +00004355 std::vector<const SCEV *> SizesSCEV;
4356
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004357 const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads();
Michael Kruse37d136e2016-02-26 16:08:24 +00004358 for (auto *Subscript : Subscripts) {
4359 InvariantLoadsSetTy AccessILS;
Johannes Doerfert99191c72016-05-31 09:41:04 +00004360 if (!isAffineExpr(&scop->getRegion(), L, Subscript, SE, &AccessILS))
Michael Kruse37d136e2016-02-26 16:08:24 +00004361 return false;
4362
4363 for (LoadInst *LInst : AccessILS)
4364 if (!ScopRIL.count(LInst))
4365 return false;
4366 }
4367
4368 if (Sizes.empty())
4369 return false;
4370
4371 for (auto V : Sizes)
Johannes Doerfert99191c72016-05-31 09:41:04 +00004372 SizesSCEV.push_back(SE.getSCEV(
Michael Kruse37d136e2016-02-26 16:08:24 +00004373 ConstantInt::get(IntegerType::getInt64Ty(BasePtr->getContext()), V)));
4374
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004375 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, true,
Michael Kruse37d136e2016-02-26 16:08:24 +00004376 Subscripts, SizesSCEV, Val);
4377 return true;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004378}
4379
Johannes Doerfert57a73172016-05-23 12:45:17 +00004380bool ScopInfo::buildAccessMultiDimParam(MemAccInst Inst, Loop *L) {
Michael Kruse37d136e2016-02-26 16:08:24 +00004381 if (!PollyDelinearize)
4382 return false;
4383
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004384 Value *Address = Inst.getPointerOperand();
4385 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004386 Type *ElementType = Val->getType();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004387 unsigned ElementSize = DL.getTypeAllocSize(ElementType);
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004388 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004389 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004390
Johannes Doerfert99191c72016-05-31 09:41:04 +00004391 const SCEV *AccessFunction = SE.getSCEVAtScope(Address, L);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004392 const SCEVUnknown *BasePointer =
Johannes Doerfert99191c72016-05-31 09:41:04 +00004393 dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004394
4395 assert(BasePointer && "Could not find base pointer");
Tobias Grosser5fd8c092015-09-17 17:28:15 +00004396
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004397 auto &InsnToMemAcc = scop->getInsnToMemAccMap();
Michael Kruse7bf39442015-09-10 12:46:52 +00004398 auto AccItr = InsnToMemAcc.find(Inst);
Michael Kruse37d136e2016-02-26 16:08:24 +00004399 if (AccItr == InsnToMemAcc.end())
4400 return false;
Tobias Grosser5d51afe2016-02-02 16:46:45 +00004401
Michael Kruse37d136e2016-02-26 16:08:24 +00004402 std::vector<const SCEV *> Sizes(
4403 AccItr->second.Shape->DelinearizedSizes.begin(),
4404 AccItr->second.Shape->DelinearizedSizes.end());
4405 // Remove the element size. This information is already provided by the
4406 // ElementSize parameter. In case the element size of this access and the
4407 // element size used for delinearization differs the delinearization is
4408 // incorrect. Hence, we invalidate the scop.
4409 //
4410 // TODO: Handle delinearization with differing element sizes.
4411 auto DelinearizedSize =
4412 cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue();
4413 Sizes.pop_back();
4414 if (ElementSize != DelinearizedSize)
4415 scop->invalidate(DELINEARIZATION, Inst->getDebugLoc());
4416
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004417 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, true,
Michael Kruse37d136e2016-02-26 16:08:24 +00004418 AccItr->second.DelinearizedSubscripts, Sizes, Val);
4419 return true;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004420}
4421
Johannes Doerfert57a73172016-05-23 12:45:17 +00004422bool ScopInfo::buildAccessMemIntrinsic(MemAccInst Inst, Loop *L) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004423 auto *MemIntr = dyn_cast_or_null<MemIntrinsic>(Inst);
4424
4425 if (MemIntr == nullptr)
Johannes Doerfertcea61932016-02-21 19:13:19 +00004426 return false;
4427
Johannes Doerfert99191c72016-05-31 09:41:04 +00004428 auto *LengthVal = SE.getSCEVAtScope(MemIntr->getLength(), L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00004429 assert(LengthVal);
4430
Johannes Doerferta7920982016-02-25 14:08:48 +00004431 // Check if the length val is actually affine or if we overapproximate it
4432 InvariantLoadsSetTy AccessILS;
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004433 const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads();
Johannes Doerfert57a73172016-05-23 12:45:17 +00004434 bool LengthIsAffine =
Johannes Doerfert99191c72016-05-31 09:41:04 +00004435 isAffineExpr(&scop->getRegion(), L, LengthVal, SE, &AccessILS);
Johannes Doerferta7920982016-02-25 14:08:48 +00004436 for (LoadInst *LInst : AccessILS)
4437 if (!ScopRIL.count(LInst))
4438 LengthIsAffine = false;
4439 if (!LengthIsAffine)
4440 LengthVal = nullptr;
4441
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004442 auto *DestPtrVal = MemIntr->getDest();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004443 assert(DestPtrVal);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004444
Johannes Doerfert99191c72016-05-31 09:41:04 +00004445 auto *DestAccFunc = SE.getSCEVAtScope(DestPtrVal, L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00004446 assert(DestAccFunc);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004447 // Ignore accesses to "NULL".
4448 // TODO: We could use this to optimize the region further, e.g., intersect
4449 // the context with
4450 // isl_set_complement(isl_set_params(getDomain()))
4451 // as we know it would be undefined to execute this instruction anyway.
4452 if (DestAccFunc->isZero())
4453 return true;
4454
Johannes Doerfert99191c72016-05-31 09:41:04 +00004455 auto *DestPtrSCEV = dyn_cast<SCEVUnknown>(SE.getPointerBase(DestAccFunc));
Johannes Doerfertcea61932016-02-21 19:13:19 +00004456 assert(DestPtrSCEV);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004457 DestAccFunc = SE.getMinusSCEV(DestAccFunc, DestPtrSCEV);
Johannes Doerfertcea61932016-02-21 19:13:19 +00004458 addArrayAccess(Inst, MemoryAccess::MUST_WRITE, DestPtrSCEV->getValue(),
4459 IntegerType::getInt8Ty(DestPtrVal->getContext()), false,
4460 {DestAccFunc, LengthVal}, {}, Inst.getValueOperand());
4461
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004462 auto *MemTrans = dyn_cast<MemTransferInst>(MemIntr);
4463 if (!MemTrans)
Johannes Doerfertcea61932016-02-21 19:13:19 +00004464 return true;
4465
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004466 auto *SrcPtrVal = MemTrans->getSource();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004467 assert(SrcPtrVal);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004468
Johannes Doerfert99191c72016-05-31 09:41:04 +00004469 auto *SrcAccFunc = SE.getSCEVAtScope(SrcPtrVal, L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00004470 assert(SrcAccFunc);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004471 // Ignore accesses to "NULL".
4472 // TODO: See above TODO
4473 if (SrcAccFunc->isZero())
4474 return true;
4475
Johannes Doerfert99191c72016-05-31 09:41:04 +00004476 auto *SrcPtrSCEV = dyn_cast<SCEVUnknown>(SE.getPointerBase(SrcAccFunc));
Johannes Doerfertcea61932016-02-21 19:13:19 +00004477 assert(SrcPtrSCEV);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004478 SrcAccFunc = SE.getMinusSCEV(SrcAccFunc, SrcPtrSCEV);
Johannes Doerfertcea61932016-02-21 19:13:19 +00004479 addArrayAccess(Inst, MemoryAccess::READ, SrcPtrSCEV->getValue(),
4480 IntegerType::getInt8Ty(SrcPtrVal->getContext()), false,
4481 {SrcAccFunc, LengthVal}, {}, Inst.getValueOperand());
4482
4483 return true;
4484}
4485
Johannes Doerfert57a73172016-05-23 12:45:17 +00004486bool ScopInfo::buildAccessCallInst(MemAccInst Inst, Loop *L) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004487 auto *CI = dyn_cast_or_null<CallInst>(Inst);
4488
4489 if (CI == nullptr)
Johannes Doerferta7920982016-02-25 14:08:48 +00004490 return false;
4491
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004492 if (CI->doesNotAccessMemory() || isIgnoredIntrinsic(CI))
Johannes Doerferta7920982016-02-25 14:08:48 +00004493 return true;
4494
4495 bool ReadOnly = false;
Johannes Doerfert99191c72016-05-31 09:41:04 +00004496 auto *AF = SE.getConstant(IntegerType::getInt64Ty(CI->getContext()), 0);
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004497 auto *CalledFunction = CI->getCalledFunction();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004498 switch (AA.getModRefBehavior(CalledFunction)) {
Johannes Doerferta7920982016-02-25 14:08:48 +00004499 case llvm::FMRB_UnknownModRefBehavior:
4500 llvm_unreachable("Unknown mod ref behaviour cannot be represented.");
4501 case llvm::FMRB_DoesNotAccessMemory:
4502 return true;
4503 case llvm::FMRB_OnlyReadsMemory:
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004504 GlobalReads.push_back(CI);
Johannes Doerferta7920982016-02-25 14:08:48 +00004505 return true;
4506 case llvm::FMRB_OnlyReadsArgumentPointees:
4507 ReadOnly = true;
4508 // Fall through
4509 case llvm::FMRB_OnlyAccessesArgumentPointees:
4510 auto AccType = ReadOnly ? MemoryAccess::READ : MemoryAccess::MAY_WRITE;
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004511 for (const auto &Arg : CI->arg_operands()) {
Johannes Doerferta7920982016-02-25 14:08:48 +00004512 if (!Arg->getType()->isPointerTy())
4513 continue;
4514
Johannes Doerfert99191c72016-05-31 09:41:04 +00004515 auto *ArgSCEV = SE.getSCEVAtScope(Arg, L);
Johannes Doerferta7920982016-02-25 14:08:48 +00004516 if (ArgSCEV->isZero())
4517 continue;
4518
Johannes Doerfert99191c72016-05-31 09:41:04 +00004519 auto *ArgBasePtr = cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV));
Johannes Doerferta7920982016-02-25 14:08:48 +00004520 addArrayAccess(Inst, AccType, ArgBasePtr->getValue(),
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004521 ArgBasePtr->getType(), false, {AF}, {}, CI);
Johannes Doerferta7920982016-02-25 14:08:48 +00004522 }
4523 return true;
4524 }
4525
4526 return true;
4527}
4528
Johannes Doerfert57a73172016-05-23 12:45:17 +00004529void ScopInfo::buildAccessSingleDim(MemAccInst Inst, Loop *L) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004530 Value *Address = Inst.getPointerOperand();
4531 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004532 Type *ElementType = Val->getType();
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004533 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004534 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004535
Johannes Doerfert99191c72016-05-31 09:41:04 +00004536 const SCEV *AccessFunction = SE.getSCEVAtScope(Address, L);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004537 const SCEVUnknown *BasePointer =
Johannes Doerfert99191c72016-05-31 09:41:04 +00004538 dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004539
4540 assert(BasePointer && "Could not find base pointer");
Johannes Doerfert99191c72016-05-31 09:41:04 +00004541 AccessFunction = SE.getMinusSCEV(AccessFunction, BasePointer);
Michael Kruse7bf39442015-09-10 12:46:52 +00004542
4543 // Check if the access depends on a loop contained in a non-affine subregion.
4544 bool isVariantInNonAffineLoop = false;
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004545 SetVector<const Loop *> Loops;
4546 auto &BoxedLoops = scop->getBoxedLoops();
4547 findLoops(AccessFunction, Loops);
4548 for (const Loop *L : Loops)
4549 if (BoxedLoops.count(L))
4550 isVariantInNonAffineLoop = true;
Michael Kruse7bf39442015-09-10 12:46:52 +00004551
Johannes Doerfert09e36972015-10-07 20:17:36 +00004552 InvariantLoadsSetTy AccessILS;
Johannes Doerfert57a73172016-05-23 12:45:17 +00004553 bool IsAffine =
4554 !isVariantInNonAffineLoop &&
Johannes Doerfert99191c72016-05-31 09:41:04 +00004555 isAffineExpr(&scop->getRegion(), L, AccessFunction, SE, &AccessILS);
Johannes Doerfert09e36972015-10-07 20:17:36 +00004556
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004557 const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads();
Johannes Doerfert09e36972015-10-07 20:17:36 +00004558 for (LoadInst *LInst : AccessILS)
4559 if (!ScopRIL.count(LInst))
4560 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00004561
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004562 if (!IsAffine && AccType == MemoryAccess::MUST_WRITE)
4563 AccType = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00004564
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004565 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, IsAffine,
Tobias Grosser5d51afe2016-02-02 16:46:45 +00004566 {AccessFunction}, {}, Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00004567}
4568
Johannes Doerfert57a73172016-05-23 12:45:17 +00004569void ScopInfo::buildMemoryAccess(MemAccInst Inst, Loop *L) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004570
Johannes Doerfert57a73172016-05-23 12:45:17 +00004571 if (buildAccessMemIntrinsic(Inst, L))
Johannes Doerfertcea61932016-02-21 19:13:19 +00004572 return;
4573
Johannes Doerfert57a73172016-05-23 12:45:17 +00004574 if (buildAccessCallInst(Inst, L))
Johannes Doerferta7920982016-02-25 14:08:48 +00004575 return;
4576
Johannes Doerfert57a73172016-05-23 12:45:17 +00004577 if (buildAccessMultiDimFixed(Inst, L))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004578 return;
4579
Johannes Doerfert57a73172016-05-23 12:45:17 +00004580 if (buildAccessMultiDimParam(Inst, L))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004581 return;
4582
Johannes Doerfert57a73172016-05-23 12:45:17 +00004583 buildAccessSingleDim(Inst, L);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004584}
4585
Johannes Doerfert57a73172016-05-23 12:45:17 +00004586void ScopInfo::buildAccessFunctions(Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00004587
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004588 if (scop->isNonAffineSubRegion(&SR)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00004589 for (BasicBlock *BB : SR.blocks())
Johannes Doerfert57a73172016-05-23 12:45:17 +00004590 buildAccessFunctions(*BB, &SR);
Michael Kruse7bf39442015-09-10 12:46:52 +00004591 return;
4592 }
4593
4594 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4595 if (I->isSubRegion())
Johannes Doerfert57a73172016-05-23 12:45:17 +00004596 buildAccessFunctions(*I->getNodeAs<Region>());
Michael Kruse7bf39442015-09-10 12:46:52 +00004597 else
Johannes Doerfert57a73172016-05-23 12:45:17 +00004598 buildAccessFunctions(*I->getNodeAs<BasicBlock>());
Michael Kruse7bf39442015-09-10 12:46:52 +00004599}
4600
Johannes Doerfert57a73172016-05-23 12:45:17 +00004601void ScopInfo::buildStmts(Region &SR) {
Michael Krusecac948e2015-10-02 13:53:07 +00004602
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004603 if (scop->isNonAffineSubRegion(&SR)) {
Michael Krusecac948e2015-10-02 13:53:07 +00004604 scop->addScopStmt(nullptr, &SR);
4605 return;
4606 }
4607
4608 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4609 if (I->isSubRegion())
Johannes Doerfert57a73172016-05-23 12:45:17 +00004610 buildStmts(*I->getNodeAs<Region>());
Michael Krusecac948e2015-10-02 13:53:07 +00004611 else
4612 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
4613}
4614
Johannes Doerfert57a73172016-05-23 12:45:17 +00004615void ScopInfo::buildAccessFunctions(BasicBlock &BB, Region *NonAffineSubRegion,
Michael Krused868b5d2015-09-10 15:25:24 +00004616 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00004617 // We do not build access functions for error blocks, as they may contain
4618 // instructions we can not model.
Johannes Doerfert99191c72016-05-31 09:41:04 +00004619 if (isErrorBlock(BB, scop->getRegion(), LI, DT) && !IsExitBlock)
Tobias Grosser910cf262015-11-11 20:15:49 +00004620 return;
4621
Johannes Doerfert99191c72016-05-31 09:41:04 +00004622 Loop *L = LI.getLoopFor(&BB);
Michael Kruse7bf39442015-09-10 12:46:52 +00004623
Michael Kruse2e02d562016-02-06 09:19:40 +00004624 for (Instruction &Inst : BB) {
4625 PHINode *PHI = dyn_cast<PHINode>(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004626 if (PHI)
Johannes Doerfert57a73172016-05-23 12:45:17 +00004627 buildPHIAccesses(PHI, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00004628
4629 // For the exit block we stop modeling after the last PHI node.
4630 if (!PHI && IsExitBlock)
4631 break;
4632
Michael Kruse70131d32016-01-27 17:09:17 +00004633 if (auto MemInst = MemAccInst::dyn_cast(Inst))
Johannes Doerfert57a73172016-05-23 12:45:17 +00004634 buildMemoryAccess(MemInst, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00004635
Michael Kruse2e02d562016-02-06 09:19:40 +00004636 if (isIgnoredIntrinsic(&Inst))
Michael Kruse7bf39442015-09-10 12:46:52 +00004637 continue;
4638
Tobias Grosser0904c692016-03-16 23:33:54 +00004639 // PHI nodes have already been modeled above and TerminatorInsts that are
4640 // not part of a non-affine subregion are fully modeled and regenerated
4641 // from the polyhedral domains. Hence, they do not need to be modeled as
4642 // explicit data dependences.
4643 if (!PHI && (!isa<TerminatorInst>(&Inst) || NonAffineSubRegion))
Michael Kruse2e02d562016-02-06 09:19:40 +00004644 buildScalarDependences(&Inst);
Tobias Grosser0904c692016-03-16 23:33:54 +00004645
Michael Kruse2e02d562016-02-06 09:19:40 +00004646 if (!IsExitBlock)
4647 buildEscapingDependences(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004648 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00004649}
Michael Kruse7bf39442015-09-10 12:46:52 +00004650
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004651MemoryAccess *ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004652 MemoryAccess::AccessType AccType,
4653 Value *BaseAddress, Type *ElementType,
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004654 bool Affine, Value *AccessValue,
4655 ArrayRef<const SCEV *> Subscripts,
4656 ArrayRef<const SCEV *> Sizes,
4657 ScopArrayInfo::MemoryKind Kind) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004658 ScopStmt *Stmt = scop->getStmtFor(BB);
Michael Krusecac948e2015-10-02 13:53:07 +00004659
4660 // Do not create a memory access for anything not in the SCoP. It would be
4661 // ignored anyway.
4662 if (!Stmt)
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004663 return nullptr;
Michael Krusecac948e2015-10-02 13:53:07 +00004664
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00004665 AccFuncSetType &AccList = scop->getOrCreateAccessFunctions(BB);
Michael Krusee2bccbb2015-09-18 19:59:43 +00004666 Value *BaseAddr = BaseAddress;
4667 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
4668
Tobias Grosserf4f68702015-12-14 15:05:37 +00004669 bool isKnownMustAccess = false;
4670
4671 // Accesses in single-basic block statements are always excuted.
4672 if (Stmt->isBlockStmt())
4673 isKnownMustAccess = true;
4674
4675 if (Stmt->isRegionStmt()) {
4676 // Accesses that dominate the exit block of a non-affine region are always
4677 // executed. In non-affine regions there may exist MK_Values that do not
4678 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs
4679 // only if there is at most one PHI_WRITE in the non-affine region.
Johannes Doerfert99191c72016-05-31 09:41:04 +00004680 if (DT.dominates(BB, Stmt->getRegion()->getExit()))
Tobias Grosserf4f68702015-12-14 15:05:37 +00004681 isKnownMustAccess = true;
4682 }
4683
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004684 // Non-affine PHI writes do not "happen" at a particular instruction, but
4685 // after exiting the statement. Therefore they are guaranteed execute and
4686 // overwrite the old value.
4687 if (Kind == ScopArrayInfo::MK_PHI || Kind == ScopArrayInfo::MK_ExitPHI)
4688 isKnownMustAccess = true;
4689
Johannes Doerfertcea61932016-02-21 19:13:19 +00004690 if (!isKnownMustAccess && AccType == MemoryAccess::MUST_WRITE)
4691 AccType = MemoryAccess::MAY_WRITE;
Michael Krusecac948e2015-10-02 13:53:07 +00004692
Johannes Doerfertcea61932016-02-21 19:13:19 +00004693 AccList.emplace_back(Stmt, Inst, AccType, BaseAddress, ElementType, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00004694 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00004695 Stmt->addAccess(&AccList.back());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004696 return &AccList.back();
Michael Kruse7bf39442015-09-10 12:46:52 +00004697}
4698
Michael Kruse70131d32016-01-27 17:09:17 +00004699void ScopInfo::addArrayAccess(MemAccInst MemAccInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004700 MemoryAccess::AccessType AccType,
4701 Value *BaseAddress, Type *ElementType,
4702 bool IsAffine, ArrayRef<const SCEV *> Subscripts,
Tobias Grossera535dff2015-12-13 19:59:01 +00004703 ArrayRef<const SCEV *> Sizes,
4704 Value *AccessValue) {
Johannes Doerferta7920982016-02-25 14:08:48 +00004705 ArrayBasePointers.insert(BaseAddress);
Hongbin Zhengf3d66122016-02-26 09:47:11 +00004706 addMemoryAccess(MemAccInst->getParent(), MemAccInst, AccType, BaseAddress,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004707 ElementType, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00004708 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004709}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004710
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004711void ScopInfo::ensureValueWrite(Instruction *Inst) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004712 ScopStmt *Stmt = scop->getStmtFor(Inst);
Michael Kruse436db622016-01-26 13:33:10 +00004713
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004714 // Inst not defined within this SCoP.
Michael Kruse436db622016-01-26 13:33:10 +00004715 if (!Stmt)
4716 return;
4717
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004718 // Do not process further if the instruction is already written.
4719 if (Stmt->lookupValueWriteOf(Inst))
Michael Kruse436db622016-01-26 13:33:10 +00004720 return;
4721
Johannes Doerfertcea61932016-02-21 19:13:19 +00004722 addMemoryAccess(Inst->getParent(), Inst, MemoryAccess::MUST_WRITE, Inst,
4723 Inst->getType(), true, Inst, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004724 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004725}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004726
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004727void ScopInfo::ensureValueRead(Value *V, BasicBlock *UserBB) {
Michael Krusefd463082016-01-27 22:51:56 +00004728
Michael Kruse2e02d562016-02-06 09:19:40 +00004729 // There cannot be an "access" for literal constants. BasicBlock references
4730 // (jump destinations) also never change.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004731 if ((isa<Constant>(V) && !isa<GlobalVariable>(V)) || isa<BasicBlock>(V))
Michael Kruse2e02d562016-02-06 09:19:40 +00004732 return;
4733
Michael Krusefd463082016-01-27 22:51:56 +00004734 // If the instruction can be synthesized and the user is in the region we do
4735 // not need to add a value dependences.
Johannes Doerfert99191c72016-05-31 09:41:04 +00004736 auto *Scope = LI.getLoopFor(UserBB);
4737 if (canSynthesize(V, *scop, &LI, &SE, Scope))
Michael Krusefd463082016-01-27 22:51:56 +00004738 return;
4739
Michael Kruse2e02d562016-02-06 09:19:40 +00004740 // Do not build scalar dependences for required invariant loads as we will
4741 // hoist them later on anyway or drop the SCoP if we cannot.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004742 auto &ScopRIL = scop->getRequiredInvariantLoads();
4743 if (ScopRIL.count(dyn_cast<LoadInst>(V)))
Michael Kruse2e02d562016-02-06 09:19:40 +00004744 return;
4745
4746 // Determine the ScopStmt containing the value's definition and use. There is
4747 // no defining ScopStmt if the value is a function argument, a global value,
4748 // or defined outside the SCoP.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004749 Instruction *ValueInst = dyn_cast<Instruction>(V);
Michael Kruse6f7721f2016-02-24 22:08:19 +00004750 ScopStmt *ValueStmt = ValueInst ? scop->getStmtFor(ValueInst) : nullptr;
Michael Kruse2e02d562016-02-06 09:19:40 +00004751
Michael Kruse6f7721f2016-02-24 22:08:19 +00004752 ScopStmt *UserStmt = scop->getStmtFor(UserBB);
Michael Krusead28e5a2016-01-26 13:33:15 +00004753
4754 // We do not model uses outside the scop.
4755 if (!UserStmt)
4756 return;
4757
Michael Kruse2e02d562016-02-06 09:19:40 +00004758 // Add MemoryAccess for invariant values only if requested.
4759 if (!ModelReadOnlyScalars && !ValueStmt)
4760 return;
4761
4762 // Ignore use-def chains within the same ScopStmt.
4763 if (ValueStmt == UserStmt)
4764 return;
4765
Michael Krusead28e5a2016-01-26 13:33:15 +00004766 // Do not create another MemoryAccess for reloading the value if one already
4767 // exists.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004768 if (UserStmt->lookupValueReadOf(V))
Michael Krusead28e5a2016-01-26 13:33:15 +00004769 return;
4770
Johannes Doerfert2075b5d2016-04-03 11:16:00 +00004771 // For exit PHIs use the MK_ExitPHI MemoryKind not MK_Value.
4772 ScopArrayInfo::MemoryKind Kind = ScopArrayInfo::MK_Value;
4773 if (!ValueStmt && isa<PHINode>(V))
4774 Kind = ScopArrayInfo::MK_ExitPHI;
4775
Johannes Doerfertcea61932016-02-21 19:13:19 +00004776 addMemoryAccess(UserBB, nullptr, MemoryAccess::READ, V, V->getType(), true, V,
Johannes Doerfert2075b5d2016-04-03 11:16:00 +00004777 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(), Kind);
Michael Kruse2e02d562016-02-06 09:19:40 +00004778 if (ValueInst)
4779 ensureValueWrite(ValueInst);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004780}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004781
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004782void ScopInfo::ensurePHIWrite(PHINode *PHI, BasicBlock *IncomingBlock,
4783 Value *IncomingValue, bool IsExitBlock) {
Johannes Doerfert57c5f0b2016-04-05 13:44:21 +00004784 // As the incoming block might turn out to be an error statement ensure we
4785 // will create an exit PHI SAI object. It is needed during code generation
4786 // and would be created later anyway.
4787 if (IsExitBlock)
4788 scop->getOrCreateScopArrayInfo(PHI, PHI->getType(), {},
4789 ScopArrayInfo::MK_ExitPHI);
4790
Michael Kruse6f7721f2016-02-24 22:08:19 +00004791 ScopStmt *IncomingStmt = scop->getStmtFor(IncomingBlock);
Michael Kruse2e02d562016-02-06 09:19:40 +00004792 if (!IncomingStmt)
4793 return;
4794
4795 // Take care for the incoming value being available in the incoming block.
4796 // This must be done before the check for multiple PHI writes because multiple
4797 // exiting edges from subregion each can be the effective written value of the
4798 // subregion. As such, all of them must be made available in the subregion
4799 // statement.
4800 ensureValueRead(IncomingValue, IncomingBlock);
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004801
4802 // Do not add more than one MemoryAccess per PHINode and ScopStmt.
4803 if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) {
4804 assert(Acc->getAccessInstruction() == PHI);
4805 Acc->addIncoming(IncomingBlock, IncomingValue);
4806 return;
4807 }
4808
4809 MemoryAccess *Acc = addMemoryAccess(
Michael Kruse375cb5f2016-02-24 22:08:24 +00004810 IncomingStmt->getEntryBlock(), PHI, MemoryAccess::MUST_WRITE, PHI,
4811 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4812 ArrayRef<const SCEV *>(),
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004813 IsExitBlock ? ScopArrayInfo::MK_ExitPHI : ScopArrayInfo::MK_PHI);
4814 assert(Acc);
4815 Acc->addIncoming(IncomingBlock, IncomingValue);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004816}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004817
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004818void ScopInfo::addPHIReadAccess(PHINode *PHI) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00004819 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI,
4820 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4821 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004822}
4823
Michael Krusedaf66942015-12-13 22:10:37 +00004824void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Johannes Doerfert99191c72016-05-31 09:41:04 +00004825 scop.reset(new Scop(R, SE, LI, *SD.getDetectionContext(&R)));
Michael Kruse7bf39442015-09-10 12:46:52 +00004826
Johannes Doerfert57a73172016-05-23 12:45:17 +00004827 buildStmts(R);
4828 buildAccessFunctions(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00004829
4830 // In case the region does not have an exiting block we will later (during
4831 // code generation) split the exit block. This will move potential PHI nodes
4832 // from the current exit block into the new region exiting block. Hence, PHI
4833 // nodes that are at this point not part of the region will be.
4834 // To handle these PHI nodes later we will now model their operands as scalar
4835 // accesses. Note that we do not model anything in the exit block if we have
4836 // an exiting block in the region, as there will not be any splitting later.
Johannes Doerfertef744432016-05-23 12:42:38 +00004837 if (!scop->hasSingleExitEdge())
Johannes Doerfert57a73172016-05-23 12:45:17 +00004838 buildAccessFunctions(*R.getExit(), nullptr,
Hongbin Zheng22623202016-02-15 00:20:58 +00004839 /* IsExitBlock */ true);
Michael Kruse7bf39442015-09-10 12:46:52 +00004840
Johannes Doerferta7920982016-02-25 14:08:48 +00004841 // Create memory accesses for global reads since all arrays are now known.
Johannes Doerfert99191c72016-05-31 09:41:04 +00004842 auto *AF = SE.getConstant(IntegerType::getInt64Ty(SE.getContext()), 0);
Johannes Doerferta7920982016-02-25 14:08:48 +00004843 for (auto *GlobalRead : GlobalReads)
4844 for (auto *BP : ArrayBasePointers)
4845 addArrayAccess(MemAccInst(GlobalRead), MemoryAccess::READ, BP,
4846 BP->getType(), false, {AF}, {}, GlobalRead);
4847
Johannes Doerfert99191c72016-05-31 09:41:04 +00004848 scop->init(AA, AC, DT, LI);
Michael Kruse7bf39442015-09-10 12:46:52 +00004849}
4850
Johannes Doerfert99191c72016-05-31 09:41:04 +00004851ScopInfo::ScopInfo(Region *R, AssumptionCache &AC, AliasAnalysis &AA,
4852 const DataLayout &DL, DominatorTree &DT, LoopInfo &LI,
4853 ScopDetection &SD, ScalarEvolution &SE)
4854 : AA(AA), DL(DL), DT(DT), LI(LI), SD(SD), SE(SE) {
Michael Krused868b5d2015-09-10 15:25:24 +00004855
4856 Function *F = R->getEntry()->getParent();
Michael Krused868b5d2015-09-10 15:25:24 +00004857
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004858 DebugLoc Beg, End;
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00004859 getDebugLocations(getBBPairForRegion(R), Beg, End);
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004860 std::string Msg = "SCoP begins here.";
4861 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4862
Michael Krusedaf66942015-12-13 22:10:37 +00004863 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004864
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004865 DEBUG(scop->print(dbgs()));
4866
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004867 if (!scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004868 Msg = "SCoP ends here but was dismissed.";
Hongbin Zhengfec32802016-02-13 15:13:02 +00004869 scop.reset();
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004870 } else {
4871 Msg = "SCoP ends here.";
4872 ++ScopFound;
4873 if (scop->getMaxLoopDepth() > 0)
4874 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004875 }
4876
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004877 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004878}
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004879
Johannes Doerfert99191c72016-05-31 09:41:04 +00004880void ScopInfo::clear() { scop.reset(); }
4881
4882//===----------------------------------------------------------------------===//
4883void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4884 AU.addRequired<LoopInfoWrapperPass>();
4885 AU.addRequired<RegionInfoPass>();
4886 AU.addRequired<DominatorTreeWrapperPass>();
4887 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4888 AU.addRequiredTransitive<ScopDetection>();
4889 AU.addRequired<AAResultsWrapperPass>();
4890 AU.addRequired<AssumptionCacheTracker>();
4891 AU.setPreservesAll();
4892}
4893
4894bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4895 auto &SD = getAnalysis<ScopDetection>();
4896
4897 if (!SD.isMaxRegionInScop(*R))
4898 return false;
4899
4900 Function *F = R->getEntry()->getParent();
4901 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4902 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4903 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4904 auto const &DL = F->getParent()->getDataLayout();
4905 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4906 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
4907
4908 SI.reset(new ScopInfo(R, AC, AA, DL, DT, LI, SD, SE));
Tobias Grosser75805372011-04-29 06:27:02 +00004909 return false;
4910}
4911
Johannes Doerfert99191c72016-05-31 09:41:04 +00004912void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
4913 Scop *scop;
4914 if (SI) {
4915 if ((scop = SI->getScop())) {
4916 scop->print(OS);
4917 return;
4918 }
4919 }
4920 OS << "Invalid Scop!\n";
4921}
Tobias Grosser75805372011-04-29 06:27:02 +00004922
Johannes Doerfert99191c72016-05-31 09:41:04 +00004923char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004924
Johannes Doerfert99191c72016-05-31 09:41:04 +00004925Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4926
4927INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004928 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004929 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004930INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004931INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004932INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004933INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004934INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004935INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004936INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004937INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004938 "Polly - Create polyhedral description of Scops", false,
4939 false)