blob: f256b456541b8959487a749c052e91fdd17d421d [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));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000098static cl::opt<std::string> UserContextStr(
99 "polly-context", cl::value_desc("isl parameter set"),
100 cl::desc("Provide additional constraints on the context parameters"),
101 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000102
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000103static cl::opt<bool> DetectReductions("polly-detect-reductions",
104 cl::desc("Detect and exploit reductions"),
105 cl::Hidden, cl::ZeroOrMore,
106 cl::init(true), cl::cat(PollyCategory));
107
Tobias Grosser2937b592016-04-29 11:43:20 +0000108static cl::opt<bool>
109 IslOnErrorAbort("polly-on-isl-error-abort",
110 cl::desc("Abort if an isl error is encountered"),
111 cl::init(true), cl::cat(PollyCategory));
112
Michael Kruse7bf39442015-09-10 12:46:52 +0000113//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000114
Michael Kruse046dde42015-08-10 13:01:57 +0000115// Create a sequence of two schedules. Either argument may be null and is
116// interpreted as the empty schedule. Can also return null if both schedules are
117// empty.
118static __isl_give isl_schedule *
119combineInSequence(__isl_take isl_schedule *Prev,
120 __isl_take isl_schedule *Succ) {
121 if (!Prev)
122 return Succ;
123 if (!Succ)
124 return Prev;
125
126 return isl_schedule_sequence(Prev, Succ);
127}
128
Johannes Doerferte7044942015-02-24 11:58:30 +0000129static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
130 const ConstantRange &Range,
131 int dim,
132 enum isl_dim_type type) {
133 isl_val *V;
134 isl_ctx *ctx = isl_set_get_ctx(S);
135
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000136 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
137 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000138 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000139 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
140
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000141 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000142 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000143 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000144 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000145 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
146
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000147 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000148 return isl_set_union(SLB, SUB);
149 else
150 return isl_set_intersect(SLB, SUB);
151}
152
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000153static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
154 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
155 if (!BasePtrLI)
156 return nullptr;
157
158 if (!S->getRegion().contains(BasePtrLI))
159 return nullptr;
160
161 ScalarEvolution &SE = *S->getSE();
162
163 auto *OriginBaseSCEV =
164 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
165 if (!OriginBaseSCEV)
166 return nullptr;
167
168 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
169 if (!OriginBaseSCEVUnknown)
170 return nullptr;
171
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000172 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000173 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000174}
175
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000176ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000177 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000178 const DataLayout &DL, Scop *S)
179 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000180 std::string BasePtrName =
Tobias Grossera535dff2015-12-13 19:59:01 +0000181 getIslCompatibleName("MemRef_", BasePtr, Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000182 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000183
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000184 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000185 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
186 if (BasePtrOriginSAI)
187 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000188}
189
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000190__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000191 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000192 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
193 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
194 return Space;
195}
196
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000197void ScopArrayInfo::updateElementType(Type *NewElementType) {
198 if (NewElementType == ElementType)
199 return;
200
Tobias Grosserd840fc72016-02-04 13:18:42 +0000201 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
202 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
203
Johannes Doerferta7920982016-02-25 14:08:48 +0000204 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000205 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000206
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000207 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
208 ElementType = NewElementType;
209 } else {
210 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
211 ElementType = IntegerType::get(ElementType->getContext(), GCD);
212 }
213}
214
215bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000216 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
217 int ExtraDimsNew = NewSizes.size() - SharedDims;
218 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000219 for (int i = 0; i < SharedDims; i++)
220 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
221 return false;
222
223 if (DimensionSizes.size() >= NewSizes.size())
224 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000225
226 DimensionSizes.clear();
227 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
228 NewSizes.end());
229 for (isl_pw_aff *Size : DimensionSizesPw)
230 isl_pw_aff_free(Size);
231 DimensionSizesPw.clear();
232 for (const SCEV *Expr : DimensionSizes) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000233 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000234 DimensionSizesPw.push_back(Size);
235 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000236 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000237}
238
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000239ScopArrayInfo::~ScopArrayInfo() {
240 isl_id_free(Id);
241 for (isl_pw_aff *Size : DimensionSizesPw)
242 isl_pw_aff_free(Size);
243}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000244
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000245std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
246
247int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000248 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000249}
250
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000251__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
252 return isl_id_copy(Id);
253}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000254
255void ScopArrayInfo::dump() const { print(errs()); }
256
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000257void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000258 OS.indent(8) << *getElementType() << " " << getName();
259 if (getNumberOfDimensions() > 0)
260 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000261 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000262 OS << "[";
263
Tobias Grosser26253842015-11-10 14:24:21 +0000264 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000265 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000266 OS << " " << Size << " ";
267 isl_pw_aff_free(Size);
268 } else {
269 OS << *getDimensionSize(u);
270 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000271
272 OS << "]";
273 }
274
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000275 OS << ";";
276
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000277 if (BasePtrOriginSAI)
278 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
279
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000280 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000281}
282
283const ScopArrayInfo *
284ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
285 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
286 assert(Id && "Output dimension didn't have an ID");
287 return getFromId(Id);
288}
289
290const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
291 void *User = isl_id_get_user(Id);
292 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
293 isl_id_free(Id);
294 return SAI;
295}
296
Michael Kruse3b425ff2016-04-11 14:34:08 +0000297void MemoryAccess::wrapConstantDimensions() {
298 auto *SAI = getScopArrayInfo();
299 auto *ArraySpace = SAI->getSpace();
300 auto *Ctx = isl_space_get_ctx(ArraySpace);
301 unsigned DimsArray = SAI->getNumberOfDimensions();
302
303 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
304 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
305 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
306
307 // Begin with last dimension, to iteratively carry into higher dimensions.
308 for (int i = DimsArray - 1; i > 0; i--) {
309 auto *DimSize = SAI->getDimensionSize(i);
310 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
311
312 // This transformation is not applicable to dimensions with dynamic size.
313 if (!DimSizeCst)
314 continue;
315
316 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
317 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
318 isl_dim_set, i);
319 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
320 isl_dim_set, i - 1);
321
322 // Compute: index % size
323 // Modulo must apply in the divide of the previous iteration, if any.
324 auto *Modulo = isl_aff_copy(Var);
325 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
326 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
327
328 // Compute: floor(index / size)
329 auto *Divide = Var;
330 Divide = isl_aff_div(
331 Divide,
332 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
333 Divide = isl_aff_floor(Divide);
334 Divide = isl_aff_add(Divide, PrevVar);
335 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
336
337 // Apply Modulo and Divide.
338 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
339 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
340 }
341
342 // Apply all modulo/divides on the accesses.
343 AccessRelation =
344 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
345 AccessRelation = isl_map_detect_equalities(AccessRelation);
346 isl_local_space_free(LArraySpace);
347}
348
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000349void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000350 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000351 auto *ArraySpace = SAI->getSpace();
352 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000353 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000354
355 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
356 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
357 auto DimsMissing = DimsArray - DimsAccess;
358
Michael Kruse375cb5f2016-02-24 22:08:24 +0000359 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000360 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000361 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000362 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000363
Johannes Doerferta90943d2016-02-21 16:37:25 +0000364 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000365 isl_set_universe(AccessSpace),
366 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000367
368 for (unsigned i = 0; i < DimsMissing; i++)
369 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
370
371 for (unsigned i = DimsMissing; i < DimsArray; i++)
372 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
373
374 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000375
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000376 // For the non delinearized arrays, divide the access function of the last
377 // subscript by the size of the elements in the array.
378 //
379 // A stride one array access in C expressed as A[i] is expressed in
380 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
381 // two subsequent values of 'i' index two values that are stored next to
382 // each other in memory. By this division we make this characteristic
383 // obvious again. If the base pointer was accessed with offsets not divisible
384 // by the accesses element size, we will have choosen a smaller ArrayElemSize
385 // that divides the offsets of all accesses to this base pointer.
386 if (DimsAccess == 1) {
387 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
388 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
389 }
390
Michael Kruse3b425ff2016-04-11 14:34:08 +0000391 // We currently do this only if we added at least one dimension, which means
392 // some dimension's indices have not been specified, an indicator that some
393 // index values have been added together.
394 // TODO: Investigate general usefulness; Effect on unit tests is to make index
395 // expressions more complicated.
396 if (DimsMissing)
397 wrapConstantDimensions();
398
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000399 if (!isAffine())
400 computeBoundsOnAccessRelation(ArrayElemSize);
401
Tobias Grosserd840fc72016-02-04 13:18:42 +0000402 // Introduce multi-element accesses in case the type loaded by this memory
403 // access is larger than the canonical element type of the array.
404 //
405 // An access ((float *)A)[i] to an array char *A is modeled as
406 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000407 if (ElemBytes > ArrayElemSize) {
408 assert(ElemBytes % ArrayElemSize == 0 &&
409 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000410 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000411 isl_set_universe(isl_space_copy(ArraySpace)),
412 isl_set_universe(isl_space_copy(ArraySpace)));
413 for (unsigned i = 0; i < DimsArray - 1; i++)
414 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
415
Tobias Grosserd840fc72016-02-04 13:18:42 +0000416 isl_constraint *C;
417 isl_local_space *LS;
418
419 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000420 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
421
422 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
423 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000424 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000425 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
426 Map = isl_map_add_constraint(Map, C);
427
428 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000429 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000430 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
431 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
432 Map = isl_map_add_constraint(Map, C);
433 AccessRelation = isl_map_apply_range(AccessRelation, Map);
434 }
435
436 isl_space_free(ArraySpace);
437
Roman Gareev10595a12016-01-08 14:01:59 +0000438 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000439}
440
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000441const std::string
442MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
443 switch (RT) {
444 case MemoryAccess::RT_NONE:
445 llvm_unreachable("Requested a reduction operator string for a memory "
446 "access which isn't a reduction");
447 case MemoryAccess::RT_ADD:
448 return "+";
449 case MemoryAccess::RT_MUL:
450 return "*";
451 case MemoryAccess::RT_BOR:
452 return "|";
453 case MemoryAccess::RT_BXOR:
454 return "^";
455 case MemoryAccess::RT_BAND:
456 return "&";
457 }
458 llvm_unreachable("Unknown reduction type");
459 return "";
460}
461
Johannes Doerfertf6183392014-07-01 20:52:51 +0000462/// @brief Return the reduction type for a given binary operator
463static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
464 const Instruction *Load) {
465 if (!BinOp)
466 return MemoryAccess::RT_NONE;
467 switch (BinOp->getOpcode()) {
468 case Instruction::FAdd:
469 if (!BinOp->hasUnsafeAlgebra())
470 return MemoryAccess::RT_NONE;
471 // Fall through
472 case Instruction::Add:
473 return MemoryAccess::RT_ADD;
474 case Instruction::Or:
475 return MemoryAccess::RT_BOR;
476 case Instruction::Xor:
477 return MemoryAccess::RT_BXOR;
478 case Instruction::And:
479 return MemoryAccess::RT_BAND;
480 case Instruction::FMul:
481 if (!BinOp->hasUnsafeAlgebra())
482 return MemoryAccess::RT_NONE;
483 // Fall through
484 case Instruction::Mul:
485 if (DisableMultiplicativeReductions)
486 return MemoryAccess::RT_NONE;
487 return MemoryAccess::RT_MUL;
488 default:
489 return MemoryAccess::RT_NONE;
490 }
491}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000492
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000493/// @brief Derive the individual index expressions from a GEP instruction
494///
495/// This function optimistically assumes the GEP references into a fixed size
496/// array. If this is actually true, this function returns a list of array
497/// subscript expressions as SCEV as well as a list of integers describing
498/// the size of the individual array dimensions. Both lists have either equal
499/// length of the size list is one element shorter in case there is no known
500/// size available for the outermost array dimension.
501///
502/// @param GEP The GetElementPtr instruction to analyze.
503///
504/// @return A tuple with the subscript expressions and the dimension sizes.
505static std::tuple<std::vector<const SCEV *>, std::vector<int>>
506getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
507 std::vector<const SCEV *> Subscripts;
508 std::vector<int> Sizes;
509
510 Type *Ty = GEP->getPointerOperandType();
511
512 bool DroppedFirstDim = false;
513
Michael Kruse26ed65e2015-09-24 17:32:49 +0000514 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000515
516 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
517
518 if (i == 1) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000519 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000520 Ty = PtrTy->getElementType();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000521 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000522 Ty = ArrayTy->getElementType();
523 } else {
524 Subscripts.clear();
525 Sizes.clear();
526 break;
527 }
Johannes Doerferta90943d2016-02-21 16:37:25 +0000528 if (auto *Const = dyn_cast<SCEVConstant>(Expr))
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000529 if (Const->getValue()->isZero()) {
530 DroppedFirstDim = true;
531 continue;
532 }
533 Subscripts.push_back(Expr);
534 continue;
535 }
536
Johannes Doerferta90943d2016-02-21 16:37:25 +0000537 auto *ArrayTy = dyn_cast<ArrayType>(Ty);
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000538 if (!ArrayTy) {
539 Subscripts.clear();
540 Sizes.clear();
541 break;
542 }
543
544 Subscripts.push_back(Expr);
545 if (!(DroppedFirstDim && i == 2))
546 Sizes.push_back(ArrayTy->getNumElements());
547
548 Ty = ArrayTy->getElementType();
549 }
550
551 return std::make_tuple(Subscripts, Sizes);
552}
553
Tobias Grosser75805372011-04-29 06:27:02 +0000554MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000555 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000556 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000557 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000558 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000559}
560
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000561const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
562 isl_id *ArrayId = getArrayId();
563 void *User = isl_id_get_user(ArrayId);
564 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
565 isl_id_free(ArrayId);
566 return SAI;
567}
568
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000569__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000570 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
571}
572
Tobias Grosserd840fc72016-02-04 13:18:42 +0000573__isl_give isl_map *MemoryAccess::getAddressFunction() const {
574 return isl_map_lexmin(getAccessRelation());
575}
576
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000577__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
578 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000579 isl_map *Schedule, *ScheduledAccRel;
580 isl_union_set *UDomain;
581
582 UDomain = isl_union_set_from_set(getStatement()->getDomain());
583 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
584 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000585 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000586 return isl_pw_multi_aff_from_map(ScheduledAccRel);
587}
588
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000589__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000590 return isl_map_copy(AccessRelation);
591}
592
Johannes Doerferta99130f2014-10-13 12:58:03 +0000593std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000594 return stringFromIslObj(AccessRelation);
595}
596
Johannes Doerferta99130f2014-10-13 12:58:03 +0000597__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000598 return isl_map_get_space(AccessRelation);
599}
600
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000601__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000602 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000603}
604
Tobias Grosser6f730082015-09-05 07:46:47 +0000605std::string MemoryAccess::getNewAccessRelationStr() const {
606 return stringFromIslObj(NewAccessRelation);
607}
608
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000609__isl_give isl_basic_map *
610MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000611 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000612 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000613
Tobias Grosser084d8f72012-05-29 09:29:44 +0000614 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000615 isl_basic_set_universe(Statement->getDomainSpace()),
616 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000617}
618
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000619// Formalize no out-of-bound access assumption
620//
621// When delinearizing array accesses we optimistically assume that the
622// delinearized accesses do not access out of bound locations (the subscript
623// expression of each array evaluates for each statement instance that is
624// executed to a value that is larger than zero and strictly smaller than the
625// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000626// dimension for which we do not need to assume any upper bound. At this point
627// we formalize this assumption to ensure that at code generation time the
628// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000629//
630// To find the set of constraints necessary to avoid out of bound accesses, we
631// first build the set of data locations that are not within array bounds. We
632// then apply the reverse access relation to obtain the set of iterations that
633// may contain invalid accesses and reduce this set of iterations to the ones
634// that are actually executed by intersecting them with the domain of the
635// statement. If we now project out all loop dimensions, we obtain a set of
636// parameters that may cause statement instances to be executed that may
637// possibly yield out of bound memory accesses. The complement of these
638// constraints is the set of constraints that needs to be assumed to ensure such
639// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000640void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000641 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000642 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000643 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000644 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000645 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
646 isl_pw_aff *Var =
647 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
648 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
649
650 isl_set *DimOutside;
651
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000652 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000653 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000654 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
655 isl_space_dim(Space, isl_dim_set));
656 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
657 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000658
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000659 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000660
661 Outside = isl_set_union(Outside, DimOutside);
662 }
663
664 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
665 Outside = isl_set_intersect(Outside, Statement->getDomain());
666 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000667
668 // Remove divs to avoid the construction of overly complicated assumptions.
669 // Doing so increases the set of parameter combinations that are assumed to
670 // not appear. This is always save, but may make the resulting run-time check
671 // bail out more often than strictly necessary.
672 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000673 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000674 const auto &Loc = getAccessInstruction()
675 ? getAccessInstruction()->getDebugLoc()
676 : DebugLoc();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000677 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
678 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000679 isl_space_free(Space);
680}
681
Johannes Doerfertcea61932016-02-21 19:13:19 +0000682void MemoryAccess::buildMemIntrinsicAccessRelation() {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000683 assert(isa<MemIntrinsic>(getAccessInstruction()));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000684 assert(Subscripts.size() == 2 && Sizes.size() == 0);
685
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000686 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000687 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000688
689 isl_map *LengthMap;
690 if (Subscripts[1] == nullptr) {
691 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
692 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000693 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000694 LengthMap = isl_map_from_pw_aff(LengthPWA);
695 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
696 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
697 }
698 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
699 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000700 SubscriptMap =
701 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000702 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
703 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
704 getStatement()->getDomainId());
705}
706
Johannes Doerferte7044942015-02-24 11:58:30 +0000707void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
708 ScalarEvolution *SE = Statement->getParent()->getSE();
709
Johannes Doerfertcea61932016-02-21 19:13:19 +0000710 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000711 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000712 return;
713
714 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000715 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
716 return;
717
718 auto *PtrSCEV = SE->getSCEV(Ptr);
719 if (isa<SCEVCouldNotCompute>(PtrSCEV))
720 return;
721
722 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
723 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
724 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
725
726 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
727 if (Range.isFullSet())
728 return;
729
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000730 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000731 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000732 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000733 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000734 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000735
736 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000737 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000738
739 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
740 AccessRange =
741 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
742 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
743}
744
Michael Krusee2bccbb2015-09-18 19:59:43 +0000745__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000746 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000747 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000748
749 for (int i = Size - 2; i >= 0; --i) {
750 isl_space *Space;
751 isl_map *MapOne, *MapTwo;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000752 isl_pw_aff *DimSize = getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000753
754 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
755 isl_pw_aff_free(DimSize);
756 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
757
758 Space = isl_map_get_space(AccessRelation);
759 Space = isl_space_map_from_set(isl_space_range(Space));
760 Space = isl_space_align_params(Space, SpaceSize);
761
762 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
763 isl_id_free(ParamId);
764
765 MapOne = isl_map_universe(isl_space_copy(Space));
766 for (int j = 0; j < Size; ++j)
767 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
768 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
769
770 MapTwo = isl_map_universe(isl_space_copy(Space));
771 for (int j = 0; j < Size; ++j)
772 if (j < i || j > i + 1)
773 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
774
775 isl_local_space *LS = isl_local_space_from_space(Space);
776 isl_constraint *C;
777 C = isl_equality_alloc(isl_local_space_copy(LS));
778 C = isl_constraint_set_constant_si(C, -1);
779 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
780 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
781 MapTwo = isl_map_add_constraint(MapTwo, C);
782 C = isl_equality_alloc(LS);
783 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
784 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
785 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
786 MapTwo = isl_map_add_constraint(MapTwo, C);
787 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
788
789 MapOne = isl_map_union(MapOne, MapTwo);
790 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
791 }
792 return AccessRelation;
793}
794
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000795/// @brief Check if @p Expr is divisible by @p Size.
796static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000797 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000798 if (Size == 1)
799 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000800
801 // Only one factor needs to be divisible.
802 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
803 for (auto *FactorExpr : MulExpr->operands())
804 if (isDivisible(FactorExpr, Size, SE))
805 return true;
806 return false;
807 }
808
809 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
810 // to be divisble.
811 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
812 for (auto *OpExpr : NAryExpr->operands())
813 if (!isDivisible(OpExpr, Size, SE))
814 return false;
815 return true;
816 }
817
818 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
819 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
820 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
821 return MulSCEV == Expr;
822}
823
Michael Krusee2bccbb2015-09-18 19:59:43 +0000824void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
825 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000826
Johannes Doerfert85676e32016-04-23 14:32:34 +0000827 // Initialize the invalid domain which describes all iterations for which the
828 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000829 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
830 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
831 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000832
Michael Krusee2bccbb2015-09-18 19:59:43 +0000833 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000834 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000835
Michael Krusee2bccbb2015-09-18 19:59:43 +0000836 if (!isAffine()) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000837 if (isa<MemIntrinsic>(getAccessInstruction()))
838 buildMemIntrinsicAccessRelation();
839
Tobias Grosser4f967492013-06-23 05:21:18 +0000840 // We overapproximate non-affine accesses with a possible access to the
841 // whole array. For read accesses it does not make a difference, if an
842 // access must or may happen. However, for write accesses it is important to
843 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000844 if (!AccessRelation)
845 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
846
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000847 AccessRelation =
848 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000849 return;
850 }
851
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000852 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000853 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000854
Michael Krusee2bccbb2015-09-18 19:59:43 +0000855 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000856 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000857 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000858 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000859 }
860
Tobias Grosser5d51afe2016-02-02 16:46:45 +0000861 if (Sizes.size() >= 1 && !isa<SCEVConstant>(Sizes[0]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000862 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000863
Tobias Grosser79baa212014-04-10 08:38:02 +0000864 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000865 AccessRelation = isl_map_set_tuple_id(
866 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000867 AccessRelation =
868 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
869
Tobias Grosseraa660a92015-03-30 00:07:50 +0000870 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000871 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000872}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000873
Michael Krusecac948e2015-10-02 13:53:07 +0000874MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000875 AccessType AccType, Value *BaseAddress,
876 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000877 ArrayRef<const SCEV *> Subscripts,
878 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000879 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000880 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Johannes Doerfert85676e32016-04-23 14:32:34 +0000881 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
882 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()),
883 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000884 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000885 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000886 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000887 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000888
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000889 std::string IdName =
890 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000891 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
892}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000893
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000894void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +0000895 auto *Ctx = Statement->getParent()->getContext();
896 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
897 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +0000898}
899
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000900const std::string MemoryAccess::getReductionOperatorStr() const {
901 return MemoryAccess::getReductionOperatorStr(getReductionType());
902}
903
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000904__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
905
Johannes Doerfertf6183392014-07-01 20:52:51 +0000906raw_ostream &polly::operator<<(raw_ostream &OS,
907 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000908 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000909 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000910 else
911 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000912 return OS;
913}
914
Tobias Grosser75805372011-04-29 06:27:02 +0000915void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000916 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000917 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000918 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000919 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000920 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000921 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000922 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000923 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000924 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000925 break;
926 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000927 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000928 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000929 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000930 if (hasNewAccessRelation())
931 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000932}
933
Tobias Grosser74394f02013-01-14 22:40:23 +0000934void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000935
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000936__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
937 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000938 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
939 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
940 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000941}
942
Tobias Grosser75805372011-04-29 06:27:02 +0000943// Create a map in the size of the provided set domain, that maps from the
944// one element of the provided set domain to another element of the provided
945// set domain.
946// The mapping is limited to all points that are equal in all but the last
947// dimension and for which the last dimension of the input is strict smaller
948// than the last dimension of the output.
949//
950// getEqualAndLarger(set[i0, i1, ..., iX]):
951//
952// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
953// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
954//
Tobias Grosserf5338802011-10-06 00:03:35 +0000955static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000956 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000957 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000958 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000959
960 // Set all but the last dimension to be equal for the input and output
961 //
962 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
963 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000964 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000965 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000966
967 // Set the last dimension of the input to be strict smaller than the
968 // last dimension of the output.
969 //
970 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000971 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
972 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000973 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000974}
975
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000976__isl_give isl_set *
977MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000978 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000979 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000980 isl_space *Space = isl_space_range(isl_map_get_space(S));
981 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000982
Sebastian Popa00a0292012-12-18 07:46:06 +0000983 S = isl_map_reverse(S);
984 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000985
Sebastian Popa00a0292012-12-18 07:46:06 +0000986 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
987 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
988 NextScatt = isl_map_apply_domain(NextScatt, S);
989 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000990
Sebastian Popa00a0292012-12-18 07:46:06 +0000991 isl_set *Deltas = isl_map_deltas(NextScatt);
992 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000993}
994
Sebastian Popa00a0292012-12-18 07:46:06 +0000995bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000996 int StrideWidth) const {
997 isl_set *Stride, *StrideX;
998 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000999
Sebastian Popa00a0292012-12-18 07:46:06 +00001000 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001001 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001002 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1003 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1004 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1005 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001006 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001007
Tobias Grosser28dd4862012-01-24 16:42:16 +00001008 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001009 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001010
Tobias Grosser28dd4862012-01-24 16:42:16 +00001011 return IsStrideX;
1012}
1013
Sebastian Popa00a0292012-12-18 07:46:06 +00001014bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
1015 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001016}
1017
Sebastian Popa00a0292012-12-18 07:46:06 +00001018bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
1019 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001020}
1021
Tobias Grosser166c4222015-09-05 07:46:40 +00001022void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
1023 isl_map_free(NewAccessRelation);
1024 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001025}
Tobias Grosser75805372011-04-29 06:27:02 +00001026
1027//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001028
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001029__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001030 isl_set *Domain = getDomain();
1031 if (isl_set_is_empty(Domain)) {
1032 isl_set_free(Domain);
1033 return isl_map_from_aff(
1034 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1035 }
1036 auto *Schedule = getParent()->getSchedule();
1037 Schedule = isl_union_map_intersect_domain(
1038 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1039 if (isl_union_map_is_empty(Schedule)) {
1040 isl_set_free(Domain);
1041 isl_union_map_free(Schedule);
1042 return isl_map_from_aff(
1043 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1044 }
1045 auto *M = isl_map_from_union_map(Schedule);
1046 M = isl_map_coalesce(M);
1047 M = isl_map_gist_domain(M, Domain);
1048 M = isl_map_coalesce(M);
1049 return M;
1050}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001051
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001052__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1053 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001054 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1055 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001056}
1057
Tobias Grosser37eb4222014-02-20 21:43:54 +00001058void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1059 assert(isl_set_is_subset(NewDomain, Domain) &&
1060 "New domain is not a subset of old domain!");
1061 isl_set_free(Domain);
1062 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001063}
1064
Michael Krusecac948e2015-10-02 13:53:07 +00001065void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001066 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001067 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001068 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001069
Tobias Grossera535dff2015-12-13 19:59:01 +00001070 ScopArrayInfo::MemoryKind Ty;
1071 if (Access->isPHIKind())
1072 Ty = ScopArrayInfo::MK_PHI;
1073 else if (Access->isExitPHIKind())
1074 Ty = ScopArrayInfo::MK_ExitPHI;
1075 else if (Access->isValueKind())
1076 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001077 else
Tobias Grossera535dff2015-12-13 19:59:01 +00001078 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001079
Johannes Doerfertadeab372016-02-07 13:57:32 +00001080 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1081 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001082 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001083 }
1084}
1085
Michael Krusecac948e2015-10-02 13:53:07 +00001086void ScopStmt::addAccess(MemoryAccess *Access) {
1087 Instruction *AccessInst = Access->getAccessInstruction();
1088
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001089 if (Access->isArrayKind()) {
1090 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1091 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001092 } else if (Access->isValueKind() && Access->isWrite()) {
1093 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001094 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001095 assert(!ValueWrites.lookup(AccessVal));
1096
1097 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001098 } else if (Access->isValueKind() && Access->isRead()) {
1099 Value *AccessVal = Access->getAccessValue();
1100 assert(!ValueReads.lookup(AccessVal));
1101
1102 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001103 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1104 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1105 assert(!PHIWrites.lookup(PHI));
1106
1107 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001108 }
1109
1110 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001111}
1112
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001113void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001114 for (MemoryAccess *MA : *this)
1115 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001116
Johannes Doerferta60ad842016-05-10 12:18:22 +00001117 auto *Ctx = Parent.getContext();
1118 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1119 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001120}
1121
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001122/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
1123static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1124 void *User) {
1125 isl_set **BoundedParts = static_cast<isl_set **>(User);
1126 if (isl_basic_set_is_bounded(BSet))
1127 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1128 else
1129 isl_basic_set_free(BSet);
1130 return isl_stat_ok;
1131}
1132
1133/// @brief Return the bounded parts of @p S.
1134static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1135 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1136 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1137 isl_set_free(S);
1138 return BoundedParts;
1139}
1140
1141/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
1142///
1143/// @returns A separation of @p S into first an unbounded then a bounded subset,
1144/// both with regards to the dimension @p Dim.
1145static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1146partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1147
1148 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001149 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001150
1151 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001152 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001153
1154 // Remove dimensions that are greater than Dim as they are not interesting.
1155 assert(NumDimsS >= Dim + 1);
1156 OnlyDimS =
1157 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1158
1159 // Create artificial parametric upper bounds for dimensions smaller than Dim
1160 // as we are not interested in them.
1161 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1162 for (unsigned u = 0; u < Dim; u++) {
1163 isl_constraint *C = isl_inequality_alloc(
1164 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1165 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1166 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1167 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1168 }
1169
1170 // Collect all bounded parts of OnlyDimS.
1171 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1172
1173 // Create the dimensions greater than Dim again.
1174 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1175 NumDimsS - Dim - 1);
1176
1177 // Remove the artificial upper bound parameters again.
1178 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1179
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001180 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001181 return std::make_pair(UnboundedParts, BoundedParts);
1182}
1183
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001184/// @brief Set the dimension Ids from @p From in @p To.
1185static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1186 __isl_take isl_set *To) {
1187 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1188 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1189 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1190 }
1191 return To;
1192}
1193
1194/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001195static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001196 __isl_take isl_pw_aff *L,
1197 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001198 switch (Pred) {
1199 case ICmpInst::ICMP_EQ:
1200 return isl_pw_aff_eq_set(L, R);
1201 case ICmpInst::ICMP_NE:
1202 return isl_pw_aff_ne_set(L, R);
1203 case ICmpInst::ICMP_SLT:
1204 return isl_pw_aff_lt_set(L, R);
1205 case ICmpInst::ICMP_SLE:
1206 return isl_pw_aff_le_set(L, R);
1207 case ICmpInst::ICMP_SGT:
1208 return isl_pw_aff_gt_set(L, R);
1209 case ICmpInst::ICMP_SGE:
1210 return isl_pw_aff_ge_set(L, R);
1211 case ICmpInst::ICMP_ULT:
1212 return isl_pw_aff_lt_set(L, R);
1213 case ICmpInst::ICMP_UGT:
1214 return isl_pw_aff_gt_set(L, R);
1215 case ICmpInst::ICMP_ULE:
1216 return isl_pw_aff_le_set(L, R);
1217 case ICmpInst::ICMP_UGE:
1218 return isl_pw_aff_ge_set(L, R);
1219 default:
1220 llvm_unreachable("Non integer predicate not supported");
1221 }
1222}
1223
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001224/// @brief Create the conditions under which @p L @p Pred @p R is true.
1225///
1226/// Helper function that will make sure the dimensions of the result have the
1227/// same isl_id's as the @p Domain.
1228static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1229 __isl_take isl_pw_aff *L,
1230 __isl_take isl_pw_aff *R,
1231 __isl_keep isl_set *Domain) {
1232 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1233 return setDimensionIds(Domain, ConsequenceCondSet);
1234}
1235
1236/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001237///
1238/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001239/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1240/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001241static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001242buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1243 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001244 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1245
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001246 Value *Condition = getConditionFromTerminator(SI);
1247 assert(Condition && "No condition for switch");
1248
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001249 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001250 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001251 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001252 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001253
1254 unsigned NumSuccessors = SI->getNumSuccessors();
1255 ConditionSets.resize(NumSuccessors);
1256 for (auto &Case : SI->cases()) {
1257 unsigned Idx = Case.getSuccessorIndex();
1258 ConstantInt *CaseValue = Case.getCaseValue();
1259
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001260 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001261 isl_set *CaseConditionSet =
1262 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1263 ConditionSets[Idx] = isl_set_coalesce(
1264 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1265 }
1266
1267 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1268 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1269 for (unsigned u = 2; u < NumSuccessors; u++)
1270 ConditionSetUnion =
1271 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1272 ConditionSets[0] = setDimensionIds(
1273 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1274
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001275 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001276
1277 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001278}
1279
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001280/// @brief Build the conditions sets for the branch condition @p Condition in
1281/// the @p Domain.
1282///
1283/// This will fill @p ConditionSets with the conditions under which control
1284/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001285/// have as many elements as @p TI has successors. If @p TI is nullptr the
1286/// context under which @p Condition is true/false will be returned as the
1287/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001288static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001289buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1290 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001291 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1292
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001293 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001294 isl_set *ConsequenceCondSet = nullptr;
1295 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1296 if (CCond->isZero())
1297 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1298 else
1299 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1300 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1301 auto Opcode = BinOp->getOpcode();
1302 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1303
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001304 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1305 ConditionSets) &&
1306 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1307 ConditionSets);
1308 if (!Valid) {
1309 while (!ConditionSets.empty())
1310 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001311 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001312 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001313
1314 isl_set_free(ConditionSets.pop_back_val());
1315 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1316 isl_set_free(ConditionSets.pop_back_val());
1317 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1318
1319 if (Opcode == Instruction::And)
1320 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1321 else
1322 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1323 } else {
1324 auto *ICond = dyn_cast<ICmpInst>(Condition);
1325 assert(ICond &&
1326 "Condition of exiting branch was neither constant nor ICmp!");
1327
1328 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001329 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001330 // For unsigned comparisons we assumed the signed bit of neither operand
1331 // to be set. The comparison is equal to a signed comparison under this
1332 // assumption.
1333 bool NonNeg = ICond->isUnsigned();
1334 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1335 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001336 ConsequenceCondSet =
1337 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1338 }
1339
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001340 // If no terminator was given we are only looking for parameter constraints
1341 // under which @p Condition is true/false.
1342 if (!TI)
1343 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001344 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001345 ConsequenceCondSet = isl_set_coalesce(
1346 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001347
Johannes Doerfertb2885792016-04-26 09:20:41 +00001348 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001349 bool TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001350 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001351
Michael Krusef7a4a942016-05-02 12:25:36 +00001352 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001353 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1354 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001355 TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001356 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001357 }
1358
Michael Krusef7a4a942016-05-02 12:25:36 +00001359 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001360 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001361 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001362 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001363 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001364 }
1365
1366 ConditionSets.push_back(ConsequenceCondSet);
1367 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001368
1369 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001370}
1371
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001372/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1373///
1374/// This will fill @p ConditionSets with the conditions under which control
1375/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1376/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001377static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001378buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001379 __isl_keep isl_set *Domain,
1380 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1381
1382 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001383 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001384
1385 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1386
1387 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001388 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001389 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001390 }
1391
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001392 Value *Condition = getConditionFromTerminator(TI);
1393 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001394
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001395 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001396}
1397
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001398void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001399 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001400
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001401 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001402 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001403}
1404
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001405void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP, LoopInfo &LI) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001406 isl_ctx *Ctx = Parent.getIslCtx();
1407 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1408 Type *Ty = GEP->getPointerOperandType();
1409 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 Grosser7b50bee2014-11-25 10:51:12 +00001419 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001420 Ty = PtrTy->getElementType();
1421 }
1422
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001423 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001424
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001425 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001426
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001427 auto *NotExecuted = isl_set_complement(isl_set_params(getDomain()));
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001428 for (size_t i = 0; i < Sizes.size(); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001429 auto *Expr = Subscripts[i + IndexOffset];
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001430 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001431
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001432 auto *Scope = LI.getLoopFor(getEntryBlock());
Johannes Doerfert09e36972015-10-07 20:17:36 +00001433 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +00001434 if (!isAffineExpr(&Parent.getRegion(), Scope, Expr, SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +00001435 continue;
1436
1437 bool NonAffine = false;
1438 for (LoadInst *LInst : AccessILS)
1439 if (!ScopRIL.count(LInst))
1440 NonAffine = true;
1441
1442 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001443 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001444
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001445 isl_pw_aff *AccessOffset = getPwAff(Expr);
1446 AccessOffset =
1447 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001448
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001449 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1450 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001451
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001452 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1453 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1454 OutOfBound = isl_set_params(OutOfBound);
1455 isl_set *InBound = isl_set_complement(OutOfBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001456
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001457 // A => B == !A or B
1458 isl_set *InBoundIfExecuted =
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001459 isl_set_union(isl_set_copy(NotExecuted), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001460
Roman Gareev10595a12016-01-08 14:01:59 +00001461 InBoundIfExecuted = isl_set_coalesce(InBoundIfExecuted);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00001462 Parent.recordAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc(),
1463 AS_ASSUMPTION);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001464 }
1465
1466 isl_local_space_free(LSpace);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001467 isl_set_free(NotExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001468}
1469
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001470void ScopStmt::deriveAssumptions(LoopInfo &LI) {
Johannes Doerfertd5c369f2016-04-25 18:55:15 +00001471 for (auto *MA : *this) {
1472 if (!MA->isArrayKind())
1473 continue;
1474
1475 MemAccInst Acc(MA->getAccessInstruction());
1476 auto *GEP = dyn_cast_or_null<GetElementPtrInst>(Acc.getPointerOperand());
1477
1478 if (GEP)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001479 deriveAssumptionsFromGEP(GEP, LI);
Johannes Doerfertd5c369f2016-04-25 18:55:15 +00001480 }
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001481}
1482
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001483void ScopStmt::collectSurroundingLoops() {
1484 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1485 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1486 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1487 isl_id_free(DimId);
1488 }
1489}
1490
Michael Kruse9d080092015-09-11 21:41:48 +00001491ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerferta3519512016-04-23 13:02:23 +00001492 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1493 R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001494
Tobias Grosser16c44032015-07-09 07:31:45 +00001495 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001496}
1497
Michael Kruse9d080092015-09-11 21:41:48 +00001498ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerferta3519512016-04-23 13:02:23 +00001499 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1500 R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001501
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001502 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001503}
1504
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001505void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001506 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001507
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001508 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001509 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001510 buildAccessRelations();
1511
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001512 deriveAssumptions(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00001513
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001514 if (DetectReductions)
1515 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001516}
1517
Johannes Doerferte58a0122014-06-27 20:31:28 +00001518/// @brief Collect loads which might form a reduction chain with @p StoreMA
1519///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001520/// Check if the stored value for @p StoreMA is a binary operator with one or
1521/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001522/// used only once (by @p StoreMA) and its load operands are also used only
1523/// once, we have found a possible reduction chain. It starts at an operand
1524/// load and includes the binary operator and @p StoreMA.
1525///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001526/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001527/// escape this block or into any other store except @p StoreMA.
1528void ScopStmt::collectCandiateReductionLoads(
1529 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1530 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1531 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001532 return;
1533
1534 // Skip if there is not one binary operator between the load and the store
1535 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001536 if (!BinOp)
1537 return;
1538
1539 // Skip if the binary operators has multiple uses
1540 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001541 return;
1542
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001543 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001544 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1545 return;
1546
Johannes Doerfert9890a052014-07-01 00:32:29 +00001547 // Skip if the binary operator is outside the current SCoP
1548 if (BinOp->getParent() != Store->getParent())
1549 return;
1550
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001551 // Skip if it is a multiplicative reduction and we disabled them
1552 if (DisableMultiplicativeReductions &&
1553 (BinOp->getOpcode() == Instruction::Mul ||
1554 BinOp->getOpcode() == Instruction::FMul))
1555 return;
1556
Johannes Doerferte58a0122014-06-27 20:31:28 +00001557 // Check the binary operator operands for a candidate load
1558 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1559 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1560 if (!PossibleLoad0 && !PossibleLoad1)
1561 return;
1562
1563 // A load is only a candidate if it cannot escape (thus has only this use)
1564 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001565 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001566 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001567 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001568 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001569 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001570}
1571
1572/// @brief Check for reductions in this ScopStmt
1573///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001574/// Iterate over all store memory accesses and check for valid binary reduction
1575/// like chains. For all candidates we check if they have the same base address
1576/// and there are no other accesses which overlap with them. The base address
1577/// check rules out impossible reductions candidates early. The overlap check,
1578/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001579/// guarantees that none of the intermediate results will escape during
1580/// execution of the loop nest. We basically check here that no other memory
1581/// access can access the same memory as the potential reduction.
1582void ScopStmt::checkForReductions() {
1583 SmallVector<MemoryAccess *, 2> Loads;
1584 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1585
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001586 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001587 // stores and collecting possible reduction loads.
1588 for (MemoryAccess *StoreMA : MemAccs) {
1589 if (StoreMA->isRead())
1590 continue;
1591
1592 Loads.clear();
1593 collectCandiateReductionLoads(StoreMA, Loads);
1594 for (MemoryAccess *LoadMA : Loads)
1595 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1596 }
1597
1598 // Then check each possible candidate pair.
1599 for (const auto &CandidatePair : Candidates) {
1600 bool Valid = true;
1601 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1602 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1603
1604 // Skip those with obviously unequal base addresses.
1605 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1606 isl_map_free(LoadAccs);
1607 isl_map_free(StoreAccs);
1608 continue;
1609 }
1610
1611 // And check if the remaining for overlap with other memory accesses.
1612 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1613 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1614 isl_set *AllAccs = isl_map_range(AllAccsRel);
1615
1616 for (MemoryAccess *MA : MemAccs) {
1617 if (MA == CandidatePair.first || MA == CandidatePair.second)
1618 continue;
1619
1620 isl_map *AccRel =
1621 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1622 isl_set *Accs = isl_map_range(AccRel);
1623
1624 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1625 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1626 Valid = Valid && isl_set_is_empty(OverlapAccs);
1627 isl_set_free(OverlapAccs);
1628 }
1629 }
1630
1631 isl_set_free(AllAccs);
1632 if (!Valid)
1633 continue;
1634
Johannes Doerfertf6183392014-07-01 20:52:51 +00001635 const LoadInst *Load =
1636 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1637 MemoryAccess::ReductionType RT =
1638 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1639
Johannes Doerferte58a0122014-06-27 20:31:28 +00001640 // If no overlapping access was found we mark the load and store as
1641 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001642 CandidatePair.first->markAsReductionLike(RT);
1643 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001644 }
Tobias Grosser75805372011-04-29 06:27:02 +00001645}
1646
Tobias Grosser74394f02013-01-14 22:40:23 +00001647std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001648
Tobias Grosser54839312015-04-21 11:37:25 +00001649std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001650 auto *S = getSchedule();
1651 auto Str = stringFromIslObj(S);
1652 isl_map_free(S);
1653 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001654}
1655
Johannes Doerferta3519512016-04-23 13:02:23 +00001656void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1657 isl_set_free(InvalidDomain);
1658 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001659}
1660
Michael Kruse375cb5f2016-02-24 22:08:24 +00001661BasicBlock *ScopStmt::getEntryBlock() const {
1662 if (isBlockStmt())
1663 return getBasicBlock();
1664 return getRegion()->getEntry();
1665}
1666
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001667unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001668
Tobias Grosser75805372011-04-29 06:27:02 +00001669const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1670
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001671Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001672 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001673}
1674
Tobias Grosser74394f02013-01-14 22:40:23 +00001675isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001676
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001677__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001678
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001679__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001680 return isl_set_get_space(Domain);
1681}
1682
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001683__isl_give isl_id *ScopStmt::getDomainId() const {
1684 return isl_set_get_tuple_id(Domain);
1685}
Tobias Grossercd95b772012-08-30 11:49:38 +00001686
Johannes Doerfert7c013572016-04-12 09:57:34 +00001687ScopStmt::~ScopStmt() {
1688 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001689 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001690}
Tobias Grosser75805372011-04-29 06:27:02 +00001691
1692void ScopStmt::print(raw_ostream &OS) const {
1693 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001694 OS.indent(12) << "Domain :=\n";
1695
1696 if (Domain) {
1697 OS.indent(16) << getDomainStr() << ";\n";
1698 } else
1699 OS.indent(16) << "n/a\n";
1700
Tobias Grosser54839312015-04-21 11:37:25 +00001701 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001702
1703 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001704 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001705 } else
1706 OS.indent(16) << "n/a\n";
1707
Tobias Grosser083d3d32014-06-28 08:59:45 +00001708 for (MemoryAccess *Access : MemAccs)
1709 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001710}
1711
1712void ScopStmt::dump() const { print(dbgs()); }
1713
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001714void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001715 // Remove all memory accesses in @p InvMAs from this statement
1716 // together with all scalar accesses that were caused by them.
Michael Krusead28e5a2016-01-26 13:33:15 +00001717 // MK_Value READs have no access instruction, hence would not be removed by
1718 // this function. However, it is only used for invariant LoadInst accesses,
1719 // its arguments are always affine, hence synthesizable, and therefore there
1720 // are no MK_Value READ accesses to be removed.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001721 for (MemoryAccess *MA : InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001722 auto Predicate = [&](MemoryAccess *Acc) {
Tobias Grosser3a6ac9f2015-11-30 21:13:43 +00001723 return Acc->getAccessInstruction() == MA->getAccessInstruction();
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001724 };
1725 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1726 MemAccs.end());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001727 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001728 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001729}
1730
Tobias Grosser75805372011-04-29 06:27:02 +00001731//===----------------------------------------------------------------------===//
1732/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001733
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001734void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001735 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1736 isl_set_free(Context);
1737 Context = NewContext;
1738}
1739
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001740/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1741struct SCEVSensitiveParameterRewriter
1742 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1743 ValueToValueMap &VMap;
1744 ScalarEvolution &SE;
1745
1746public:
1747 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1748 : VMap(VMap), SE(SE) {}
1749
1750 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1751 ValueToValueMap &VMap) {
1752 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1753 return SSPR.visit(E);
1754 }
1755
1756 const SCEV *visit(const SCEV *E) {
1757 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1758 }
1759
1760 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1761
1762 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1763 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1764 }
1765
1766 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1767 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1768 }
1769
1770 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1771 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1772 }
1773
1774 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1775 SmallVector<const SCEV *, 4> Operands;
1776 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1777 Operands.push_back(visit(E->getOperand(i)));
1778 return SE.getAddExpr(Operands);
1779 }
1780
1781 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1782 SmallVector<const SCEV *, 4> Operands;
1783 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1784 Operands.push_back(visit(E->getOperand(i)));
1785 return SE.getMulExpr(Operands);
1786 }
1787
1788 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1789 SmallVector<const SCEV *, 4> Operands;
1790 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1791 Operands.push_back(visit(E->getOperand(i)));
1792 return SE.getSMaxExpr(Operands);
1793 }
1794
1795 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1796 SmallVector<const SCEV *, 4> Operands;
1797 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1798 Operands.push_back(visit(E->getOperand(i)));
1799 return SE.getUMaxExpr(Operands);
1800 }
1801
1802 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1803 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1804 }
1805
1806 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1807 auto *Start = visit(E->getStart());
1808 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1809 visit(E->getStepRecurrence(SE)),
1810 E->getLoop(), SCEV::FlagAnyWrap);
1811 return SE.getAddExpr(Start, AddRec);
1812 }
1813
1814 const SCEV *visitUnknown(const SCEVUnknown *E) {
1815 if (auto *NewValue = VMap.lookup(E->getValue()))
1816 return SE.getUnknown(NewValue);
1817 return E;
1818 }
1819};
1820
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001821const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001822 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001823}
1824
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001825void Scop::createParameterId(const SCEV *Parameter) {
1826 assert(Parameters.count(Parameter));
1827 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001828
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001829 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001830
Tobias Grosser8f99c162011-11-15 11:38:55 +00001831 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1832 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001833
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001834 // If this parameter references a specific Value and this value has a name
1835 // we use this name as it is likely to be unique and more useful than just
1836 // a number.
1837 if (Val->hasName())
1838 ParameterName = Val->getName();
1839 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001840 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001841 if (LoadOrigin->hasName()) {
1842 ParameterName += "_loaded_from_";
1843 ParameterName +=
1844 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1845 }
1846 }
1847 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001848
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001849 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1850 const_cast<void *>((const void *)Parameter));
1851 ParameterIds[Parameter] = Id;
1852}
1853
1854void Scop::addParams(const ParameterSetTy &NewParameters) {
1855 for (const SCEV *Parameter : NewParameters) {
1856 // Normalize the SCEV to get the representing element for an invariant load.
1857 Parameter = extractConstantFactor(Parameter, *SE).second;
1858 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1859
1860 if (Parameters.insert(Parameter))
1861 createParameterId(Parameter);
1862 }
1863}
1864
1865__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1866 // Normalize the SCEV to get the representing element for an invariant load.
1867 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1868 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001869}
Tobias Grosser75805372011-04-29 06:27:02 +00001870
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001871__isl_give isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001872 isl_set *DomainContext = isl_union_set_params(getDomains());
1873 return isl_set_intersect_params(C, DomainContext);
1874}
1875
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001876void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1877 LoopInfo &LI) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001878 auto *R = &getRegion();
1879 auto &F = *R->getEntry()->getParent();
1880 for (auto &Assumption : AC.assumptions()) {
1881 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1882 if (!CI || CI->getNumArgOperands() != 1)
1883 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001884
1885 bool InR = R->contains(CI);
1886 if (!InR && !DT.dominates(CI->getParent(), R->getEntry()))
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001887 continue;
1888
Michael Kruse09eb4452016-03-03 22:10:47 +00001889 auto *L = LI.getLoopFor(CI->getParent());
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001890 auto *Val = CI->getArgOperand(0);
Johannes Doerfertf560b3d2016-04-25 13:33:07 +00001891 ParameterSetTy DetectedParams;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001892 if (!isAffineConstraint(Val, R, L, *SE, DetectedParams)) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001893 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1894 CI->getDebugLoc(),
1895 "Non-affine user assumption ignored.");
1896 continue;
1897 }
1898
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001899 // Collect all newly introduced parameters.
1900 ParameterSetTy NewParams;
1901 for (auto *Param : DetectedParams) {
1902 Param = extractConstantFactor(Param, *SE).second;
1903 Param = getRepresentingInvariantLoadSCEV(Param);
1904 if (Parameters.count(Param))
1905 continue;
1906 NewParams.insert(Param);
1907 }
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001908
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001909 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001910 auto *TI = InR ? CI->getParent()->getTerminator() : nullptr;
1911 auto &Stmt = InR ? *getStmtFor(CI->getParent()) : *Stmts.begin();
1912 auto *Dom = InR ? getDomainConditions(&Stmt) : isl_set_copy(Context);
1913 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
1914 isl_set_free(Dom);
1915
1916 if (!Valid)
Johannes Doerfert297c7202016-05-10 13:06:42 +00001917 continue;
1918
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001919 isl_set *AssumptionCtx = nullptr;
1920 if (InR) {
1921 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
1922 isl_set_free(ConditionSets[0]);
1923 } else {
1924 AssumptionCtx = isl_set_complement(ConditionSets[1]);
1925 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
1926 }
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001927
1928 // Project out newly introduced parameters as they are not otherwise useful.
1929 if (!NewParams.empty()) {
1930 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
1931 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
1932 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
1933 isl_id_free(Id);
1934
1935 if (!NewParams.count(Param))
1936 continue;
1937
1938 AssumptionCtx =
1939 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
1940 }
1941 }
1942
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001943 emitOptimizationRemarkAnalysis(
1944 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1945 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1946 Context = isl_set_intersect(Context, AssumptionCtx);
1947 }
1948}
1949
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001950void Scop::addUserContext() {
1951 if (UserContextStr.empty())
1952 return;
1953
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001954 isl_set *UserContext =
1955 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001956 isl_space *Space = getParamSpace();
1957 if (isl_space_dim(Space, isl_dim_param) !=
1958 isl_set_dim(UserContext, isl_dim_param)) {
1959 auto SpaceStr = isl_space_to_str(Space);
1960 errs() << "Error: the context provided in -polly-context has not the same "
1961 << "number of dimensions than the computed context. Due to this "
1962 << "mismatch, the -polly-context option is ignored. Please provide "
1963 << "the context in the parameter space: " << SpaceStr << ".\n";
1964 free(SpaceStr);
1965 isl_set_free(UserContext);
1966 isl_space_free(Space);
1967 return;
1968 }
1969
1970 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001971 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1972 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001973
1974 if (strcmp(NameContext, NameUserContext) != 0) {
1975 auto SpaceStr = isl_space_to_str(Space);
1976 errs() << "Error: the name of dimension " << i
1977 << " provided in -polly-context "
1978 << "is '" << NameUserContext << "', but the name in the computed "
1979 << "context is '" << NameContext
1980 << "'. Due to this name mismatch, "
1981 << "the -polly-context option is ignored. Please provide "
1982 << "the context in the parameter space: " << SpaceStr << ".\n";
1983 free(SpaceStr);
1984 isl_set_free(UserContext);
1985 isl_space_free(Space);
1986 return;
1987 }
1988
1989 UserContext =
1990 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1991 isl_space_get_dim_id(Space, isl_dim_param, i));
1992 }
1993
1994 Context = isl_set_intersect(Context, UserContext);
1995 isl_space_free(Space);
1996}
1997
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001998void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001999 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002000
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002001 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002002 for (LoadInst *LInst : RIL) {
2003 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2004
Johannes Doerfert96e54712016-02-07 17:30:13 +00002005 Type *Ty = LInst->getType();
2006 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002007 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002008 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002009 continue;
2010 }
2011
2012 ClassRep = LInst;
Johannes Doerfert96e54712016-02-07 17:30:13 +00002013 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(), nullptr,
2014 Ty);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002015 }
2016}
2017
Tobias Grosser6be480c2011-11-08 15:41:13 +00002018void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002019 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002020 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002021 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002022 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002023}
2024
Tobias Grosser18daaca2012-05-22 10:47:27 +00002025void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002026 unsigned PDim = 0;
2027 for (auto *Parameter : Parameters) {
2028 ConstantRange SRange = SE->getSignedRange(Parameter);
2029 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002030 }
2031}
2032
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002033void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002034 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002035 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002036
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002037 unsigned PDim = 0;
2038 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002039 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002040 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002041 }
2042
2043 // Align the parameters of all data structures to the model.
2044 Context = isl_set_align_params(Context, Space);
2045
Johannes Doerferta60ad842016-05-10 12:18:22 +00002046 // As all parameters are known add bounds to them.
2047 addParameterBounds();
2048
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002049 for (ScopStmt &Stmt : *this)
2050 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002051}
2052
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002053static __isl_give isl_set *
2054simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2055 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002056 // If we modelt all blocks in the SCoP that have side effects we can simplify
2057 // the context with the constraints that are needed for anything to be
2058 // executed at all. However, if we have error blocks in the SCoP we already
2059 // assumed some parameter combinations cannot occure and removed them from the
2060 // domains, thus we cannot use the remaining domain to simplify the
2061 // assumptions.
2062 if (!S.hasErrorBlock()) {
2063 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2064 AssumptionContext =
2065 isl_set_gist_params(AssumptionContext, DomainParameters);
2066 }
2067
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002068 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2069 return AssumptionContext;
2070}
2071
2072void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002073 // The parameter constraints of the iteration domains give us a set of
2074 // constraints that need to hold for all cases where at least a single
2075 // statement iteration is executed in the whole scop. We now simplify the
2076 // assumed context under the assumption that such constraints hold and at
2077 // least a single statement iteration is executed. For cases where no
2078 // statement instances are executed, the assumptions we have taken about
2079 // the executed code do not matter and can be changed.
2080 //
2081 // WARNING: This only holds if the assumptions we have taken do not reduce
2082 // the set of statement instances that are executed. Otherwise we
2083 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002084 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002085 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002086 // performed. In such a case, modifying the run-time conditions and
2087 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002088 // to not be executed.
2089 //
2090 // Example:
2091 //
2092 // When delinearizing the following code:
2093 //
2094 // for (long i = 0; i < 100; i++)
2095 // for (long j = 0; j < m; j++)
2096 // A[i+p][j] = 1.0;
2097 //
2098 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002099 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002100 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002101 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002102 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002103}
2104
Johannes Doerfertb164c792014-09-18 11:17:17 +00002105/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002106static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002107 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2108 isl_pw_multi_aff *MinPMA, *MaxPMA;
2109 isl_pw_aff *LastDimAff;
2110 isl_aff *OneAff;
2111 unsigned Pos;
2112
Johannes Doerfert6296d952016-04-22 11:38:19 +00002113 Set = isl_set_remove_divs(Set);
2114
Michael Krusebc150122016-05-02 12:25:18 +00002115 if (isl_set_n_basic_set(Set) >= MaxDisjunctionsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002116 isl_set_free(Set);
2117 return isl_stat_error;
2118 }
2119
Johannes Doerfert9143d672014-09-27 11:02:39 +00002120 // Restrict the number of parameters involved in the access as the lexmin/
2121 // lexmax computation will take too long if this number is high.
2122 //
2123 // Experiments with a simple test case using an i7 4800MQ:
2124 //
2125 // #Parameters involved | Time (in sec)
2126 // 6 | 0.01
2127 // 7 | 0.04
2128 // 8 | 0.12
2129 // 9 | 0.40
2130 // 10 | 1.54
2131 // 11 | 6.78
2132 // 12 | 30.38
2133 //
2134 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2135 unsigned InvolvedParams = 0;
2136 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2137 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2138 InvolvedParams++;
2139
2140 if (InvolvedParams > RunTimeChecksMaxParameters) {
2141 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002142 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002143 }
2144 }
2145
Johannes Doerfertb164c792014-09-18 11:17:17 +00002146 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2147 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2148
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002149 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2150 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2151
Johannes Doerfertb164c792014-09-18 11:17:17 +00002152 // Adjust the last dimension of the maximal access by one as we want to
2153 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2154 // we test during code generation might now point after the end of the
2155 // allocated array but we will never dereference it anyway.
2156 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2157 "Assumed at least one output dimension");
2158 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2159 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2160 OneAff = isl_aff_zero_on_domain(
2161 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2162 OneAff = isl_aff_add_constant_si(OneAff, 1);
2163 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2164 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2165
2166 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2167
2168 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002169 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002170}
2171
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002172static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2173 isl_set *Domain = MA->getStatement()->getDomain();
2174 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2175 return isl_set_reset_tuple_id(Domain);
2176}
2177
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002178/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
2179static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002180 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002181 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002182
2183 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2184 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002185 Locations = isl_union_set_coalesce(Locations);
2186 Locations = isl_union_set_detect_equalities(Locations);
2187 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002188 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002189 isl_union_set_free(Locations);
2190 return Valid;
2191}
2192
Johannes Doerfert96425c22015-08-30 21:13:53 +00002193/// @brief Helper to treat non-affine regions and basic blocks the same.
2194///
2195///{
2196
2197/// @brief Return the block that is the representing block for @p RN.
2198static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2199 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2200 : RN->getNodeAs<BasicBlock>();
2201}
2202
2203/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002204static inline BasicBlock *
2205getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002206 if (RN->isSubRegion()) {
2207 assert(idx == 0);
2208 return RN->getNodeAs<Region>()->getExit();
2209 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002210 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002211}
2212
2213/// @brief Return the smallest loop surrounding @p RN.
2214static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2215 if (!RN->isSubRegion())
2216 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2217
2218 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2219 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2220 while (L && NonAffineSubRegion->contains(L))
2221 L = L->getParentLoop();
2222 return L;
2223}
2224
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002225static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2226 if (!RN->isSubRegion())
2227 return 1;
2228
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002229 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002230 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002231}
2232
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002233static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2234 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002235 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002236 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002237 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002238 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002239 return true;
2240 return false;
2241}
2242
Johannes Doerfert96425c22015-08-30 21:13:53 +00002243///}
2244
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002245static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2246 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002247 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002248 isl_id *DimId =
2249 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2250 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2251}
2252
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002253__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002254 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002255}
2256
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002257__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002258 auto DIt = DomainMap.find(BB);
2259 if (DIt != DomainMap.end())
2260 return isl_set_copy(DIt->getSecond());
2261
2262 auto &RI = *R.getRegionInfo();
2263 auto *BBR = RI.getRegionFor(BB);
2264 while (BBR->getEntry() == BB)
2265 BBR = BBR->getParent();
2266 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002267}
2268
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002269bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002270
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002271 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002272 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002273 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2274 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002275 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002276
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002277 while (LD-- >= 0) {
2278 S = addDomainDimId(S, LD + 1, L);
2279 L = L->getParentLoop();
2280 }
2281
Johannes Doerferta3519512016-04-23 13:02:23 +00002282 // Initialize the invalid domain.
2283 auto *EntryStmt = getStmtFor(EntryBB);
2284 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2285
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002286 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002287
Johannes Doerfert432658d2016-01-26 11:01:41 +00002288 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002289 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002290
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002291 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002292 return false;
2293
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002294 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002295 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002296
2297 // Error blocks and blocks dominated by them have been assumed to never be
2298 // executed. Representing them in the Scop does not add any value. In fact,
2299 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002300 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002301 // will cause problems when building up a ScopStmt for them.
2302 // Furthermore, basic blocks dominated by error blocks may reference
2303 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002304 // can themselves not be constructed properly. To this end we will replace
2305 // the domains of error blocks and those only reachable via error blocks
2306 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002307 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002308 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002309 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002310 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002311
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002312 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002313}
2314
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002315static Loop *getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI,
2316 const BoxedLoopsSetTy &BoxedLoops) {
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002317 auto *L = LI.getLoopFor(BB);
2318 while (BoxedLoops.count(L))
2319 L = L->getParentLoop();
2320 return L;
2321}
2322
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002323/// @brief Adjust the dimensions of @p Dom that was constructed for @p OldL
2324/// to be compatible to domains constructed for loop @p NewL.
2325///
2326/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2327/// edge from @p OldL to @p NewL.
2328static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2329 __isl_take isl_set *Dom,
2330 Loop *OldL, Loop *NewL) {
2331
2332 // If the loops are the same there is nothing to do.
2333 if (NewL == OldL)
2334 return Dom;
2335
2336 int OldDepth = S.getRelativeLoopDepth(OldL);
2337 int NewDepth = S.getRelativeLoopDepth(NewL);
2338 // If both loops are non-affine loops there is nothing to do.
2339 if (OldDepth == -1 && NewDepth == -1)
2340 return Dom;
2341
2342 // Distinguish three cases:
2343 // 1) The depth is the same but the loops are not.
2344 // => One loop was left one was entered.
2345 // 2) The depth increased from OldL to NewL.
2346 // => One loop was entered, none was left.
2347 // 3) The depth decreased from OldL to NewL.
2348 // => Loops were left were difference of the depths defines how many.
2349 if (OldDepth == NewDepth) {
2350 assert(OldL->getParentLoop() == NewL->getParentLoop());
2351 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2352 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2353 Dom = addDomainDimId(Dom, NewDepth, NewL);
2354 } else if (OldDepth < NewDepth) {
2355 assert(OldDepth + 1 == NewDepth);
2356 auto &R = S.getRegion();
2357 (void)R;
2358 assert(NewL->getParentLoop() == OldL ||
2359 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2360 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2361 Dom = addDomainDimId(Dom, NewDepth, NewL);
2362 } else {
2363 assert(OldDepth > NewDepth);
2364 int Diff = OldDepth - NewDepth;
2365 int NumDim = isl_set_n_dim(Dom);
2366 assert(NumDim >= Diff);
2367 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2368 }
2369
2370 return Dom;
2371}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002372
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002373bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2374 LoopInfo &LI) {
2375 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002376
2377 ReversePostOrderTraversal<Region *> RTraversal(R);
2378 for (auto *RN : RTraversal) {
2379
2380 // Recurse for affine subregions but go on for basic blocks and non-affine
2381 // subregions.
2382 if (RN->isSubRegion()) {
2383 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002384 if (!isNonAffineSubRegion(SubRegion)) {
2385 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002386 continue;
2387 }
2388 }
2389
2390 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2391 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002392 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002393 isl_set *&Domain = DomainMap[BB];
2394 assert(Domain && "Cannot propagate a nullptr");
2395
Johannes Doerferta3519512016-04-23 13:02:23 +00002396 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002397 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002398 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002399
Johannes Doerferta3519512016-04-23 13:02:23 +00002400 if (!IsInvalidBlock) {
2401 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002402 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002403 isl_set_free(InvalidDomain);
2404 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002405 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2406 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2407 AS_RESTRICTION);
2408 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002409 }
2410
Johannes Doerferta3519512016-04-23 13:02:23 +00002411 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002412 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002413 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002414 }
2415
Johannes Doerferta3519512016-04-23 13:02:23 +00002416 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002417 auto *TI = BB->getTerminator();
2418 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2419 for (unsigned u = 0; u < NumSuccs; u++) {
2420 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002421 auto *SuccStmt = getStmtFor(SuccBB);
2422
2423 // Skip successors outside the SCoP.
2424 if (!SuccStmt)
2425 continue;
2426
Johannes Doerferte4459a22016-04-25 13:34:50 +00002427 // Skip backedges.
2428 if (DT.dominates(SuccBB, BB))
2429 continue;
2430
Johannes Doerferta3519512016-04-23 13:02:23 +00002431 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2432 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2433 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2434 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2435 SuccInvalidDomain =
2436 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2437 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2438 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2439 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002440
Michael Krusebc150122016-05-02 12:25:18 +00002441 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002442 // In case this happens we will bail.
Michael Krusebc150122016-05-02 12:25:18 +00002443 if (NumConjucts < MaxDisjunctionsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002444 continue;
2445
Johannes Doerferta3519512016-04-23 13:02:23 +00002446 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002447 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002448 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002449 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002450
2451 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002452 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002453
2454 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002455}
2456
Johannes Doerfert642594a2016-04-04 07:57:39 +00002457void Scop::propagateDomainConstraintsToRegionExit(
2458 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002459 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002460
2461 // Check if the block @p BB is the entry of a region. If so we propagate it's
2462 // domain to the exit block of the region. Otherwise we are done.
2463 auto *RI = R.getRegionInfo();
2464 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2465 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
2466 if (!BBReg || BBReg->getEntry() != BB || !R.contains(ExitBB))
2467 return;
2468
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002469 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002470 // Do not propagate the domain if there is a loop backedge inside the region
2471 // that would prevent the exit block from beeing executed.
2472 auto *L = BBLoop;
2473 while (L && R.contains(L)) {
2474 SmallVector<BasicBlock *, 4> LatchBBs;
2475 BBLoop->getLoopLatches(LatchBBs);
2476 for (auto *LatchBB : LatchBBs)
2477 if (BB != LatchBB && BBReg->contains(LatchBB))
2478 return;
2479 L = L->getParentLoop();
2480 }
2481
2482 auto *Domain = DomainMap[BB];
2483 assert(Domain && "Cannot propagate a nullptr");
2484
2485 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2486
2487 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2488 // adjust the domain before we can propagate it.
2489 auto *AdjustedDomain =
2490 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2491 auto *&ExitDomain = DomainMap[ExitBB];
2492
2493 // If the exit domain is not yet created we set it otherwise we "add" the
2494 // current domain.
2495 ExitDomain =
2496 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2497
Johannes Doerferta3519512016-04-23 13:02:23 +00002498 // Initialize the invalid domain.
2499 auto *ExitStmt = getStmtFor(ExitBB);
2500 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2501
Johannes Doerfert642594a2016-04-04 07:57:39 +00002502 FinishedExitBlocks.insert(ExitBB);
2503}
2504
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002505bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2506 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002507 // To create the domain for each block in R we iterate over all blocks and
2508 // subregions in R and propagate the conditions under which the current region
2509 // element is executed. To this end we iterate in reverse post order over R as
2510 // it ensures that we first visit all predecessors of a region node (either a
2511 // basic block or a subregion) before we visit the region node itself.
2512 // Initially, only the domain for the SCoP region entry block is set and from
2513 // there we propagate the current domain to all successors, however we add the
2514 // condition that the successor is actually executed next.
2515 // As we are only interested in non-loop carried constraints here we can
2516 // simply skip loop back edges.
2517
Johannes Doerfert642594a2016-04-04 07:57:39 +00002518 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002519 ReversePostOrderTraversal<Region *> RTraversal(R);
2520 for (auto *RN : RTraversal) {
2521
2522 // Recurse for affine subregions but go on for basic blocks and non-affine
2523 // subregions.
2524 if (RN->isSubRegion()) {
2525 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002526 if (!isNonAffineSubRegion(SubRegion)) {
2527 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002528 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002529 continue;
2530 }
2531 }
2532
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002533 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002534 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002535
Johannes Doerfert96425c22015-08-30 21:13:53 +00002536 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002537 TerminatorInst *TI = BB->getTerminator();
2538
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002539 if (isa<UnreachableInst>(TI))
2540 continue;
2541
Johannes Doerfertf5673802015-10-01 23:48:18 +00002542 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002543 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002544 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002545 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002546
Johannes Doerfert642594a2016-04-04 07:57:39 +00002547 auto *BBLoop = getRegionNodeLoop(RN, LI);
2548 // Propagate the domain from BB directly to blocks that have a superset
2549 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002550 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002551
2552 // If all successors of BB have been set a domain through the propagation
2553 // above we do not need to build condition sets but can just skip this
2554 // block. However, it is important to note that this is a local property
2555 // with regards to the region @p R. To this end FinishedExitBlocks is a
2556 // local variable.
2557 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2558 return FinishedExitBlocks.count(SuccBB);
2559 };
2560 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2561 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002562
2563 // Build the condition sets for the successor nodes of the current region
2564 // node. If it is a non-affine subregion we will always execute the single
2565 // exit node, hence the single entry node domain is the condition set. For
2566 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002567 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002568 if (RN->isSubRegion())
2569 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002570 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2571 ConditionSets))
2572 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002573
2574 // Now iterate over the successors and set their initial domain based on
2575 // their condition set. We skip back edges here and have to be careful when
2576 // we leave a loop not to keep constraints over a dimension that doesn't
2577 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002578 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002579 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002580 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002581 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002582
Johannes Doerfert535de032016-04-19 14:49:05 +00002583 auto *SuccStmt = getStmtFor(SuccBB);
2584 // Skip blocks outside the region.
2585 if (!SuccStmt) {
2586 isl_set_free(CondSet);
2587 continue;
2588 }
2589
Johannes Doerfert642594a2016-04-04 07:57:39 +00002590 // If we propagate the domain of some block to "SuccBB" we do not have to
2591 // adjust the domain.
2592 if (FinishedExitBlocks.count(SuccBB)) {
2593 isl_set_free(CondSet);
2594 continue;
2595 }
2596
Johannes Doerfert96425c22015-08-30 21:13:53 +00002597 // Skip back edges.
2598 if (DT.dominates(SuccBB, BB)) {
2599 isl_set_free(CondSet);
2600 continue;
2601 }
2602
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002603 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002604 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002605 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002606
2607 // Set the domain for the successor or merge it with an existing domain in
2608 // case there are multiple paths (without loop back edges) to the
2609 // successor block.
2610 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002611
Johannes Doerferta3519512016-04-23 13:02:23 +00002612 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002613 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002614 } else {
2615 // Initialize the invalid domain.
2616 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2617 SuccDomain = CondSet;
2618 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002619
Michael Krusebc150122016-05-02 12:25:18 +00002620 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002621 // In case this happens we will clean up and bail.
Michael Krusebc150122016-05-02 12:25:18 +00002622 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctionsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002623 continue;
2624
2625 invalidate(COMPLEXITY, DebugLoc());
2626 while (++u < ConditionSets.size())
2627 isl_set_free(ConditionSets[u]);
2628 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002629 }
2630 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002631
2632 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002633}
2634
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00002635__isl_give isl_set *Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2636 isl_set *Domain,
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00002637 DominatorTree &DT,
2638 LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002639 // If @p BB is the ScopEntry we are done
2640 if (R.getEntry() == BB)
2641 return isl_set_universe(isl_set_get_space(Domain));
2642
2643 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002644 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002645
2646 // The region info of this function.
2647 auto &RI = *R.getRegionInfo();
2648
2649 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2650
2651 // A domain to collect all predecessor domains, thus all conditions under
2652 // which the block is executed. To this end we start with the empty domain.
2653 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2654
2655 // Set of regions of which the entry block domain has been propagated to BB.
2656 // all predecessors inside any of the regions can be skipped.
2657 SmallSet<Region *, 8> PropagatedRegions;
2658
2659 for (auto *PredBB : predecessors(BB)) {
2660 // Skip backedges.
2661 if (DT.dominates(BB, PredBB))
2662 continue;
2663
2664 // If the predecessor is in a region we used for propagation we can skip it.
2665 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2666 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2667 PredBBInRegion)) {
2668 continue;
2669 }
2670
2671 // Check if there is a valid region we can use for propagation, thus look
2672 // for a region that contains the predecessor and has @p BB as exit block.
2673 auto *PredR = RI.getRegionFor(PredBB);
2674 while (PredR->getExit() != BB && !PredR->contains(BB))
2675 PredR->getParent();
2676
2677 // If a valid region for propagation was found use the entry of that region
2678 // for propagation, otherwise the PredBB directly.
2679 if (PredR->getExit() == BB) {
2680 PredBB = PredR->getEntry();
2681 PropagatedRegions.insert(PredR);
2682 }
2683
Johannes Doerfert41cda152016-04-08 10:32:26 +00002684 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002685 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2686 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2687
2688 PredDom = isl_set_union(PredDom, PredBBDom);
2689 }
2690
2691 return PredDom;
2692}
2693
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002694bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2695 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002696 // Iterate over the region R and propagate the domain constrains from the
2697 // predecessors to the current node. In contrast to the
2698 // buildDomainsWithBranchConstraints function, this one will pull the domain
2699 // information from the predecessors instead of pushing it to the successors.
2700 // Additionally, we assume the domains to be already present in the domain
2701 // map here. However, we iterate again in reverse post order so we know all
2702 // predecessors have been visited before a block or non-affine subregion is
2703 // visited.
2704
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002705 ReversePostOrderTraversal<Region *> RTraversal(R);
2706 for (auto *RN : RTraversal) {
2707
2708 // Recurse for affine subregions but go on for basic blocks and non-affine
2709 // subregions.
2710 if (RN->isSubRegion()) {
2711 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002712 if (!isNonAffineSubRegion(SubRegion)) {
2713 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002714 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002715 continue;
2716 }
2717 }
2718
2719 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002720 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002721 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002722
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002723 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002724 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002725 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002726 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002727
Johannes Doerfert642594a2016-04-04 07:57:39 +00002728 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002729 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002730 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2731 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002732 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002733
2734 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002735}
2736
2737/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2738/// is incremented by one and all other dimensions are equal, e.g.,
2739/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2740/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2741static __isl_give isl_map *
2742createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2743 auto *MapSpace = isl_space_map_from_set(SetSpace);
2744 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2745 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2746 if (u != Dim)
2747 NextIterationMap =
2748 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2749 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2750 C = isl_constraint_set_constant_si(C, 1);
2751 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2752 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2753 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2754 return NextIterationMap;
2755}
2756
Johannes Doerfert297c7202016-05-10 13:06:42 +00002757bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002758 int LoopDepth = getRelativeLoopDepth(L);
2759 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002760
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002761 BasicBlock *HeaderBB = L->getHeader();
2762 assert(DomainMap.count(HeaderBB));
2763 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002764
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002765 isl_map *NextIterationMap =
2766 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002767
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002768 isl_set *UnionBackedgeCondition =
2769 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002770
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002771 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2772 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002773
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002774 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002775
2776 // If the latch is only reachable via error statements we skip it.
2777 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2778 if (!LatchBBDom)
2779 continue;
2780
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002781 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002782
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002783 TerminatorInst *TI = LatchBB->getTerminator();
2784 BranchInst *BI = dyn_cast<BranchInst>(TI);
2785 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002786 BackedgeCondition = isl_set_copy(LatchBBDom);
2787 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002788 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002789 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002790 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
2791 ConditionSets))
2792 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002793
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002794 // Free the non back edge condition set as we do not need it.
2795 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002796
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002797 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002798 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002799
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002800 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2801 assert(LatchLoopDepth >= LoopDepth);
2802 BackedgeCondition =
2803 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2804 LatchLoopDepth - LoopDepth);
2805 UnionBackedgeCondition =
2806 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002807 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002808
2809 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2810 for (int i = 0; i < LoopDepth; i++)
2811 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2812
2813 isl_set *UnionBackedgeConditionComplement =
2814 isl_set_complement(UnionBackedgeCondition);
2815 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2816 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2817 UnionBackedgeConditionComplement =
2818 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2819 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2820 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2821
2822 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2823 HeaderBBDom = Parts.second;
2824
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002825 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2826 // the bounded assumptions to the context as they are already implied by the
2827 // <nsw> tag.
2828 if (Affinator.hasNSWAddRecForLoop(L)) {
2829 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002830 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002831 }
2832
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002833 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002834 recordAssumption(INFINITELOOP, UnboundedCtx,
2835 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002836 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002837}
2838
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002839void Scop::buildAliasChecks(AliasAnalysis &AA) {
2840 if (!PollyUseRuntimeAliasChecks)
2841 return;
2842
2843 if (buildAliasGroups(AA))
2844 return;
2845
2846 // If a problem occurs while building the alias groups we need to delete
2847 // this SCoP and pretend it wasn't valid in the first place. To this end
2848 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002849 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002850
2851 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2852 << " could not be created as the number of parameters involved "
2853 "is too high. The SCoP will be "
2854 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2855 "the maximal number of parameters but be advised that the "
2856 "compile time might increase exponentially.\n\n");
2857}
2858
Johannes Doerfert9143d672014-09-27 11:02:39 +00002859bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002860 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002861 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002862 // for all memory accesses inside the SCoP.
2863 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002864 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002865 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002866 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002867 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002868 // if their access domains intersect, otherwise they are in different
2869 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002870 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002871 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002872 // and maximal accesses to each array of a group in read only and non
2873 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002874 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2875
2876 AliasSetTracker AST(AA);
2877
2878 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002879 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002880 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002881
2882 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002883 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002884 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2885 isl_set_free(StmtDomain);
2886 if (StmtDomainEmpty)
2887 continue;
2888
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002889 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002890 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002891 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002892 if (!MA->isRead())
2893 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002894 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002895 if (MA->isRead() && isa<MemTransferInst>(Acc))
2896 PtrToAcc[cast<MemTransferInst>(Acc)->getSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002897 else
2898 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002899 AST.add(Acc);
2900 }
2901 }
2902
2903 SmallVector<AliasGroupTy, 4> AliasGroups;
2904 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002905 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002906 continue;
2907 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002908 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002909 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002910 if (AG.size() < 2)
2911 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002912 AliasGroups.push_back(std::move(AG));
2913 }
2914
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002915 // Split the alias groups based on their domain.
2916 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2917 AliasGroupTy NewAG;
2918 AliasGroupTy &AG = AliasGroups[u];
2919 AliasGroupTy::iterator AGI = AG.begin();
2920 isl_set *AGDomain = getAccessDomain(*AGI);
2921 while (AGI != AG.end()) {
2922 MemoryAccess *MA = *AGI;
2923 isl_set *MADomain = getAccessDomain(MA);
2924 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2925 NewAG.push_back(MA);
2926 AGI = AG.erase(AGI);
2927 isl_set_free(MADomain);
2928 } else {
2929 AGDomain = isl_set_union(AGDomain, MADomain);
2930 AGI++;
2931 }
2932 }
2933 if (NewAG.size() > 1)
2934 AliasGroups.push_back(std::move(NewAG));
2935 isl_set_free(AGDomain);
2936 }
2937
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002938 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002939 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002940 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2941 for (AliasGroupTy &AG : AliasGroups) {
2942 NonReadOnlyBaseValues.clear();
2943 ReadOnlyPairs.clear();
2944
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002945 if (AG.size() < 2) {
2946 AG.clear();
2947 continue;
2948 }
2949
Johannes Doerfert13771732014-10-01 12:40:46 +00002950 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002951 emitOptimizationRemarkAnalysis(
2952 F.getContext(), DEBUG_TYPE, F,
2953 (*II)->getAccessInstruction()->getDebugLoc(),
2954 "Possibly aliasing pointer, use restrict keyword.");
2955
Johannes Doerfert13771732014-10-01 12:40:46 +00002956 Value *BaseAddr = (*II)->getBaseAddr();
2957 if (HasWriteAccess.count(BaseAddr)) {
2958 NonReadOnlyBaseValues.insert(BaseAddr);
2959 II++;
2960 } else {
2961 ReadOnlyPairs[BaseAddr].insert(*II);
2962 II = AG.erase(II);
2963 }
2964 }
2965
2966 // If we don't have read only pointers check if there are at least two
2967 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002968 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002969 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002970 continue;
2971 }
2972
2973 // If we don't have non read only pointers clear the alias group.
2974 if (NonReadOnlyBaseValues.empty()) {
2975 AG.clear();
2976 continue;
2977 }
2978
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002979 // Check if we have non-affine accesses left, if so bail out as we cannot
2980 // generate a good access range yet.
2981 for (auto *MA : AG)
2982 if (!MA->isAffine()) {
2983 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2984 return false;
2985 }
2986 for (auto &ReadOnlyPair : ReadOnlyPairs)
2987 for (auto *MA : ReadOnlyPair.second)
2988 if (!MA->isAffine()) {
2989 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2990 return false;
2991 }
2992
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002993 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002994 MinMaxAliasGroups.emplace_back();
2995 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2996 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2997 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2998 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002999
3000 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003001
3002 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00003003 for (MemoryAccess *MA : AG)
3004 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003005
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003006 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
3007 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003008
3009 // Bail out if the number of values we need to compare is too large.
3010 // This is important as the number of comparisions grows quadratically with
3011 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003012 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
3013 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003014 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003015
3016 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003017 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003018 Accesses = isl_union_map_empty(getParamSpace());
3019
3020 for (const auto &ReadOnlyPair : ReadOnlyPairs)
3021 for (MemoryAccess *MA : ReadOnlyPair.second)
3022 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
3023
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003024 Valid =
3025 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003026
3027 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003028 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003029 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003030
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003031 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003032}
3033
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003034/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003035static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003036 // Start with the smallest loop containing the entry and expand that
3037 // loop until it contains all blocks in the region. If there is a loop
3038 // containing all blocks in the region check if it is itself contained
3039 // and if so take the parent loop as it will be the smallest containing
3040 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003041 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003042 while (L) {
3043 bool AllContained = true;
3044 for (auto *BB : R.blocks())
3045 AllContained &= L->contains(BB);
3046 if (AllContained)
3047 break;
3048 L = L->getParentLoop();
3049 }
3050
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003051 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
3052}
3053
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003054Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003055 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003056 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003057 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003058 MaxLoopDepth(0), DC(DC), IslCtx(isl_ctx_alloc(), isl_ctx_free),
3059 Context(nullptr), Affinator(this, LI), AssumedContext(nullptr),
3060 InvalidContext(nullptr), Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003061 if (IslOnErrorAbort)
3062 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003063 buildContext();
3064}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003065
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003066void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT,
3067 LoopInfo &LI) {
3068 buildInvariantEquivalenceClasses();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003069
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003070 if (!buildDomains(&R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003071 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003072
Johannes Doerfertff68f462016-04-19 14:49:42 +00003073 addUserAssumptions(AC, DT, LI);
3074
Johannes Doerfert26404542016-05-10 12:19:47 +00003075 // Remove empty statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003076 // Exit early in case there are no executable statements left in this scop.
Johannes Doerfert26404542016-05-10 12:19:47 +00003077 simplifySCoP(false, DT, LI);
Michael Kruseafe06702015-10-02 16:33:27 +00003078 if (Stmts.empty())
3079 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003080
Michael Krusecac948e2015-10-02 13:53:07 +00003081 // The ScopStmts now have enough information to initialize themselves.
3082 for (ScopStmt &Stmt : Stmts)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003083 Stmt.init(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00003084
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003085 // Check early for profitability. Afterwards it cannot change anymore,
3086 // only the runtime context could become infeasible.
3087 if (!isProfitable()) {
3088 invalidate(PROFITABLE, DebugLoc());
Tobias Grosser8286b832015-11-02 11:29:32 +00003089 return;
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003090 }
3091
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003092 buildSchedule(LI);
Tobias Grosser8286b832015-11-02 11:29:32 +00003093
3094 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003095 realignParams();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003096 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003097
3098 // After the context was fully constructed, thus all our knowledge about
3099 // the parameters is in there, we add all recorded assumptions to the
3100 // assumed/invalid context.
3101 addRecordedAssumptions();
3102
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003103 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003104 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003105
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003106 hoistInvariantLoads();
3107 verifyInvariantLoads();
Johannes Doerfert26404542016-05-10 12:19:47 +00003108 simplifySCoP(true, DT, LI);
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003109
3110 // Check late for a feasible runtime context because profitability did not
3111 // change.
3112 if (!hasFeasibleRuntimeContext()) {
3113 invalidate(PROFITABLE, DebugLoc());
3114 return;
3115 }
Tobias Grosser75805372011-04-29 06:27:02 +00003116}
3117
3118Scop::~Scop() {
3119 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003120 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003121 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003122 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003123
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003124 for (auto &It : ParameterIds)
3125 isl_id_free(It.second);
3126
Johannes Doerfert96425c22015-08-30 21:13:53 +00003127 for (auto It : DomainMap)
3128 isl_set_free(It.second);
3129
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003130 for (auto &AS : RecordedAssumptions)
3131 isl_set_free(AS.Set);
3132
Johannes Doerfertb164c792014-09-18 11:17:17 +00003133 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003134 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003135 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003136 isl_pw_multi_aff_free(MMA.first);
3137 isl_pw_multi_aff_free(MMA.second);
3138 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003139 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003140 isl_pw_multi_aff_free(MMA.first);
3141 isl_pw_multi_aff_free(MMA.second);
3142 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003143 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003144
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003145 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003146 isl_set_free(std::get<2>(IAClass));
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003147
3148 // Explicitly release all Scop objects and the underlying isl objects before
3149 // we relase the isl context.
3150 Stmts.clear();
3151 ScopArrayInfoMap.clear();
3152 AccFuncMap.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003153}
3154
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003155void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003156 // Check all array accesses for each base pointer and find a (virtual) element
3157 // size for the base pointer that divides all access functions.
3158 for (auto &Stmt : *this)
3159 for (auto *Access : Stmt) {
3160 if (!Access->isArrayKind())
3161 continue;
3162 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
3163 ScopArrayInfo::MK_Array)];
3164 if (SAI->getNumberOfDimensions() != 1)
3165 continue;
3166 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3167 auto *Subscript = Access->getSubscript(0);
3168 while (!isDivisible(Subscript, DivisibleSize, *SE))
3169 DivisibleSize /= 2;
3170 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3171 SAI->updateElementType(Ty);
3172 }
3173
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003174 for (auto &Stmt : *this)
3175 for (auto &Access : Stmt)
3176 Access->updateDimensionality();
3177}
3178
Johannes Doerfert26404542016-05-10 12:19:47 +00003179void Scop::simplifySCoP(bool AfterHoisting, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003180 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3181 ScopStmt &Stmt = *StmtIt;
3182
Johannes Doerfert26404542016-05-10 12:19:47 +00003183 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003184 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003185 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003186
Johannes Doerferteca9e892015-11-03 16:54:49 +00003187 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003188 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003189 bool OnlyRead = true;
3190 for (MemoryAccess *MA : Stmt) {
3191 if (MA->isRead())
3192 continue;
3193
3194 OnlyRead = false;
3195 break;
3196 }
3197
3198 RemoveStmt = OnlyRead;
3199 }
3200
Johannes Doerfert26404542016-05-10 12:19:47 +00003201 if (!RemoveStmt) {
3202 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003203 continue;
3204 }
3205
Johannes Doerfert26404542016-05-10 12:19:47 +00003206 // Remove the statement because it is unnecessary.
3207 if (Stmt.isRegionStmt())
3208 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3209 StmtMap.erase(BB);
3210 else
3211 StmtMap.erase(Stmt.getBasicBlock());
3212
3213 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003214 }
3215}
3216
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003217InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003218 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3219 if (!LInst)
3220 return nullptr;
3221
3222 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3223 LInst = cast<LoadInst>(Rep);
3224
Johannes Doerfert96e54712016-02-07 17:30:13 +00003225 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003226 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003227 for (auto &IAClass : InvariantEquivClasses) {
3228 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
3229 continue;
3230
3231 auto &MAs = std::get<1>(IAClass);
3232 for (auto *MA : MAs)
3233 if (MA->getAccessInstruction() == Val)
3234 return &IAClass;
3235 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003236
3237 return nullptr;
3238}
3239
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003240/// @brief Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003241static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
3242 bool MAInvalidCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003243 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3244 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3245 // TODO: We can provide more information for better but more expensive
3246 // results.
3247 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3248 LInst->getAlignment(), DL))
3249 return false;
3250
3251 // If a dereferencable load is in a statement that is modeled precisely we can
3252 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003253 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003254 return true;
3255
3256 // Even if the statement is not modeled precisely we can hoist the load if it
3257 // does not involve any parameters that might have been specilized by the
3258 // statement domain.
3259 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3260 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3261 return false;
3262 return true;
3263}
3264
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003265void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
3266
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003267 if (InvMAs.empty())
3268 return;
3269
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003270 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003271 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003272
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003273 // Get the context under which the statement is executed but remove the error
3274 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003275 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003276 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003277
Michael Krusebc150122016-05-02 12:25:18 +00003278 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctionsInDomain) {
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003279 auto *AccInst = InvMAs.front()->getAccessInstruction();
3280 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3281 isl_set_free(DomainCtx);
3282 return;
3283 }
3284
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003285 // Project out all parameters that relate to loads in the statement. Otherwise
3286 // we could have cyclic dependences on the constraints under which the
3287 // hoisted loads are executed and we could not determine an order in which to
3288 // pre-load them. This happens because not only lower bounds are part of the
3289 // domain but also upper bounds.
3290 for (MemoryAccess *MA : InvMAs) {
3291 Instruction *AccInst = MA->getAccessInstruction();
3292 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003293 SetVector<Value *> Values;
3294 for (const SCEV *Parameter : Parameters) {
3295 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003296 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003297 if (!Values.count(AccInst))
3298 continue;
3299
3300 if (isl_id *ParamId = getIdForParam(Parameter)) {
3301 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3302 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3303 isl_id_free(ParamId);
3304 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003305 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003306 }
3307 }
3308
3309 for (MemoryAccess *MA : InvMAs) {
3310 // Check for another invariant access that accesses the same location as
3311 // MA and if found consolidate them. Otherwise create a new equivalence
3312 // class at the end of InvariantEquivClasses.
3313 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003314 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003315 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3316
Johannes Doerfert85676e32016-04-23 14:32:34 +00003317 auto *MAInvalidCtx = MA->getInvalidContext();
3318 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3319
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003320 isl_set *MACtx;
3321 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003322 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003323 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003324 isl_set_free(MAInvalidCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003325 } else {
3326 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003327 MACtx = isl_set_subtract(MACtx, MAInvalidCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003328 MACtx = isl_set_gist_params(MACtx, getContext());
3329 }
3330
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003331 bool Consolidated = false;
3332 for (auto &IAClass : InvariantEquivClasses) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00003333 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003334 continue;
3335
Johannes Doerfertdf880232016-03-03 12:26:58 +00003336 // If the pointer and the type is equal check if the access function wrt.
3337 // to the domain is equal too. It can happen that the domain fixes
3338 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003339 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003340 // create a new invariant load equivalence class.
3341 auto &MAs = std::get<1>(IAClass);
3342 if (!MAs.empty()) {
3343 auto *LastMA = MAs.front();
3344
3345 auto *AR = isl_map_range(MA->getAccessRelation());
3346 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3347 bool SameAR = isl_set_is_equal(AR, LastAR);
3348 isl_set_free(AR);
3349 isl_set_free(LastAR);
3350
3351 if (!SameAR)
3352 continue;
3353 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003354
3355 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003356 MAs.push_front(MA);
3357
Johannes Doerfertdf880232016-03-03 12:26:58 +00003358 Consolidated = true;
3359
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003360 // Unify the execution context of the class and this statement.
3361 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003362 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003363 IAClassDomainCtx =
3364 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003365 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003366 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003367 break;
3368 }
3369
3370 if (Consolidated)
3371 continue;
3372
3373 // If we did not consolidate MA, thus did not find an equivalence class
3374 // for it, we create a new one.
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003375 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA}, MACtx,
3376 Ty);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003377 }
3378
3379 isl_set_free(DomainCtx);
3380}
3381
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003382bool Scop::isHoistableAccess(MemoryAccess *Access,
3383 __isl_keep isl_union_map *Writes) {
3384 // TODO: Loads that are not loop carried, hence are in a statement with
3385 // zero iterators, are by construction invariant, though we
3386 // currently "hoist" them anyway. This is necessary because we allow
3387 // them to be treated as parameters (e.g., in conditions) and our code
3388 // generation would otherwise use the old value.
3389
3390 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003391 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003392
3393 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
3394 return false;
3395
3396 // Skip accesses that have an invariant base pointer which is defined but
3397 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3398 // returns a pointer that is used as a base address. However, as we want
3399 // to hoist indirect pointers, we allow the base pointer to be defined in
3400 // the region if it is also a memory access. Each ScopArrayInfo object
3401 // that has a base pointer origin has a base pointer that is loaded and
3402 // that it is invariant, thus it will be hoisted too. However, if there is
3403 // no base pointer origin we check that the base pointer is defined
3404 // outside the region.
3405 const ScopArrayInfo *SAI = Access->getScopArrayInfo();
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003406 auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr());
3407 if (SAI->getBasePtrOriginSAI()) {
3408 assert(BasePtrInst && R.contains(BasePtrInst));
3409 if (!isa<LoadInst>(BasePtrInst))
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003410 return false;
Michael Kruse6f7721f2016-02-24 22:08:19 +00003411 auto *BasePtrStmt = getStmtFor(BasePtrInst);
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003412 assert(BasePtrStmt);
3413 auto *BasePtrMA = BasePtrStmt->getArrayAccessOrNULLFor(BasePtrInst);
3414 if (BasePtrMA && !isHoistableAccess(BasePtrMA, Writes))
3415 return false;
3416 } else if (BasePtrInst && R.contains(BasePtrInst))
3417 return false;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003418
3419 // Skip accesses in non-affine subregions as they might not be executed
3420 // under the same condition as the entry of the non-affine subregion.
Johannes Doerfertcda1bd52016-05-19 13:47:34 +00003421 if (BB != Access->getAccessInstruction()->getParent())
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003422 return false;
3423
3424 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003425 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003426
3427 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3428 Stmt.getNumIterators())) {
3429 isl_map_free(AccessRelation);
3430 return false;
3431 }
3432
3433 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3434 isl_set *AccessRange = isl_map_range(AccessRelation);
3435
3436 isl_union_map *Written = isl_union_map_intersect_range(
3437 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
3438 bool IsWritten = !isl_union_map_is_empty(Written);
Johannes Doerfertcda1bd52016-05-19 13:47:34 +00003439 isl_union_map_free(Written);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003440
Johannes Doerfertcda1bd52016-05-19 13:47:34 +00003441 if (IsWritten)
3442 return false;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003443
Johannes Doerfertcda1bd52016-05-19 13:47:34 +00003444 return true;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003445}
3446
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003447void Scop::verifyInvariantLoads() {
3448 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003449 for (LoadInst *LI : RIL) {
3450 assert(LI && getRegion().contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003451 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003452 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003453 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3454 return;
3455 }
3456 }
3457}
3458
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003459void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003460 if (!PollyInvariantLoadHoisting)
3461 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003462
Tobias Grosser0865e7752016-02-29 07:29:42 +00003463 isl_union_map *Writes = getWrites();
3464 for (ScopStmt &Stmt : *this) {
3465 MemoryAccessList InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003466
Tobias Grosser0865e7752016-02-29 07:29:42 +00003467 for (MemoryAccess *Access : Stmt)
3468 if (isHoistableAccess(Access, Writes))
3469 InvariantAccesses.push_front(Access);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003470
Tobias Grosser0865e7752016-02-29 07:29:42 +00003471 // We inserted invariant accesses always in the front but need them to be
3472 // sorted in a "natural order". The statements are already sorted in
3473 // reverse post order and that suffices for the accesses too. The reason
3474 // we require an order in the first place is the dependences between
3475 // invariant loads that can be caused by indirect loads.
3476 InvariantAccesses.reverse();
3477
3478 // Transfer the memory access from the statement to the SCoP.
3479 Stmt.removeMemoryAccesses(InvariantAccesses);
3480 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003481 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003482 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003483}
3484
Johannes Doerfert80ef1102014-11-07 08:31:31 +00003485const ScopArrayInfo *
Tobias Grossercc779502016-02-02 13:22:54 +00003486Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003487 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003488 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003489 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003490 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003491 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003492 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003493 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003494 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003495 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003496 // In case of mismatching array sizes, we bail out by setting the run-time
3497 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003498 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003499 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003500 }
Tobias Grosserab671442015-05-23 05:58:27 +00003501 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003502}
3503
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003504const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003505 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003506 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003507 assert(SAI && "No ScopArrayInfo available for this base pointer");
3508 return SAI;
3509}
3510
Tobias Grosser74394f02013-01-14 22:40:23 +00003511std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003512
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003513std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003514 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003515 return stringFromIslObj(AssumedContext);
3516}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003517
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003518std::string Scop::getInvalidContextStr() const {
3519 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003520}
Tobias Grosser75805372011-04-29 06:27:02 +00003521
3522std::string Scop::getNameStr() const {
3523 std::string ExitName, EntryName;
3524 raw_string_ostream ExitStr(ExitName);
3525 raw_string_ostream EntryStr(EntryName);
3526
Tobias Grosserf240b482014-01-09 10:42:15 +00003527 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003528 EntryStr.str();
3529
3530 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003531 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003532 ExitStr.str();
3533 } else
3534 ExitName = "FunctionExit";
3535
3536 return EntryName + "---" + ExitName;
3537}
3538
Tobias Grosser74394f02013-01-14 22:40:23 +00003539__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003540__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003541 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003542}
3543
Tobias Grossere86109f2013-10-29 21:05:49 +00003544__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003545 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003546 return isl_set_copy(AssumedContext);
3547}
3548
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003549bool Scop::isProfitable() const {
3550 if (PollyProcessUnprofitable)
3551 return true;
3552
3553 if (!hasFeasibleRuntimeContext())
3554 return false;
3555
3556 if (isEmpty())
3557 return false;
3558
3559 unsigned OptimizableStmtsOrLoops = 0;
3560 for (auto &Stmt : *this) {
3561 if (Stmt.getNumIterators() == 0)
3562 continue;
3563
3564 bool ContainsArrayAccs = false;
3565 bool ContainsScalarAccs = false;
3566 for (auto *MA : Stmt) {
3567 if (MA->isRead())
3568 continue;
3569 ContainsArrayAccs |= MA->isArrayKind();
3570 ContainsScalarAccs |= MA->isScalarKind();
3571 }
3572
3573 if (ContainsArrayAccs && !ContainsScalarAccs)
3574 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3575 }
3576
3577 return OptimizableStmtsOrLoops > 1;
3578}
3579
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003580bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003581 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003582 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003583 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3584 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3585 isl_set_is_subset(PositiveContext, NegativeContext));
3586 isl_set_free(PositiveContext);
3587 if (!IsFeasible) {
3588 isl_set_free(NegativeContext);
3589 return false;
3590 }
3591
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003592 auto *DomainContext = isl_union_set_params(getDomains());
3593 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003594 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003595 isl_set_free(NegativeContext);
3596 isl_set_free(DomainContext);
3597
Johannes Doerfert43788c52015-08-20 05:58:56 +00003598 return IsFeasible;
3599}
3600
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003601static std::string toString(AssumptionKind Kind) {
3602 switch (Kind) {
3603 case ALIASING:
3604 return "No-aliasing";
3605 case INBOUNDS:
3606 return "Inbounds";
3607 case WRAPPING:
3608 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00003609 case UNSIGNED:
3610 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003611 case COMPLEXITY:
3612 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003613 case PROFITABLE:
3614 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003615 case ERRORBLOCK:
3616 return "No-error";
3617 case INFINITELOOP:
3618 return "Finite loop";
3619 case INVARIANTLOAD:
3620 return "Invariant load";
3621 case DELINEARIZATION:
3622 return "Delinearization";
3623 }
3624 llvm_unreachable("Unknown AssumptionKind!");
3625}
3626
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003627bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3628 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert2f705842016-04-12 16:09:44 +00003629 if (PollyRemarksMinimal) {
3630 if (Sign == AS_ASSUMPTION) {
3631 if (isl_set_is_subset(Context, Set))
3632 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003633
Johannes Doerfert2f705842016-04-12 16:09:44 +00003634 if (isl_set_is_subset(AssumedContext, Set))
3635 return false;
3636 } else {
3637 if (isl_set_is_disjoint(Set, Context))
3638 return false;
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003639
Johannes Doerfert2f705842016-04-12 16:09:44 +00003640 if (isl_set_is_subset(Set, InvalidContext))
3641 return false;
3642 }
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003643 }
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003644
3645 auto &F = *getRegion().getEntry()->getParent();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003646 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3647 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003648 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003649 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003650}
3651
3652void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003653 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003654 // Simplify the assumptions/restrictions first.
3655 Set = isl_set_gist_params(Set, getContext());
3656
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003657 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3658 isl_set_free(Set);
3659 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003660 }
3661
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003662 if (Sign == AS_ASSUMPTION) {
3663 AssumedContext = isl_set_intersect(AssumedContext, Set);
3664 AssumedContext = isl_set_coalesce(AssumedContext);
3665 } else {
3666 InvalidContext = isl_set_union(InvalidContext, Set);
3667 InvalidContext = isl_set_coalesce(InvalidContext);
3668 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003669}
3670
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003671void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003672 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
3673 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003674}
3675
3676void Scop::addRecordedAssumptions() {
3677 while (!RecordedAssumptions.empty()) {
3678 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003679
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003680 if (!AS.BB) {
3681 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
3682 continue;
3683 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003684
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003685 // If the domain was deleted the assumptions are void.
3686 isl_set *Dom = getDomainConditions(AS.BB);
3687 if (!Dom) {
3688 isl_set_free(AS.Set);
3689 continue;
3690 }
3691
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003692 // If a basic block was given use its domain to simplify the assumption.
3693 // In case of restrictions we know they only have to hold on the domain,
3694 // thus we can intersect them with the domain of the block. However, for
3695 // assumptions the domain has to imply them, thus:
3696 // _ _____
3697 // Dom => S <==> A v B <==> A - B
3698 //
3699 // To avoid the complement we will register A - B as a restricton not an
3700 // assumption.
3701 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003702 if (AS.Sign == AS_RESTRICTION)
3703 S = isl_set_params(isl_set_intersect(S, Dom));
3704 else /* (AS.Sign == AS_ASSUMPTION) */
3705 S = isl_set_params(isl_set_subtract(Dom, S));
3706
3707 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003708 }
3709}
3710
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003711void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003712 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003713}
3714
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003715__isl_give isl_set *Scop::getInvalidContext() const {
3716 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003717}
3718
Tobias Grosser75805372011-04-29 06:27:02 +00003719void Scop::printContext(raw_ostream &OS) const {
3720 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003721 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003722
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003723 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003724 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003725
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003726 OS.indent(4) << "Invalid Context:\n";
3727 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003728
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003729 unsigned Dim = 0;
3730 for (const SCEV *Parameter : Parameters)
3731 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003732}
3733
Johannes Doerfertb164c792014-09-18 11:17:17 +00003734void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003735 int noOfGroups = 0;
3736 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003737 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003738 noOfGroups += 1;
3739 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003740 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003741 }
3742
Tobias Grosserbb853c22015-07-25 12:31:03 +00003743 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003744 if (MinMaxAliasGroups.empty()) {
3745 OS.indent(8) << "n/a\n";
3746 return;
3747 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003748
Tobias Grosserbb853c22015-07-25 12:31:03 +00003749 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003750
3751 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003752 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003753 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003754 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003755 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3756 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003757 }
3758 OS << " ]]\n";
3759 }
3760
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003761 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003762 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003763 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003764 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003765 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3766 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003767 }
3768 OS << " ]]\n";
3769 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003770 }
3771}
3772
Tobias Grosser75805372011-04-29 06:27:02 +00003773void Scop::printStatements(raw_ostream &OS) const {
3774 OS << "Statements {\n";
3775
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003776 for (const ScopStmt &Stmt : *this)
3777 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003778
3779 OS.indent(4) << "}\n";
3780}
3781
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003782void Scop::printArrayInfo(raw_ostream &OS) const {
3783 OS << "Arrays {\n";
3784
Tobias Grosserab671442015-05-23 05:58:27 +00003785 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003786 Array.second->print(OS);
3787
3788 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003789
3790 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3791
3792 for (auto &Array : arrays())
3793 Array.second->print(OS, /* SizeAsPwAff */ true);
3794
3795 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003796}
3797
Tobias Grosser75805372011-04-29 06:27:02 +00003798void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003799 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3800 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003801 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003802 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003803 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003804 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003805 const auto &MAs = std::get<1>(IAClass);
3806 if (MAs.empty()) {
3807 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003808 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003809 MAs.front()->print(OS);
3810 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003811 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003812 }
3813 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003814 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003815 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003816 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003817 printStatements(OS.indent(4));
3818}
3819
3820void Scop::dump() const { print(dbgs()); }
3821
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003822isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003823
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003824__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
3825 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003826 // First try to use the SCEVAffinator to generate a piecewise defined
3827 // affine function from @p E in the context of @p BB. If that tasks becomes to
3828 // complex the affinator might return a nullptr. In such a case we invalidate
3829 // the SCoP and return a dummy value. This way we do not need to add error
3830 // handling cdoe to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003831 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003832 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00003833 // TODO: We could use a heuristic and either use:
3834 // SCEVAffinator::takeNonNegativeAssumption
3835 // or
3836 // SCEVAffinator::interpretAsUnsigned
3837 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003838 if (NonNegative)
3839 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003840 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003841 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003842
3843 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
3844 invalidate(COMPLEXITY, DL);
3845 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003846}
3847
Tobias Grosser808cd692015-07-14 09:33:13 +00003848__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003849 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003850
Tobias Grosser808cd692015-07-14 09:33:13 +00003851 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003852 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003853
3854 return Domain;
3855}
3856
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003857__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
3858 PWACtx PWAC = getPwAff(E, BB);
3859 isl_set_free(PWAC.second);
3860 return PWAC.first;
3861}
3862
Tobias Grossere5a35142015-11-12 14:07:09 +00003863__isl_give isl_union_map *
3864Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3865 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003866
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003867 for (ScopStmt &Stmt : *this) {
3868 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003869 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003870 continue;
3871
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003872 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003873 isl_map *AccessDomain = MA->getAccessRelation();
3874 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003875 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003876 }
3877 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003878 return isl_union_map_coalesce(Accesses);
3879}
3880
3881__isl_give isl_union_map *Scop::getMustWrites() {
3882 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003883}
3884
3885__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003886 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003887}
3888
Tobias Grosser37eb4222014-02-20 21:43:54 +00003889__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003890 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003891}
3892
3893__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003894 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003895}
3896
Tobias Grosser2ac23382015-11-12 14:07:13 +00003897__isl_give isl_union_map *Scop::getAccesses() {
3898 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3899}
3900
Tobias Grosser808cd692015-07-14 09:33:13 +00003901__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003902 auto *Tree = getScheduleTree();
3903 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00003904 isl_schedule_free(Tree);
3905 return S;
3906}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003907
Tobias Grosser808cd692015-07-14 09:33:13 +00003908__isl_give isl_schedule *Scop::getScheduleTree() const {
3909 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3910 getDomains());
3911}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003912
Tobias Grosser808cd692015-07-14 09:33:13 +00003913void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3914 auto *S = isl_schedule_from_domain(getDomains());
3915 S = isl_schedule_insert_partial_schedule(
3916 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3917 isl_schedule_free(Schedule);
3918 Schedule = S;
3919}
3920
3921void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3922 isl_schedule_free(Schedule);
3923 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003924}
3925
3926bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3927 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003928 for (ScopStmt &Stmt : *this) {
3929 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003930 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3931 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3932
3933 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3934 isl_union_set_free(StmtDomain);
3935 isl_union_set_free(NewStmtDomain);
3936 continue;
3937 }
3938
3939 Changed = true;
3940
3941 isl_union_set_free(StmtDomain);
3942 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3943
3944 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003945 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003946 isl_union_set_free(NewStmtDomain);
3947 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003948 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003949 }
3950 isl_union_set_free(Domain);
3951 return Changed;
3952}
3953
Tobias Grosser75805372011-04-29 06:27:02 +00003954ScalarEvolution *Scop::getSE() const { return SE; }
3955
Tobias Grosser808cd692015-07-14 09:33:13 +00003956struct MapToDimensionDataTy {
3957 int N;
3958 isl_union_pw_multi_aff *Res;
3959};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003960
Tobias Grosser808cd692015-07-14 09:33:13 +00003961// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003962// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003963//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003964// @param Set The input set.
3965// @param User->N The dimension to map to.
3966// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003967//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003968// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003969static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3970 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3971 int Dim;
3972 isl_space *Space;
3973 isl_pw_multi_aff *PMA;
3974
3975 Dim = isl_set_dim(Set, isl_dim_set);
3976 Space = isl_set_get_space(Set);
3977 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3978 Dim - Data->N);
3979 if (Data->N > 1)
3980 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3981 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3982
3983 isl_set_free(Set);
3984
3985 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003986}
3987
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003988// @brief Create an isl_multi_union_aff that defines an identity mapping
3989// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003990//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003991// # Example:
3992//
3993// Domain: { A[i,j]; B[i,j,k] }
3994// N: 1
3995//
3996// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
3997//
3998// @param USet A union set describing the elements for which to generate a
3999// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004000// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004001// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004002static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004003mapToDimension(__isl_take isl_union_set *USet, int N) {
4004 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004005 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004006 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004007
Tobias Grosser808cd692015-07-14 09:33:13 +00004008 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004009
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004010 auto *Space = isl_union_set_get_space(USet);
4011 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004012
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004013 Data = {N, PwAff};
4014
4015 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004016 (void)Res;
4017
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004018 assert(Res == isl_stat_ok);
4019
4020 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004021 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4022}
4023
Tobias Grosser316b5b22015-11-11 19:28:14 +00004024void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00004025 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00004026 Stmts.emplace_back(*this, *BB);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004027 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004028 StmtMap[BB] = Stmt;
4029 } else {
4030 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00004031 Stmts.emplace_back(*this, *R);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004032 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004033 for (BasicBlock *BB : R->blocks())
4034 StmtMap[BB] = Stmt;
4035 }
Tobias Grosser808cd692015-07-14 09:33:13 +00004036}
4037
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004038void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004039 Loop *L = getLoopSurroundingRegion(getRegion(), LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004040 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004041 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004042 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4043 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004044}
4045
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004046/// To generate a schedule for the elements in a Region we traverse the Region
4047/// in reverse-post-order and add the contained RegionNodes in traversal order
4048/// to the schedule of the loop that is currently at the top of the LoopStack.
4049/// For loop-free codes, this results in a correct sequential ordering.
4050///
4051/// Example:
4052/// bb1(0)
4053/// / \.
4054/// bb2(1) bb3(2)
4055/// \ / \.
4056/// bb4(3) bb5(4)
4057/// \ /
4058/// bb6(5)
4059///
4060/// Including loops requires additional processing. Whenever a loop header is
4061/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4062/// from an empty schedule, we first process all RegionNodes that are within
4063/// this loop and complete the sequential schedule at this loop-level before
4064/// processing about any other nodes. To implement this
4065/// loop-nodes-first-processing, the reverse post-order traversal is
4066/// insufficient. Hence, we additionally check if the traversal yields
4067/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4068/// These region-nodes are then queue and only traverse after the all nodes
4069/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004070void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004071 Loop *OuterScopLoop = getLoopSurroundingRegion(getRegion(), LI);
4072
4073 ReversePostOrderTraversal<Region *> RTraversal(R);
4074 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4075 std::deque<RegionNode *> DelayList;
4076 bool LastRNWaiting = false;
4077
4078 // Iterate over the region @p R in reverse post-order but queue
4079 // sub-regions/blocks iff they are not part of the last encountered but not
4080 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4081 // that we queued the last sub-region/block from the reverse post-order
4082 // iterator. If it is set we have to explore the next sub-region/block from
4083 // the iterator (if any) to guarantee progress. If it is not set we first try
4084 // the next queued sub-region/blocks.
4085 while (!WorkList.empty() || !DelayList.empty()) {
4086 RegionNode *RN;
4087
4088 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4089 RN = WorkList.front();
4090 WorkList.pop_front();
4091 LastRNWaiting = false;
4092 } else {
4093 RN = DelayList.front();
4094 DelayList.pop_front();
4095 }
4096
4097 Loop *L = getRegionNodeLoop(RN, LI);
4098 if (!getRegion().contains(L))
4099 L = OuterScopLoop;
4100
Tobias Grosser151ae322016-04-03 19:36:52 +00004101 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004102 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004103 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004104 LastRNWaiting = true;
4105 DelayList.push_back(RN);
4106 continue;
4107 }
4108 LoopStack.push_back({L, nullptr, 0});
4109 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004110 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004111 }
4112
4113 return;
4114}
4115
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004116void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004117
Tobias Grosser8362c262016-01-06 15:30:06 +00004118 if (RN->isSubRegion()) {
4119 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004120 if (!isNonAffineSubRegion(LocalRegion)) {
4121 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004122 return;
4123 }
4124 }
Michael Kruse046dde42015-08-10 13:01:57 +00004125
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004126 auto &LoopData = LoopStack.back();
4127 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004128
Michael Kruse6f7721f2016-02-24 22:08:19 +00004129 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004130 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4131 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004132 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004133 }
4134
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004135 // Check if we just processed the last node in this loop. If we did, finalize
4136 // the loop by:
4137 //
4138 // - adding new schedule dimensions
4139 // - folding the resulting schedule into the parent loop schedule
4140 // - dropping the loop schedule from the LoopStack.
4141 //
4142 // Then continue to check surrounding loops, which might also have been
4143 // completed by this node.
4144 while (LoopData.L &&
4145 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004146 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004147 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004148
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004149 LoopStack.pop_back();
4150 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004151
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004152 if (Schedule) {
4153 auto *Domain = isl_schedule_get_domain(Schedule);
4154 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4155 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4156 NextLoopData.Schedule =
4157 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004158 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004159
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004160 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4161 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004162 }
Tobias Grosser75805372011-04-29 06:27:02 +00004163}
4164
Michael Kruse6f7721f2016-02-24 22:08:19 +00004165ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004166 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004167 if (StmtMapIt == StmtMap.end())
4168 return nullptr;
4169 return StmtMapIt->second;
4170}
4171
Michael Kruse6f7721f2016-02-24 22:08:19 +00004172ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4173 if (RN->isSubRegion())
4174 return getStmtFor(RN->getNodeAs<Region>());
4175 return getStmtFor(RN->getNodeAs<BasicBlock>());
4176}
4177
4178ScopStmt *Scop::getStmtFor(Region *R) const {
4179 ScopStmt *Stmt = getStmtFor(R->getEntry());
4180 assert(!Stmt || Stmt->getRegion() == R);
4181 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004182}
4183
Johannes Doerfert96425c22015-08-30 21:13:53 +00004184int Scop::getRelativeLoopDepth(const Loop *L) const {
4185 Loop *OuterLoop =
4186 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4187 if (!OuterLoop)
4188 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004189 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4190}
4191
Michael Krused868b5d2015-09-10 15:25:24 +00004192void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00004193 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00004194
4195 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
4196 // true, are not modeled as ordinary PHI nodes as they are not part of the
4197 // region. However, we model the operands in the predecessor blocks that are
4198 // part of the region as regular scalar accesses.
4199
4200 // If we can synthesize a PHI we can skip it, however only if it is in
4201 // the region. If it is not it can only be in the exit block of the region.
4202 // In this case we model the operands but not the PHI itself.
Michael Krusec7e0d9c2016-03-01 21:44:06 +00004203 auto *Scope = LI->getLoopFor(PHI->getParent());
4204 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R, Scope))
Michael Kruse7bf39442015-09-10 12:46:52 +00004205 return;
4206
4207 // PHI nodes are modeled as if they had been demoted prior to the SCoP
4208 // detection. Hence, the PHI is a load of a new memory location in which the
4209 // incoming value was written at the end of the incoming basic block.
4210 bool OnlyNonAffineSubRegionOperands = true;
4211 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
4212 Value *Op = PHI->getIncomingValue(u);
4213 BasicBlock *OpBB = PHI->getIncomingBlock(u);
4214
4215 // Do not build scalar dependences inside a non-affine subregion.
4216 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
4217 continue;
4218
4219 OnlyNonAffineSubRegionOperands = false;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004220 ensurePHIWrite(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00004221 }
4222
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004223 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
4224 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00004225 }
4226}
4227
Michael Kruse2e02d562016-02-06 09:19:40 +00004228void ScopInfo::buildScalarDependences(Instruction *Inst) {
4229 assert(!isa<PHINode>(Inst));
Michael Kruse7bf39442015-09-10 12:46:52 +00004230
Michael Kruse2e02d562016-02-06 09:19:40 +00004231 // Pull-in required operands.
4232 for (Use &Op : Inst->operands())
4233 ensureValueRead(Op.get(), Inst->getParent());
4234}
Michael Kruse7bf39442015-09-10 12:46:52 +00004235
Michael Kruse2e02d562016-02-06 09:19:40 +00004236void ScopInfo::buildEscapingDependences(Instruction *Inst) {
4237 Region *R = &scop->getRegion();
Michael Kruse7bf39442015-09-10 12:46:52 +00004238
Michael Kruse2e02d562016-02-06 09:19:40 +00004239 // Check for uses of this instruction outside the scop. Because we do not
4240 // iterate over such instructions and therefore did not "ensure" the existence
4241 // of a write, we must determine such use here.
4242 for (Use &U : Inst->uses()) {
4243 Instruction *UI = dyn_cast<Instruction>(U.getUser());
4244 if (!UI)
Michael Kruse7bf39442015-09-10 12:46:52 +00004245 continue;
4246
Michael Kruse2e02d562016-02-06 09:19:40 +00004247 BasicBlock *UseParent = getUseBlock(U);
4248 BasicBlock *UserParent = UI->getParent();
Michael Kruse7bf39442015-09-10 12:46:52 +00004249
Michael Kruse2e02d562016-02-06 09:19:40 +00004250 // An escaping value is either used by an instruction not within the scop,
4251 // or (when the scop region's exit needs to be simplified) by a PHI in the
4252 // scop's exit block. This is because region simplification before code
4253 // generation inserts new basic blocks before the PHI such that its incoming
4254 // blocks are not in the scop anymore.
4255 if (!R->contains(UseParent) ||
4256 (isa<PHINode>(UI) && UserParent == R->getExit() &&
4257 R->getExitingBlock())) {
4258 // At least one escaping use found.
4259 ensureValueWrite(Inst);
4260 break;
Michael Kruse7bf39442015-09-10 12:46:52 +00004261 }
4262 }
Michael Kruse7bf39442015-09-10 12:46:52 +00004263}
4264
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004265bool ScopInfo::buildAccessMultiDimFixed(MemAccInst Inst, Loop *L, Region *R) {
Michael Kruse70131d32016-01-27 17:09:17 +00004266 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004267 Type *ElementType = Val->getType();
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004268 Value *Address = Inst.getPointerOperand();
Tobias Grosser5fd8c092015-09-17 17:28:15 +00004269 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00004270 const SCEVUnknown *BasePointer =
4271 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004272 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004273 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00004274
Michael Kruse37d136e2016-02-26 16:08:24 +00004275 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
4276 auto *Src = BitCast->getOperand(0);
4277 auto *SrcTy = Src->getType();
4278 auto *DstTy = BitCast->getType();
Johannes Doerfert41725a12016-04-08 19:20:03 +00004279 // Do not try to delinearize non-sized (opaque) pointers.
4280 if ((SrcTy->isPointerTy() && !SrcTy->getPointerElementType()->isSized()) ||
4281 (DstTy->isPointerTy() && !DstTy->getPointerElementType()->isSized())) {
4282 return false;
4283 }
Michael Kruse436c9062016-04-08 16:20:08 +00004284 if (SrcTy->isPointerTy() && DstTy->isPointerTy() &&
4285 DL->getTypeAllocSize(SrcTy->getPointerElementType()) ==
4286 DL->getTypeAllocSize(DstTy->getPointerElementType()))
Michael Kruse37d136e2016-02-26 16:08:24 +00004287 Address = Src;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00004288 }
Michael Kruse37d136e2016-02-26 16:08:24 +00004289
4290 auto *GEP = dyn_cast<GetElementPtrInst>(Address);
4291 if (!GEP)
4292 return false;
4293
4294 std::vector<const SCEV *> Subscripts;
4295 std::vector<int> Sizes;
4296 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
4297 auto *BasePtr = GEP->getOperand(0);
4298
Tobias Grosser535afd82016-04-05 06:23:45 +00004299 if (auto *BasePtrCast = dyn_cast<BitCastInst>(BasePtr))
4300 BasePtr = BasePtrCast->getOperand(0);
4301
4302 // Check for identical base pointers to ensure that we do not miss index
4303 // offsets that have been added before this GEP is applied.
4304 if (BasePtr != BasePointer->getValue())
4305 return false;
4306
Michael Kruse37d136e2016-02-26 16:08:24 +00004307 std::vector<const SCEV *> SizesSCEV;
4308
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004309 const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads();
Michael Kruse37d136e2016-02-26 16:08:24 +00004310 for (auto *Subscript : Subscripts) {
4311 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +00004312 if (!isAffineExpr(R, L, Subscript, *SE, &AccessILS))
Michael Kruse37d136e2016-02-26 16:08:24 +00004313 return false;
4314
4315 for (LoadInst *LInst : AccessILS)
4316 if (!ScopRIL.count(LInst))
4317 return false;
4318 }
4319
4320 if (Sizes.empty())
4321 return false;
4322
4323 for (auto V : Sizes)
4324 SizesSCEV.push_back(SE->getSCEV(
4325 ConstantInt::get(IntegerType::getInt64Ty(BasePtr->getContext()), V)));
4326
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004327 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, true,
Michael Kruse37d136e2016-02-26 16:08:24 +00004328 Subscripts, SizesSCEV, Val);
4329 return true;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004330}
4331
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004332bool ScopInfo::buildAccessMultiDimParam(MemAccInst Inst, Loop *L, Region *R) {
Michael Kruse37d136e2016-02-26 16:08:24 +00004333 if (!PollyDelinearize)
4334 return false;
4335
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004336 Value *Address = Inst.getPointerOperand();
4337 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004338 Type *ElementType = Val->getType();
4339 unsigned ElementSize = DL->getTypeAllocSize(ElementType);
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004340 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004341 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004342
4343 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
4344 const SCEVUnknown *BasePointer =
4345 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
4346
4347 assert(BasePointer && "Could not find base pointer");
4348 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00004349
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004350 auto &InsnToMemAcc = scop->getInsnToMemAccMap();
Michael Kruse7bf39442015-09-10 12:46:52 +00004351 auto AccItr = InsnToMemAcc.find(Inst);
Michael Kruse37d136e2016-02-26 16:08:24 +00004352 if (AccItr == InsnToMemAcc.end())
4353 return false;
Tobias Grosser5d51afe2016-02-02 16:46:45 +00004354
Michael Kruse37d136e2016-02-26 16:08:24 +00004355 std::vector<const SCEV *> Sizes(
4356 AccItr->second.Shape->DelinearizedSizes.begin(),
4357 AccItr->second.Shape->DelinearizedSizes.end());
4358 // Remove the element size. This information is already provided by the
4359 // ElementSize parameter. In case the element size of this access and the
4360 // element size used for delinearization differs the delinearization is
4361 // incorrect. Hence, we invalidate the scop.
4362 //
4363 // TODO: Handle delinearization with differing element sizes.
4364 auto DelinearizedSize =
4365 cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue();
4366 Sizes.pop_back();
4367 if (ElementSize != DelinearizedSize)
4368 scop->invalidate(DELINEARIZATION, Inst->getDebugLoc());
4369
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004370 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, true,
Michael Kruse37d136e2016-02-26 16:08:24 +00004371 AccItr->second.DelinearizedSubscripts, Sizes, Val);
4372 return true;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004373}
4374
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004375bool ScopInfo::buildAccessMemIntrinsic(MemAccInst Inst, Loop *L, Region *R) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004376 auto *MemIntr = dyn_cast_or_null<MemIntrinsic>(Inst);
4377
4378 if (MemIntr == nullptr)
Johannes Doerfertcea61932016-02-21 19:13:19 +00004379 return false;
4380
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004381 auto *LengthVal = SE->getSCEVAtScope(MemIntr->getLength(), L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00004382 assert(LengthVal);
4383
Johannes Doerferta7920982016-02-25 14:08:48 +00004384 // Check if the length val is actually affine or if we overapproximate it
4385 InvariantLoadsSetTy AccessILS;
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004386 const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads();
Johannes Doerfertec8a2172016-04-25 13:32:36 +00004387 bool LengthIsAffine = isAffineExpr(R, L, LengthVal, *SE, &AccessILS);
Johannes Doerferta7920982016-02-25 14:08:48 +00004388 for (LoadInst *LInst : AccessILS)
4389 if (!ScopRIL.count(LInst))
4390 LengthIsAffine = false;
4391 if (!LengthIsAffine)
4392 LengthVal = nullptr;
4393
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004394 auto *DestPtrVal = MemIntr->getDest();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004395 assert(DestPtrVal);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004396
Johannes Doerfertcea61932016-02-21 19:13:19 +00004397 auto *DestAccFunc = SE->getSCEVAtScope(DestPtrVal, L);
4398 assert(DestAccFunc);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004399 // Ignore accesses to "NULL".
4400 // TODO: We could use this to optimize the region further, e.g., intersect
4401 // the context with
4402 // isl_set_complement(isl_set_params(getDomain()))
4403 // as we know it would be undefined to execute this instruction anyway.
4404 if (DestAccFunc->isZero())
4405 return true;
4406
Johannes Doerfertcea61932016-02-21 19:13:19 +00004407 auto *DestPtrSCEV = dyn_cast<SCEVUnknown>(SE->getPointerBase(DestAccFunc));
4408 assert(DestPtrSCEV);
4409 DestAccFunc = SE->getMinusSCEV(DestAccFunc, DestPtrSCEV);
4410 addArrayAccess(Inst, MemoryAccess::MUST_WRITE, DestPtrSCEV->getValue(),
4411 IntegerType::getInt8Ty(DestPtrVal->getContext()), false,
4412 {DestAccFunc, LengthVal}, {}, Inst.getValueOperand());
4413
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004414 auto *MemTrans = dyn_cast<MemTransferInst>(MemIntr);
4415 if (!MemTrans)
Johannes Doerfertcea61932016-02-21 19:13:19 +00004416 return true;
4417
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004418 auto *SrcPtrVal = MemTrans->getSource();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004419 assert(SrcPtrVal);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004420
Johannes Doerfertcea61932016-02-21 19:13:19 +00004421 auto *SrcAccFunc = SE->getSCEVAtScope(SrcPtrVal, L);
4422 assert(SrcAccFunc);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004423 // Ignore accesses to "NULL".
4424 // TODO: See above TODO
4425 if (SrcAccFunc->isZero())
4426 return true;
4427
Johannes Doerfertcea61932016-02-21 19:13:19 +00004428 auto *SrcPtrSCEV = dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccFunc));
4429 assert(SrcPtrSCEV);
4430 SrcAccFunc = SE->getMinusSCEV(SrcAccFunc, SrcPtrSCEV);
4431 addArrayAccess(Inst, MemoryAccess::READ, SrcPtrSCEV->getValue(),
4432 IntegerType::getInt8Ty(SrcPtrVal->getContext()), false,
4433 {SrcAccFunc, LengthVal}, {}, Inst.getValueOperand());
4434
4435 return true;
4436}
4437
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004438bool ScopInfo::buildAccessCallInst(MemAccInst Inst, Loop *L, Region *R) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004439 auto *CI = dyn_cast_or_null<CallInst>(Inst);
4440
4441 if (CI == nullptr)
Johannes Doerferta7920982016-02-25 14:08:48 +00004442 return false;
4443
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004444 if (CI->doesNotAccessMemory() || isIgnoredIntrinsic(CI))
Johannes Doerferta7920982016-02-25 14:08:48 +00004445 return true;
4446
4447 bool ReadOnly = false;
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004448 auto *AF = SE->getConstant(IntegerType::getInt64Ty(CI->getContext()), 0);
4449 auto *CalledFunction = CI->getCalledFunction();
Johannes Doerferta7920982016-02-25 14:08:48 +00004450 switch (AA->getModRefBehavior(CalledFunction)) {
4451 case llvm::FMRB_UnknownModRefBehavior:
4452 llvm_unreachable("Unknown mod ref behaviour cannot be represented.");
4453 case llvm::FMRB_DoesNotAccessMemory:
4454 return true;
4455 case llvm::FMRB_OnlyReadsMemory:
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004456 GlobalReads.push_back(CI);
Johannes Doerferta7920982016-02-25 14:08:48 +00004457 return true;
4458 case llvm::FMRB_OnlyReadsArgumentPointees:
4459 ReadOnly = true;
4460 // Fall through
4461 case llvm::FMRB_OnlyAccessesArgumentPointees:
4462 auto AccType = ReadOnly ? MemoryAccess::READ : MemoryAccess::MAY_WRITE;
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004463 for (const auto &Arg : CI->arg_operands()) {
Johannes Doerferta7920982016-02-25 14:08:48 +00004464 if (!Arg->getType()->isPointerTy())
4465 continue;
4466
4467 auto *ArgSCEV = SE->getSCEVAtScope(Arg, L);
4468 if (ArgSCEV->isZero())
4469 continue;
4470
4471 auto *ArgBasePtr = cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
4472 addArrayAccess(Inst, AccType, ArgBasePtr->getValue(),
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004473 ArgBasePtr->getType(), false, {AF}, {}, CI);
Johannes Doerferta7920982016-02-25 14:08:48 +00004474 }
4475 return true;
4476 }
4477
4478 return true;
4479}
4480
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004481void ScopInfo::buildAccessSingleDim(MemAccInst Inst, Loop *L, Region *R) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004482 Value *Address = Inst.getPointerOperand();
4483 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004484 Type *ElementType = Val->getType();
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004485 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004486 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004487
4488 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
4489 const SCEVUnknown *BasePointer =
4490 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
4491
4492 assert(BasePointer && "Could not find base pointer");
4493 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Michael Kruse7bf39442015-09-10 12:46:52 +00004494
4495 // Check if the access depends on a loop contained in a non-affine subregion.
4496 bool isVariantInNonAffineLoop = false;
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004497 SetVector<const Loop *> Loops;
4498 auto &BoxedLoops = scop->getBoxedLoops();
4499 findLoops(AccessFunction, Loops);
4500 for (const Loop *L : Loops)
4501 if (BoxedLoops.count(L))
4502 isVariantInNonAffineLoop = true;
Michael Kruse7bf39442015-09-10 12:46:52 +00004503
Johannes Doerfert09e36972015-10-07 20:17:36 +00004504 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +00004505 bool IsAffine = !isVariantInNonAffineLoop &&
Johannes Doerfertec8a2172016-04-25 13:32:36 +00004506 isAffineExpr(R, L, AccessFunction, *SE, &AccessILS);
Johannes Doerfert09e36972015-10-07 20:17:36 +00004507
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004508 const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads();
Johannes Doerfert09e36972015-10-07 20:17:36 +00004509 for (LoadInst *LInst : AccessILS)
4510 if (!ScopRIL.count(LInst))
4511 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00004512
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004513 if (!IsAffine && AccType == MemoryAccess::MUST_WRITE)
4514 AccType = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00004515
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004516 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, IsAffine,
Tobias Grosser5d51afe2016-02-02 16:46:45 +00004517 {AccessFunction}, {}, Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00004518}
4519
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004520void ScopInfo::buildMemoryAccess(MemAccInst Inst, Loop *L, Region *R) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004521
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004522 if (buildAccessMemIntrinsic(Inst, L, R))
Johannes Doerfertcea61932016-02-21 19:13:19 +00004523 return;
4524
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004525 if (buildAccessCallInst(Inst, L, R))
Johannes Doerferta7920982016-02-25 14:08:48 +00004526 return;
4527
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004528 if (buildAccessMultiDimFixed(Inst, L, R))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004529 return;
4530
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004531 if (buildAccessMultiDimParam(Inst, L, R))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004532 return;
4533
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004534 buildAccessSingleDim(Inst, L, R);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004535}
4536
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004537void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00004538
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004539 if (scop->isNonAffineSubRegion(&SR)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00004540 for (BasicBlock *BB : SR.blocks())
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004541 buildAccessFunctions(R, *BB, &SR);
Michael Kruse7bf39442015-09-10 12:46:52 +00004542 return;
4543 }
4544
4545 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4546 if (I->isSubRegion())
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004547 buildAccessFunctions(R, *I->getNodeAs<Region>());
Michael Kruse7bf39442015-09-10 12:46:52 +00004548 else
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004549 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
Michael Kruse7bf39442015-09-10 12:46:52 +00004550}
4551
Johannes Doerferta8781032016-02-02 14:14:40 +00004552void ScopInfo::buildStmts(Region &R, Region &SR) {
Michael Krusecac948e2015-10-02 13:53:07 +00004553
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004554 if (scop->isNonAffineSubRegion(&SR)) {
Michael Krusecac948e2015-10-02 13:53:07 +00004555 scop->addScopStmt(nullptr, &SR);
4556 return;
4557 }
4558
4559 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4560 if (I->isSubRegion())
Johannes Doerferta8781032016-02-02 14:14:40 +00004561 buildStmts(R, *I->getNodeAs<Region>());
Michael Krusecac948e2015-10-02 13:53:07 +00004562 else
4563 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
4564}
4565
Michael Krused868b5d2015-09-10 15:25:24 +00004566void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
4567 Region *NonAffineSubRegion,
4568 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00004569 // We do not build access functions for error blocks, as they may contain
4570 // instructions we can not model.
Johannes Doerfertc36d39b2016-02-02 14:14:20 +00004571 if (isErrorBlock(BB, R, *LI, *DT) && !IsExitBlock)
Tobias Grosser910cf262015-11-11 20:15:49 +00004572 return;
4573
Michael Kruse7bf39442015-09-10 12:46:52 +00004574 Loop *L = LI->getLoopFor(&BB);
4575
Michael Kruse2e02d562016-02-06 09:19:40 +00004576 for (Instruction &Inst : BB) {
4577 PHINode *PHI = dyn_cast<PHINode>(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004578 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00004579 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00004580
4581 // For the exit block we stop modeling after the last PHI node.
4582 if (!PHI && IsExitBlock)
4583 break;
4584
Michael Kruse70131d32016-01-27 17:09:17 +00004585 if (auto MemInst = MemAccInst::dyn_cast(Inst))
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004586 buildMemoryAccess(MemInst, L, &R);
Michael Kruse7bf39442015-09-10 12:46:52 +00004587
Michael Kruse2e02d562016-02-06 09:19:40 +00004588 if (isIgnoredIntrinsic(&Inst))
Michael Kruse7bf39442015-09-10 12:46:52 +00004589 continue;
4590
Tobias Grosser0904c692016-03-16 23:33:54 +00004591 // PHI nodes have already been modeled above and TerminatorInsts that are
4592 // not part of a non-affine subregion are fully modeled and regenerated
4593 // from the polyhedral domains. Hence, they do not need to be modeled as
4594 // explicit data dependences.
4595 if (!PHI && (!isa<TerminatorInst>(&Inst) || NonAffineSubRegion))
Michael Kruse2e02d562016-02-06 09:19:40 +00004596 buildScalarDependences(&Inst);
Tobias Grosser0904c692016-03-16 23:33:54 +00004597
Michael Kruse2e02d562016-02-06 09:19:40 +00004598 if (!IsExitBlock)
4599 buildEscapingDependences(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004600 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00004601}
Michael Kruse7bf39442015-09-10 12:46:52 +00004602
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004603MemoryAccess *ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004604 MemoryAccess::AccessType AccType,
4605 Value *BaseAddress, Type *ElementType,
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004606 bool Affine, Value *AccessValue,
4607 ArrayRef<const SCEV *> Subscripts,
4608 ArrayRef<const SCEV *> Sizes,
4609 ScopArrayInfo::MemoryKind Kind) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004610 ScopStmt *Stmt = scop->getStmtFor(BB);
Michael Krusecac948e2015-10-02 13:53:07 +00004611
4612 // Do not create a memory access for anything not in the SCoP. It would be
4613 // ignored anyway.
4614 if (!Stmt)
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004615 return nullptr;
Michael Krusecac948e2015-10-02 13:53:07 +00004616
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00004617 AccFuncSetType &AccList = scop->getOrCreateAccessFunctions(BB);
Michael Krusee2bccbb2015-09-18 19:59:43 +00004618 Value *BaseAddr = BaseAddress;
4619 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
4620
Tobias Grosserf4f68702015-12-14 15:05:37 +00004621 bool isKnownMustAccess = false;
4622
4623 // Accesses in single-basic block statements are always excuted.
4624 if (Stmt->isBlockStmt())
4625 isKnownMustAccess = true;
4626
4627 if (Stmt->isRegionStmt()) {
4628 // Accesses that dominate the exit block of a non-affine region are always
4629 // executed. In non-affine regions there may exist MK_Values that do not
4630 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs
4631 // only if there is at most one PHI_WRITE in the non-affine region.
4632 if (DT->dominates(BB, Stmt->getRegion()->getExit()))
4633 isKnownMustAccess = true;
4634 }
4635
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004636 // Non-affine PHI writes do not "happen" at a particular instruction, but
4637 // after exiting the statement. Therefore they are guaranteed execute and
4638 // overwrite the old value.
4639 if (Kind == ScopArrayInfo::MK_PHI || Kind == ScopArrayInfo::MK_ExitPHI)
4640 isKnownMustAccess = true;
4641
Johannes Doerfertcea61932016-02-21 19:13:19 +00004642 if (!isKnownMustAccess && AccType == MemoryAccess::MUST_WRITE)
4643 AccType = MemoryAccess::MAY_WRITE;
Michael Krusecac948e2015-10-02 13:53:07 +00004644
Johannes Doerfertcea61932016-02-21 19:13:19 +00004645 AccList.emplace_back(Stmt, Inst, AccType, BaseAddress, ElementType, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00004646 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00004647 Stmt->addAccess(&AccList.back());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004648 return &AccList.back();
Michael Kruse7bf39442015-09-10 12:46:52 +00004649}
4650
Michael Kruse70131d32016-01-27 17:09:17 +00004651void ScopInfo::addArrayAccess(MemAccInst MemAccInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004652 MemoryAccess::AccessType AccType,
4653 Value *BaseAddress, Type *ElementType,
4654 bool IsAffine, ArrayRef<const SCEV *> Subscripts,
Tobias Grossera535dff2015-12-13 19:59:01 +00004655 ArrayRef<const SCEV *> Sizes,
4656 Value *AccessValue) {
Johannes Doerferta7920982016-02-25 14:08:48 +00004657 ArrayBasePointers.insert(BaseAddress);
Hongbin Zhengf3d66122016-02-26 09:47:11 +00004658 addMemoryAccess(MemAccInst->getParent(), MemAccInst, AccType, BaseAddress,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004659 ElementType, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00004660 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004661}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004662
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004663void ScopInfo::ensureValueWrite(Instruction *Inst) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004664 ScopStmt *Stmt = scop->getStmtFor(Inst);
Michael Kruse436db622016-01-26 13:33:10 +00004665
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004666 // Inst not defined within this SCoP.
Michael Kruse436db622016-01-26 13:33:10 +00004667 if (!Stmt)
4668 return;
4669
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004670 // Do not process further if the instruction is already written.
4671 if (Stmt->lookupValueWriteOf(Inst))
Michael Kruse436db622016-01-26 13:33:10 +00004672 return;
4673
Johannes Doerfertcea61932016-02-21 19:13:19 +00004674 addMemoryAccess(Inst->getParent(), Inst, MemoryAccess::MUST_WRITE, Inst,
4675 Inst->getType(), true, Inst, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004676 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004677}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004678
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004679void ScopInfo::ensureValueRead(Value *V, BasicBlock *UserBB) {
Michael Krusefd463082016-01-27 22:51:56 +00004680
Michael Kruse2e02d562016-02-06 09:19:40 +00004681 // There cannot be an "access" for literal constants. BasicBlock references
4682 // (jump destinations) also never change.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004683 if ((isa<Constant>(V) && !isa<GlobalVariable>(V)) || isa<BasicBlock>(V))
Michael Kruse2e02d562016-02-06 09:19:40 +00004684 return;
4685
Michael Krusefd463082016-01-27 22:51:56 +00004686 // If the instruction can be synthesized and the user is in the region we do
4687 // not need to add a value dependences.
4688 Region &ScopRegion = scop->getRegion();
Michael Krusec7e0d9c2016-03-01 21:44:06 +00004689 auto *Scope = LI->getLoopFor(UserBB);
4690 if (canSynthesize(V, LI, SE, &ScopRegion, Scope))
Michael Krusefd463082016-01-27 22:51:56 +00004691 return;
4692
Michael Kruse2e02d562016-02-06 09:19:40 +00004693 // Do not build scalar dependences for required invariant loads as we will
4694 // hoist them later on anyway or drop the SCoP if we cannot.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004695 auto &ScopRIL = scop->getRequiredInvariantLoads();
4696 if (ScopRIL.count(dyn_cast<LoadInst>(V)))
Michael Kruse2e02d562016-02-06 09:19:40 +00004697 return;
4698
4699 // Determine the ScopStmt containing the value's definition and use. There is
4700 // no defining ScopStmt if the value is a function argument, a global value,
4701 // or defined outside the SCoP.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004702 Instruction *ValueInst = dyn_cast<Instruction>(V);
Michael Kruse6f7721f2016-02-24 22:08:19 +00004703 ScopStmt *ValueStmt = ValueInst ? scop->getStmtFor(ValueInst) : nullptr;
Michael Kruse2e02d562016-02-06 09:19:40 +00004704
Michael Kruse6f7721f2016-02-24 22:08:19 +00004705 ScopStmt *UserStmt = scop->getStmtFor(UserBB);
Michael Krusead28e5a2016-01-26 13:33:15 +00004706
4707 // We do not model uses outside the scop.
4708 if (!UserStmt)
4709 return;
4710
Michael Kruse2e02d562016-02-06 09:19:40 +00004711 // Add MemoryAccess for invariant values only if requested.
4712 if (!ModelReadOnlyScalars && !ValueStmt)
4713 return;
4714
4715 // Ignore use-def chains within the same ScopStmt.
4716 if (ValueStmt == UserStmt)
4717 return;
4718
Michael Krusead28e5a2016-01-26 13:33:15 +00004719 // Do not create another MemoryAccess for reloading the value if one already
4720 // exists.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004721 if (UserStmt->lookupValueReadOf(V))
Michael Krusead28e5a2016-01-26 13:33:15 +00004722 return;
4723
Johannes Doerfert2075b5d2016-04-03 11:16:00 +00004724 // For exit PHIs use the MK_ExitPHI MemoryKind not MK_Value.
4725 ScopArrayInfo::MemoryKind Kind = ScopArrayInfo::MK_Value;
4726 if (!ValueStmt && isa<PHINode>(V))
4727 Kind = ScopArrayInfo::MK_ExitPHI;
4728
Johannes Doerfertcea61932016-02-21 19:13:19 +00004729 addMemoryAccess(UserBB, nullptr, MemoryAccess::READ, V, V->getType(), true, V,
Johannes Doerfert2075b5d2016-04-03 11:16:00 +00004730 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(), Kind);
Michael Kruse2e02d562016-02-06 09:19:40 +00004731 if (ValueInst)
4732 ensureValueWrite(ValueInst);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004733}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004734
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004735void ScopInfo::ensurePHIWrite(PHINode *PHI, BasicBlock *IncomingBlock,
4736 Value *IncomingValue, bool IsExitBlock) {
Johannes Doerfert57c5f0b2016-04-05 13:44:21 +00004737 // As the incoming block might turn out to be an error statement ensure we
4738 // will create an exit PHI SAI object. It is needed during code generation
4739 // and would be created later anyway.
4740 if (IsExitBlock)
4741 scop->getOrCreateScopArrayInfo(PHI, PHI->getType(), {},
4742 ScopArrayInfo::MK_ExitPHI);
4743
Michael Kruse6f7721f2016-02-24 22:08:19 +00004744 ScopStmt *IncomingStmt = scop->getStmtFor(IncomingBlock);
Michael Kruse2e02d562016-02-06 09:19:40 +00004745 if (!IncomingStmt)
4746 return;
4747
4748 // Take care for the incoming value being available in the incoming block.
4749 // This must be done before the check for multiple PHI writes because multiple
4750 // exiting edges from subregion each can be the effective written value of the
4751 // subregion. As such, all of them must be made available in the subregion
4752 // statement.
4753 ensureValueRead(IncomingValue, IncomingBlock);
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004754
4755 // Do not add more than one MemoryAccess per PHINode and ScopStmt.
4756 if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) {
4757 assert(Acc->getAccessInstruction() == PHI);
4758 Acc->addIncoming(IncomingBlock, IncomingValue);
4759 return;
4760 }
4761
4762 MemoryAccess *Acc = addMemoryAccess(
Michael Kruse375cb5f2016-02-24 22:08:24 +00004763 IncomingStmt->getEntryBlock(), PHI, MemoryAccess::MUST_WRITE, PHI,
4764 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4765 ArrayRef<const SCEV *>(),
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004766 IsExitBlock ? ScopArrayInfo::MK_ExitPHI : ScopArrayInfo::MK_PHI);
4767 assert(Acc);
4768 Acc->addIncoming(IncomingBlock, IncomingValue);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004769}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004770
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004771void ScopInfo::addPHIReadAccess(PHINode *PHI) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00004772 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI,
4773 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4774 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004775}
4776
Michael Krusedaf66942015-12-13 22:10:37 +00004777void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004778 scop.reset(new Scop(R, *SE, *LI, *SD->getDetectionContext(&R)));
Michael Kruse7bf39442015-09-10 12:46:52 +00004779
Johannes Doerferta8781032016-02-02 14:14:40 +00004780 buildStmts(R, R);
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004781 buildAccessFunctions(R, R);
Michael Kruse7bf39442015-09-10 12:46:52 +00004782
4783 // In case the region does not have an exiting block we will later (during
4784 // code generation) split the exit block. This will move potential PHI nodes
4785 // from the current exit block into the new region exiting block. Hence, PHI
4786 // nodes that are at this point not part of the region will be.
4787 // To handle these PHI nodes later we will now model their operands as scalar
4788 // accesses. Note that we do not model anything in the exit block if we have
4789 // an exiting block in the region, as there will not be any splitting later.
4790 if (!R.getExitingBlock())
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004791 buildAccessFunctions(R, *R.getExit(), nullptr,
Hongbin Zheng22623202016-02-15 00:20:58 +00004792 /* IsExitBlock */ true);
Michael Kruse7bf39442015-09-10 12:46:52 +00004793
Johannes Doerferta7920982016-02-25 14:08:48 +00004794 // Create memory accesses for global reads since all arrays are now known.
4795 auto *AF = SE->getConstant(IntegerType::getInt64Ty(SE->getContext()), 0);
4796 for (auto *GlobalRead : GlobalReads)
4797 for (auto *BP : ArrayBasePointers)
4798 addArrayAccess(MemAccInst(GlobalRead), MemoryAccess::READ, BP,
4799 BP->getType(), false, {AF}, {}, GlobalRead);
4800
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004801 scop->init(*AA, AC, *DT, *LI);
Michael Kruse7bf39442015-09-10 12:46:52 +00004802}
4803
Michael Krused868b5d2015-09-10 15:25:24 +00004804void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00004805 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00004806 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00004807 return;
4808 }
4809
Michael Kruse9d080092015-09-11 21:41:48 +00004810 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00004811}
4812
Hongbin Zhengfec32802016-02-13 15:13:02 +00004813void ScopInfo::clear() { scop.reset(); }
Michael Kruse7bf39442015-09-10 12:46:52 +00004814
4815//===----------------------------------------------------------------------===//
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004816ScopInfo::ScopInfo() : RegionPass(ID) {}
Tobias Grosserb76f38532011-08-20 11:11:25 +00004817
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004818ScopInfo::~ScopInfo() { clear(); }
Tobias Grosserb76f38532011-08-20 11:11:25 +00004819
Tobias Grosser75805372011-04-29 06:27:02 +00004820void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00004821 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00004822 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00004823 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00004824 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4825 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004826 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004827 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00004828 AU.setPreservesAll();
4829}
4830
4831bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004832 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004833
Michael Krused868b5d2015-09-10 15:25:24 +00004834 if (!SD->isMaxRegionInScop(*R))
4835 return false;
4836
4837 Function *F = R->getEntry()->getParent();
4838 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4839 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4840 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Johannes Doerferta1f291e2016-02-02 14:15:13 +00004841 DL = &F->getParent()->getDataLayout();
Michael Krusedaf66942015-12-13 22:10:37 +00004842 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004843 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004844
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004845 DebugLoc Beg, End;
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00004846 getDebugLocations(getBBPairForRegion(R), Beg, End);
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004847 std::string Msg = "SCoP begins here.";
4848 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4849
Michael Krusedaf66942015-12-13 22:10:37 +00004850 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004851
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004852 DEBUG(scop->print(dbgs()));
4853
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004854 if (!scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004855 Msg = "SCoP ends here but was dismissed.";
Hongbin Zhengfec32802016-02-13 15:13:02 +00004856 scop.reset();
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004857 } else {
4858 Msg = "SCoP ends here.";
4859 ++ScopFound;
4860 if (scop->getMaxLoopDepth() > 0)
4861 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004862 }
4863
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004864 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4865
Tobias Grosser75805372011-04-29 06:27:02 +00004866 return false;
4867}
4868
4869char ScopInfo::ID = 0;
4870
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004871Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4872
Tobias Grosser73600b82011-10-08 00:30:40 +00004873INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4874 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004875 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004876INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004877INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004878INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004879INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004880INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004881INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004882INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004883INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4884 "Polly - Create polyhedral description of Scops", false,
4885 false)