blob: f2ebce88dc669435d8e15b19580f8b7635baaf9c [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"
Tobias Grosserba0d0922015-05-09 09:13:42 +000035#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000036#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000037#include "llvm/Analysis/RegionIterator.h"
38#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000039#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000040#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000041#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000042#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000043#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000045#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000047#include "isl/schedule.h"
48#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000049#include "isl/set.h"
50#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000051#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000052#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000053#include <sstream>
54#include <string>
55#include <vector>
56
57using namespace llvm;
58using namespace polly;
59
Chandler Carruth95fef942014-04-22 03:30:19 +000060#define DEBUG_TYPE "polly-scops"
61
Tobias Grosser74394f02013-01-14 22:40:23 +000062STATISTIC(ScopFound, "Number of valid Scops");
63STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000064
Tobias Grosser75dc40c2015-12-20 13:31:48 +000065// The maximal number of basic sets we allow during domain construction to
66// be created. More complex scops will result in very high compile time and
67// are also unlikely to result in good code
68static int const MaxConjunctsInDomain = 20;
69
Johannes Doerfert2f705842016-04-12 16:09:44 +000070static cl::opt<bool> PollyRemarksMinimal(
71 "polly-remarks-minimal",
72 cl::desc("Do not emit remarks about assumptions that are known"),
73 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
74
Michael Kruse7bf39442015-09-10 12:46:52 +000075static cl::opt<bool> ModelReadOnlyScalars(
76 "polly-analyze-read-only-scalars",
77 cl::desc("Model read-only scalar values in the scop description"),
78 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
79
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000080// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000081// operations can overflow easily. Additive reductions and bit operations
82// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000083static cl::opt<bool> DisableMultiplicativeReductions(
84 "polly-disable-multiplicative-reductions",
85 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
86 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000087
Johannes Doerfert9143d672014-09-27 11:02:39 +000088static cl::opt<unsigned> RunTimeChecksMaxParameters(
89 "polly-rtc-max-parameters",
90 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
91 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
92
Tobias Grosser71500722015-03-28 15:11:14 +000093static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
94 "polly-rtc-max-arrays-per-group",
95 cl::desc("The maximal number of arrays to compare in each alias group."),
96 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000097static cl::opt<std::string> UserContextStr(
98 "polly-context", cl::value_desc("isl parameter set"),
99 cl::desc("Provide additional constraints on the context parameters"),
100 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000101
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000102static cl::opt<bool> DetectReductions("polly-detect-reductions",
103 cl::desc("Detect and exploit reductions"),
104 cl::Hidden, cl::ZeroOrMore,
105 cl::init(true), cl::cat(PollyCategory));
106
Michael Kruse7bf39442015-09-10 12:46:52 +0000107//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000108
Michael Kruse046dde42015-08-10 13:01:57 +0000109// Create a sequence of two schedules. Either argument may be null and is
110// interpreted as the empty schedule. Can also return null if both schedules are
111// empty.
112static __isl_give isl_schedule *
113combineInSequence(__isl_take isl_schedule *Prev,
114 __isl_take isl_schedule *Succ) {
115 if (!Prev)
116 return Succ;
117 if (!Succ)
118 return Prev;
119
120 return isl_schedule_sequence(Prev, Succ);
121}
122
Johannes Doerferte7044942015-02-24 11:58:30 +0000123static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
124 const ConstantRange &Range,
125 int dim,
126 enum isl_dim_type type) {
127 isl_val *V;
128 isl_ctx *ctx = isl_set_get_ctx(S);
129
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000130 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
131 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000132 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000133 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
134
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000135 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000136 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000137 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000138 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000139 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
140
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000141 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000142 return isl_set_union(SLB, SUB);
143 else
144 return isl_set_intersect(SLB, SUB);
145}
146
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000147static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
148 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
149 if (!BasePtrLI)
150 return nullptr;
151
152 if (!S->getRegion().contains(BasePtrLI))
153 return nullptr;
154
155 ScalarEvolution &SE = *S->getSE();
156
157 auto *OriginBaseSCEV =
158 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
159 if (!OriginBaseSCEV)
160 return nullptr;
161
162 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
163 if (!OriginBaseSCEVUnknown)
164 return nullptr;
165
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000166 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000167 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000168}
169
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000170ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000171 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000172 const DataLayout &DL, Scop *S)
173 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000174 std::string BasePtrName =
Tobias Grossera535dff2015-12-13 19:59:01 +0000175 getIslCompatibleName("MemRef_", BasePtr, Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000176 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000177
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000178 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000179 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
180 if (BasePtrOriginSAI)
181 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000182}
183
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000184__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000185 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000186 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
187 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
188 return Space;
189}
190
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000191void ScopArrayInfo::updateElementType(Type *NewElementType) {
192 if (NewElementType == ElementType)
193 return;
194
Tobias Grosserd840fc72016-02-04 13:18:42 +0000195 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
196 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
197
Johannes Doerferta7920982016-02-25 14:08:48 +0000198 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000199 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000200
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000201 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
202 ElementType = NewElementType;
203 } else {
204 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
205 ElementType = IntegerType::get(ElementType->getContext(), GCD);
206 }
207}
208
209bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000210 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
211 int ExtraDimsNew = NewSizes.size() - SharedDims;
212 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000213 for (int i = 0; i < SharedDims; i++)
214 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
215 return false;
216
217 if (DimensionSizes.size() >= NewSizes.size())
218 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000219
220 DimensionSizes.clear();
221 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
222 NewSizes.end());
223 for (isl_pw_aff *Size : DimensionSizesPw)
224 isl_pw_aff_free(Size);
225 DimensionSizesPw.clear();
226 for (const SCEV *Expr : DimensionSizes) {
227 isl_pw_aff *Size = S.getPwAff(Expr);
228 DimensionSizesPw.push_back(Size);
229 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000230 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000231}
232
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000233ScopArrayInfo::~ScopArrayInfo() {
234 isl_id_free(Id);
235 for (isl_pw_aff *Size : DimensionSizesPw)
236 isl_pw_aff_free(Size);
237}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000238
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000239std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
240
241int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000242 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000243}
244
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000245__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
246 return isl_id_copy(Id);
247}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000248
249void ScopArrayInfo::dump() const { print(errs()); }
250
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000251void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000252 OS.indent(8) << *getElementType() << " " << getName();
253 if (getNumberOfDimensions() > 0)
254 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000255 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000256 OS << "[";
257
Tobias Grosser26253842015-11-10 14:24:21 +0000258 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000259 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000260 OS << " " << Size << " ";
261 isl_pw_aff_free(Size);
262 } else {
263 OS << *getDimensionSize(u);
264 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000265
266 OS << "]";
267 }
268
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000269 OS << ";";
270
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000271 if (BasePtrOriginSAI)
272 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
273
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000274 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000275}
276
277const ScopArrayInfo *
278ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
279 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
280 assert(Id && "Output dimension didn't have an ID");
281 return getFromId(Id);
282}
283
284const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
285 void *User = isl_id_get_user(Id);
286 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
287 isl_id_free(Id);
288 return SAI;
289}
290
Michael Kruse3b425ff2016-04-11 14:34:08 +0000291void MemoryAccess::wrapConstantDimensions() {
292 auto *SAI = getScopArrayInfo();
293 auto *ArraySpace = SAI->getSpace();
294 auto *Ctx = isl_space_get_ctx(ArraySpace);
295 unsigned DimsArray = SAI->getNumberOfDimensions();
296
297 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
298 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
299 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
300
301 // Begin with last dimension, to iteratively carry into higher dimensions.
302 for (int i = DimsArray - 1; i > 0; i--) {
303 auto *DimSize = SAI->getDimensionSize(i);
304 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
305
306 // This transformation is not applicable to dimensions with dynamic size.
307 if (!DimSizeCst)
308 continue;
309
310 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
311 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
312 isl_dim_set, i);
313 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
314 isl_dim_set, i - 1);
315
316 // Compute: index % size
317 // Modulo must apply in the divide of the previous iteration, if any.
318 auto *Modulo = isl_aff_copy(Var);
319 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
320 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
321
322 // Compute: floor(index / size)
323 auto *Divide = Var;
324 Divide = isl_aff_div(
325 Divide,
326 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
327 Divide = isl_aff_floor(Divide);
328 Divide = isl_aff_add(Divide, PrevVar);
329 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
330
331 // Apply Modulo and Divide.
332 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
333 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
334 }
335
336 // Apply all modulo/divides on the accesses.
337 AccessRelation =
338 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
339 AccessRelation = isl_map_detect_equalities(AccessRelation);
340 isl_local_space_free(LArraySpace);
341}
342
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000343void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000344 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000345 auto *ArraySpace = SAI->getSpace();
346 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000347 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000348
349 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
350 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
351 auto DimsMissing = DimsArray - DimsAccess;
352
Michael Kruse375cb5f2016-02-24 22:08:24 +0000353 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000354 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000355 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000356 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000357
Johannes Doerferta90943d2016-02-21 16:37:25 +0000358 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000359 isl_set_universe(AccessSpace),
360 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000361
362 for (unsigned i = 0; i < DimsMissing; i++)
363 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
364
365 for (unsigned i = DimsMissing; i < DimsArray; i++)
366 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
367
368 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000369
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000370 // For the non delinearized arrays, divide the access function of the last
371 // subscript by the size of the elements in the array.
372 //
373 // A stride one array access in C expressed as A[i] is expressed in
374 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
375 // two subsequent values of 'i' index two values that are stored next to
376 // each other in memory. By this division we make this characteristic
377 // obvious again. If the base pointer was accessed with offsets not divisible
378 // by the accesses element size, we will have choosen a smaller ArrayElemSize
379 // that divides the offsets of all accesses to this base pointer.
380 if (DimsAccess == 1) {
381 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
382 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
383 }
384
Michael Kruse3b425ff2016-04-11 14:34:08 +0000385 // We currently do this only if we added at least one dimension, which means
386 // some dimension's indices have not been specified, an indicator that some
387 // index values have been added together.
388 // TODO: Investigate general usefulness; Effect on unit tests is to make index
389 // expressions more complicated.
390 if (DimsMissing)
391 wrapConstantDimensions();
392
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000393 if (!isAffine())
394 computeBoundsOnAccessRelation(ArrayElemSize);
395
Tobias Grosserd840fc72016-02-04 13:18:42 +0000396 // Introduce multi-element accesses in case the type loaded by this memory
397 // access is larger than the canonical element type of the array.
398 //
399 // An access ((float *)A)[i] to an array char *A is modeled as
400 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000401 if (ElemBytes > ArrayElemSize) {
402 assert(ElemBytes % ArrayElemSize == 0 &&
403 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000404 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000405 isl_set_universe(isl_space_copy(ArraySpace)),
406 isl_set_universe(isl_space_copy(ArraySpace)));
407 for (unsigned i = 0; i < DimsArray - 1; i++)
408 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
409
Tobias Grosserd840fc72016-02-04 13:18:42 +0000410 isl_constraint *C;
411 isl_local_space *LS;
412
413 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000414 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
415
416 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
417 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000418 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000419 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
420 Map = isl_map_add_constraint(Map, C);
421
422 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000423 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000424 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
425 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
426 Map = isl_map_add_constraint(Map, C);
427 AccessRelation = isl_map_apply_range(AccessRelation, Map);
428 }
429
430 isl_space_free(ArraySpace);
431
Roman Gareev10595a12016-01-08 14:01:59 +0000432 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000433}
434
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000435const std::string
436MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
437 switch (RT) {
438 case MemoryAccess::RT_NONE:
439 llvm_unreachable("Requested a reduction operator string for a memory "
440 "access which isn't a reduction");
441 case MemoryAccess::RT_ADD:
442 return "+";
443 case MemoryAccess::RT_MUL:
444 return "*";
445 case MemoryAccess::RT_BOR:
446 return "|";
447 case MemoryAccess::RT_BXOR:
448 return "^";
449 case MemoryAccess::RT_BAND:
450 return "&";
451 }
452 llvm_unreachable("Unknown reduction type");
453 return "";
454}
455
Johannes Doerfertf6183392014-07-01 20:52:51 +0000456/// @brief Return the reduction type for a given binary operator
457static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
458 const Instruction *Load) {
459 if (!BinOp)
460 return MemoryAccess::RT_NONE;
461 switch (BinOp->getOpcode()) {
462 case Instruction::FAdd:
463 if (!BinOp->hasUnsafeAlgebra())
464 return MemoryAccess::RT_NONE;
465 // Fall through
466 case Instruction::Add:
467 return MemoryAccess::RT_ADD;
468 case Instruction::Or:
469 return MemoryAccess::RT_BOR;
470 case Instruction::Xor:
471 return MemoryAccess::RT_BXOR;
472 case Instruction::And:
473 return MemoryAccess::RT_BAND;
474 case Instruction::FMul:
475 if (!BinOp->hasUnsafeAlgebra())
476 return MemoryAccess::RT_NONE;
477 // Fall through
478 case Instruction::Mul:
479 if (DisableMultiplicativeReductions)
480 return MemoryAccess::RT_NONE;
481 return MemoryAccess::RT_MUL;
482 default:
483 return MemoryAccess::RT_NONE;
484 }
485}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000486
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000487/// @brief Derive the individual index expressions from a GEP instruction
488///
489/// This function optimistically assumes the GEP references into a fixed size
490/// array. If this is actually true, this function returns a list of array
491/// subscript expressions as SCEV as well as a list of integers describing
492/// the size of the individual array dimensions. Both lists have either equal
493/// length of the size list is one element shorter in case there is no known
494/// size available for the outermost array dimension.
495///
496/// @param GEP The GetElementPtr instruction to analyze.
497///
498/// @return A tuple with the subscript expressions and the dimension sizes.
499static std::tuple<std::vector<const SCEV *>, std::vector<int>>
500getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
501 std::vector<const SCEV *> Subscripts;
502 std::vector<int> Sizes;
503
504 Type *Ty = GEP->getPointerOperandType();
505
506 bool DroppedFirstDim = false;
507
Michael Kruse26ed65e2015-09-24 17:32:49 +0000508 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000509
510 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
511
512 if (i == 1) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000513 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000514 Ty = PtrTy->getElementType();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000515 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000516 Ty = ArrayTy->getElementType();
517 } else {
518 Subscripts.clear();
519 Sizes.clear();
520 break;
521 }
Johannes Doerferta90943d2016-02-21 16:37:25 +0000522 if (auto *Const = dyn_cast<SCEVConstant>(Expr))
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000523 if (Const->getValue()->isZero()) {
524 DroppedFirstDim = true;
525 continue;
526 }
527 Subscripts.push_back(Expr);
528 continue;
529 }
530
Johannes Doerferta90943d2016-02-21 16:37:25 +0000531 auto *ArrayTy = dyn_cast<ArrayType>(Ty);
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000532 if (!ArrayTy) {
533 Subscripts.clear();
534 Sizes.clear();
535 break;
536 }
537
538 Subscripts.push_back(Expr);
539 if (!(DroppedFirstDim && i == 2))
540 Sizes.push_back(ArrayTy->getNumElements());
541
542 Ty = ArrayTy->getElementType();
543 }
544
545 return std::make_tuple(Subscripts, Sizes);
546}
547
Tobias Grosser75805372011-04-29 06:27:02 +0000548MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000549 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000550 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000551 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000552}
553
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000554const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
555 isl_id *ArrayId = getArrayId();
556 void *User = isl_id_get_user(ArrayId);
557 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
558 isl_id_free(ArrayId);
559 return SAI;
560}
561
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000562__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000563 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
564}
565
Tobias Grosserd840fc72016-02-04 13:18:42 +0000566__isl_give isl_map *MemoryAccess::getAddressFunction() const {
567 return isl_map_lexmin(getAccessRelation());
568}
569
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000570__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
571 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000572 isl_map *Schedule, *ScheduledAccRel;
573 isl_union_set *UDomain;
574
575 UDomain = isl_union_set_from_set(getStatement()->getDomain());
576 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
577 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000578 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000579 return isl_pw_multi_aff_from_map(ScheduledAccRel);
580}
581
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000582__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000583 return isl_map_copy(AccessRelation);
584}
585
Johannes Doerferta99130f2014-10-13 12:58:03 +0000586std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000587 return stringFromIslObj(AccessRelation);
588}
589
Johannes Doerferta99130f2014-10-13 12:58:03 +0000590__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000591 return isl_map_get_space(AccessRelation);
592}
593
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000594__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000595 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000596}
597
Tobias Grosser6f730082015-09-05 07:46:47 +0000598std::string MemoryAccess::getNewAccessRelationStr() const {
599 return stringFromIslObj(NewAccessRelation);
600}
601
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000602__isl_give isl_basic_map *
603MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000604 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000605 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000606
Tobias Grosser084d8f72012-05-29 09:29:44 +0000607 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000608 isl_basic_set_universe(Statement->getDomainSpace()),
609 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000610}
611
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000612// Formalize no out-of-bound access assumption
613//
614// When delinearizing array accesses we optimistically assume that the
615// delinearized accesses do not access out of bound locations (the subscript
616// expression of each array evaluates for each statement instance that is
617// executed to a value that is larger than zero and strictly smaller than the
618// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000619// dimension for which we do not need to assume any upper bound. At this point
620// we formalize this assumption to ensure that at code generation time the
621// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000622//
623// To find the set of constraints necessary to avoid out of bound accesses, we
624// first build the set of data locations that are not within array bounds. We
625// then apply the reverse access relation to obtain the set of iterations that
626// may contain invalid accesses and reduce this set of iterations to the ones
627// that are actually executed by intersecting them with the domain of the
628// statement. If we now project out all loop dimensions, we obtain a set of
629// parameters that may cause statement instances to be executed that may
630// possibly yield out of bound memory accesses. The complement of these
631// constraints is the set of constraints that needs to be assumed to ensure such
632// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000633void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000634 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000635 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000636 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000637 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000638 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
639 isl_pw_aff *Var =
640 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
641 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
642
643 isl_set *DimOutside;
644
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000645 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000646 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000647 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
648 isl_space_dim(Space, isl_dim_set));
649 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
650 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000651
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000652 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000653
654 Outside = isl_set_union(Outside, DimOutside);
655 }
656
657 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
658 Outside = isl_set_intersect(Outside, Statement->getDomain());
659 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000660
661 // Remove divs to avoid the construction of overly complicated assumptions.
662 // Doing so increases the set of parameter combinations that are assumed to
663 // not appear. This is always save, but may make the resulting run-time check
664 // bail out more often than strictly necessary.
665 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000666 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000667 const auto &Loc = getAccessInstruction()
668 ? getAccessInstruction()->getDebugLoc()
669 : DebugLoc();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000670 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
671 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000672 isl_space_free(Space);
673}
674
Johannes Doerfertcea61932016-02-21 19:13:19 +0000675void MemoryAccess::buildMemIntrinsicAccessRelation() {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000676 assert(isa<MemIntrinsic>(getAccessInstruction()));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000677 assert(Subscripts.size() == 2 && Sizes.size() == 0);
678
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000679 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000680 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000681
682 isl_map *LengthMap;
683 if (Subscripts[1] == nullptr) {
684 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
685 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000686 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000687 LengthMap = isl_map_from_pw_aff(LengthPWA);
688 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
689 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
690 }
691 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
692 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000693 SubscriptMap =
694 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000695 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
696 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
697 getStatement()->getDomainId());
698}
699
Johannes Doerferte7044942015-02-24 11:58:30 +0000700void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
701 ScalarEvolution *SE = Statement->getParent()->getSE();
702
Johannes Doerfertcea61932016-02-21 19:13:19 +0000703 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000704 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000705 return;
706
707 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000708 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
709 return;
710
711 auto *PtrSCEV = SE->getSCEV(Ptr);
712 if (isa<SCEVCouldNotCompute>(PtrSCEV))
713 return;
714
715 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
716 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
717 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
718
719 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
720 if (Range.isFullSet())
721 return;
722
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000723 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000724 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000725 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000726 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000727 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000728
729 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000730 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000731
732 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
733 AccessRange =
734 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
735 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
736}
737
Michael Krusee2bccbb2015-09-18 19:59:43 +0000738__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000739 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000740 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000741
742 for (int i = Size - 2; i >= 0; --i) {
743 isl_space *Space;
744 isl_map *MapOne, *MapTwo;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000745 isl_pw_aff *DimSize = getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000746
747 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
748 isl_pw_aff_free(DimSize);
749 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
750
751 Space = isl_map_get_space(AccessRelation);
752 Space = isl_space_map_from_set(isl_space_range(Space));
753 Space = isl_space_align_params(Space, SpaceSize);
754
755 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
756 isl_id_free(ParamId);
757
758 MapOne = isl_map_universe(isl_space_copy(Space));
759 for (int j = 0; j < Size; ++j)
760 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
761 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
762
763 MapTwo = isl_map_universe(isl_space_copy(Space));
764 for (int j = 0; j < Size; ++j)
765 if (j < i || j > i + 1)
766 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
767
768 isl_local_space *LS = isl_local_space_from_space(Space);
769 isl_constraint *C;
770 C = isl_equality_alloc(isl_local_space_copy(LS));
771 C = isl_constraint_set_constant_si(C, -1);
772 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
773 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
774 MapTwo = isl_map_add_constraint(MapTwo, C);
775 C = isl_equality_alloc(LS);
776 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
777 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
778 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
779 MapTwo = isl_map_add_constraint(MapTwo, C);
780 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
781
782 MapOne = isl_map_union(MapOne, MapTwo);
783 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
784 }
785 return AccessRelation;
786}
787
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000788/// @brief Check if @p Expr is divisible by @p Size.
789static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000790 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000791 if (Size == 1)
792 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000793
794 // Only one factor needs to be divisible.
795 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
796 for (auto *FactorExpr : MulExpr->operands())
797 if (isDivisible(FactorExpr, Size, SE))
798 return true;
799 return false;
800 }
801
802 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
803 // to be divisble.
804 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
805 for (auto *OpExpr : NAryExpr->operands())
806 if (!isDivisible(OpExpr, Size, SE))
807 return false;
808 return true;
809 }
810
811 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
812 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
813 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
814 return MulSCEV == Expr;
815}
816
Michael Krusee2bccbb2015-09-18 19:59:43 +0000817void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
818 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000819
Michael Krusee2bccbb2015-09-18 19:59:43 +0000820 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000821 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000822
Michael Krusee2bccbb2015-09-18 19:59:43 +0000823 if (!isAffine()) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000824 if (isa<MemIntrinsic>(getAccessInstruction()))
825 buildMemIntrinsicAccessRelation();
826
Tobias Grosser4f967492013-06-23 05:21:18 +0000827 // We overapproximate non-affine accesses with a possible access to the
828 // whole array. For read accesses it does not make a difference, if an
829 // access must or may happen. However, for write accesses it is important to
830 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000831 if (!AccessRelation)
832 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
833
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000834 AccessRelation =
835 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000836 return;
837 }
838
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000839 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000840 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000841
Michael Krusee2bccbb2015-09-18 19:59:43 +0000842 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000843 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000844 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000845 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000846 }
847
Tobias Grosser5d51afe2016-02-02 16:46:45 +0000848 if (Sizes.size() >= 1 && !isa<SCEVConstant>(Sizes[0]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000849 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000850
Tobias Grosser79baa212014-04-10 08:38:02 +0000851 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000852 AccessRelation = isl_map_set_tuple_id(
853 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000854 AccessRelation =
855 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
856
Tobias Grosseraa660a92015-03-30 00:07:50 +0000857 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000858 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000859}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000860
Michael Krusecac948e2015-10-02 13:53:07 +0000861MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000862 AccessType AccType, Value *BaseAddress,
863 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000864 ArrayRef<const SCEV *> Subscripts,
865 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000866 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000867 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
868 BaseAddr(BaseAddress), BaseName(BaseName), ElementType(ElementType),
Michael Krusecac948e2015-10-02 13:53:07 +0000869 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
870 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000871 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000872 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000873 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000874 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000875
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000876 std::string IdName =
877 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000878 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
879}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000880
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000881void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000882 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000883 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000884}
885
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000886const std::string MemoryAccess::getReductionOperatorStr() const {
887 return MemoryAccess::getReductionOperatorStr(getReductionType());
888}
889
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000890__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
891
Johannes Doerfertf6183392014-07-01 20:52:51 +0000892raw_ostream &polly::operator<<(raw_ostream &OS,
893 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000894 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000895 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000896 else
897 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000898 return OS;
899}
900
Tobias Grosser75805372011-04-29 06:27:02 +0000901void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000902 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000903 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000904 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000905 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000906 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000907 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000908 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000909 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000910 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000911 break;
912 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000913 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000914 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000915 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000916 if (hasNewAccessRelation())
917 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000918}
919
Tobias Grosser74394f02013-01-14 22:40:23 +0000920void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000921
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000922__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
923 auto *Stmt = getStatement();
924 return Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
925}
926
Tobias Grosser75805372011-04-29 06:27:02 +0000927// Create a map in the size of the provided set domain, that maps from the
928// one element of the provided set domain to another element of the provided
929// set domain.
930// The mapping is limited to all points that are equal in all but the last
931// dimension and for which the last dimension of the input is strict smaller
932// than the last dimension of the output.
933//
934// getEqualAndLarger(set[i0, i1, ..., iX]):
935//
936// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
937// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
938//
Tobias Grosserf5338802011-10-06 00:03:35 +0000939static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000940 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000941 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000942 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000943
944 // Set all but the last dimension to be equal for the input and output
945 //
946 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
947 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000948 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000949 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000950
951 // Set the last dimension of the input to be strict smaller than the
952 // last dimension of the output.
953 //
954 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000955 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
956 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000957 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000958}
959
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000960__isl_give isl_set *
961MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000962 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000963 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000964 isl_space *Space = isl_space_range(isl_map_get_space(S));
965 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000966
Sebastian Popa00a0292012-12-18 07:46:06 +0000967 S = isl_map_reverse(S);
968 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000969
Sebastian Popa00a0292012-12-18 07:46:06 +0000970 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
971 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
972 NextScatt = isl_map_apply_domain(NextScatt, S);
973 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000974
Sebastian Popa00a0292012-12-18 07:46:06 +0000975 isl_set *Deltas = isl_map_deltas(NextScatt);
976 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000977}
978
Sebastian Popa00a0292012-12-18 07:46:06 +0000979bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000980 int StrideWidth) const {
981 isl_set *Stride, *StrideX;
982 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000983
Sebastian Popa00a0292012-12-18 07:46:06 +0000984 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000985 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000986 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
987 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
988 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
989 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000990 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000991
Tobias Grosser28dd4862012-01-24 16:42:16 +0000992 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000993 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000994
Tobias Grosser28dd4862012-01-24 16:42:16 +0000995 return IsStrideX;
996}
997
Sebastian Popa00a0292012-12-18 07:46:06 +0000998bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
999 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001000}
1001
Sebastian Popa00a0292012-12-18 07:46:06 +00001002bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
1003 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001004}
1005
Tobias Grosser166c4222015-09-05 07:46:40 +00001006void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
1007 isl_map_free(NewAccessRelation);
1008 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001009}
Tobias Grosser75805372011-04-29 06:27:02 +00001010
1011//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001012
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001013__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001014 isl_set *Domain = getDomain();
1015 if (isl_set_is_empty(Domain)) {
1016 isl_set_free(Domain);
1017 return isl_map_from_aff(
1018 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1019 }
1020 auto *Schedule = getParent()->getSchedule();
1021 Schedule = isl_union_map_intersect_domain(
1022 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1023 if (isl_union_map_is_empty(Schedule)) {
1024 isl_set_free(Domain);
1025 isl_union_map_free(Schedule);
1026 return isl_map_from_aff(
1027 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1028 }
1029 auto *M = isl_map_from_union_map(Schedule);
1030 M = isl_map_coalesce(M);
1031 M = isl_map_gist_domain(M, Domain);
1032 M = isl_map_coalesce(M);
1033 return M;
1034}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001035
Johannes Doerfert574182d2015-08-12 10:19:50 +00001036__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Michael Kruse375cb5f2016-02-24 22:08:24 +00001037 return getParent()->getPwAff(E, getEntryBlock());
Johannes Doerfert574182d2015-08-12 10:19:50 +00001038}
1039
Tobias Grosser37eb4222014-02-20 21:43:54 +00001040void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1041 assert(isl_set_is_subset(NewDomain, Domain) &&
1042 "New domain is not a subset of old domain!");
1043 isl_set_free(Domain);
1044 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001045}
1046
Michael Krusecac948e2015-10-02 13:53:07 +00001047void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001048 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001049 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001050 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001051
Tobias Grossera535dff2015-12-13 19:59:01 +00001052 ScopArrayInfo::MemoryKind Ty;
1053 if (Access->isPHIKind())
1054 Ty = ScopArrayInfo::MK_PHI;
1055 else if (Access->isExitPHIKind())
1056 Ty = ScopArrayInfo::MK_ExitPHI;
1057 else if (Access->isValueKind())
1058 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001059 else
Tobias Grossera535dff2015-12-13 19:59:01 +00001060 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001061
Johannes Doerfertadeab372016-02-07 13:57:32 +00001062 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1063 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001064 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001065 }
1066}
1067
Michael Krusecac948e2015-10-02 13:53:07 +00001068void ScopStmt::addAccess(MemoryAccess *Access) {
1069 Instruction *AccessInst = Access->getAccessInstruction();
1070
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001071 if (Access->isArrayKind()) {
1072 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1073 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001074 } else if (Access->isValueKind() && Access->isWrite()) {
1075 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001076 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001077 assert(!ValueWrites.lookup(AccessVal));
1078
1079 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001080 } else if (Access->isValueKind() && Access->isRead()) {
1081 Value *AccessVal = Access->getAccessValue();
1082 assert(!ValueReads.lookup(AccessVal));
1083
1084 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001085 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1086 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1087 assert(!PHIWrites.lookup(PHI));
1088
1089 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001090 }
1091
1092 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001093}
1094
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001095void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001096 for (MemoryAccess *MA : *this)
1097 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001098
Johannes Doerfert7c013572016-04-12 09:57:34 +00001099 InvalidContext = isl_set_align_params(InvalidContext, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001100 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001101}
1102
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001103/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
1104static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1105 void *User) {
1106 isl_set **BoundedParts = static_cast<isl_set **>(User);
1107 if (isl_basic_set_is_bounded(BSet))
1108 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1109 else
1110 isl_basic_set_free(BSet);
1111 return isl_stat_ok;
1112}
1113
1114/// @brief Return the bounded parts of @p S.
1115static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1116 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1117 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1118 isl_set_free(S);
1119 return BoundedParts;
1120}
1121
1122/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
1123///
1124/// @returns A separation of @p S into first an unbounded then a bounded subset,
1125/// both with regards to the dimension @p Dim.
1126static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1127partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1128
1129 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001130 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001131
1132 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001133 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001134
1135 // Remove dimensions that are greater than Dim as they are not interesting.
1136 assert(NumDimsS >= Dim + 1);
1137 OnlyDimS =
1138 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1139
1140 // Create artificial parametric upper bounds for dimensions smaller than Dim
1141 // as we are not interested in them.
1142 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1143 for (unsigned u = 0; u < Dim; u++) {
1144 isl_constraint *C = isl_inequality_alloc(
1145 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1146 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1147 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1148 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1149 }
1150
1151 // Collect all bounded parts of OnlyDimS.
1152 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1153
1154 // Create the dimensions greater than Dim again.
1155 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1156 NumDimsS - Dim - 1);
1157
1158 // Remove the artificial upper bound parameters again.
1159 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1160
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001161 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001162 return std::make_pair(UnboundedParts, BoundedParts);
1163}
1164
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001165/// @brief Set the dimension Ids from @p From in @p To.
1166static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1167 __isl_take isl_set *To) {
1168 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1169 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1170 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1171 }
1172 return To;
1173}
1174
1175/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001176static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001177 __isl_take isl_pw_aff *L,
1178 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001179 switch (Pred) {
1180 case ICmpInst::ICMP_EQ:
1181 return isl_pw_aff_eq_set(L, R);
1182 case ICmpInst::ICMP_NE:
1183 return isl_pw_aff_ne_set(L, R);
1184 case ICmpInst::ICMP_SLT:
1185 return isl_pw_aff_lt_set(L, R);
1186 case ICmpInst::ICMP_SLE:
1187 return isl_pw_aff_le_set(L, R);
1188 case ICmpInst::ICMP_SGT:
1189 return isl_pw_aff_gt_set(L, R);
1190 case ICmpInst::ICMP_SGE:
1191 return isl_pw_aff_ge_set(L, R);
1192 case ICmpInst::ICMP_ULT:
1193 return isl_pw_aff_lt_set(L, R);
1194 case ICmpInst::ICMP_UGT:
1195 return isl_pw_aff_gt_set(L, R);
1196 case ICmpInst::ICMP_ULE:
1197 return isl_pw_aff_le_set(L, R);
1198 case ICmpInst::ICMP_UGE:
1199 return isl_pw_aff_ge_set(L, R);
1200 default:
1201 llvm_unreachable("Non integer predicate not supported");
1202 }
1203}
1204
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001205/// @brief Create the conditions under which @p L @p Pred @p R is true.
1206///
1207/// Helper function that will make sure the dimensions of the result have the
1208/// same isl_id's as the @p Domain.
1209static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1210 __isl_take isl_pw_aff *L,
1211 __isl_take isl_pw_aff *R,
1212 __isl_keep isl_set *Domain) {
1213 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1214 return setDimensionIds(Domain, ConsequenceCondSet);
1215}
1216
1217/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001218///
1219/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001220/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1221/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001222static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001223buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001224 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1225
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001226 Value *Condition = getConditionFromTerminator(SI);
1227 assert(Condition && "No condition for switch");
1228
1229 ScalarEvolution &SE = *S.getSE();
1230 BasicBlock *BB = SI->getParent();
1231 isl_pw_aff *LHS, *RHS;
1232 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1233
1234 unsigned NumSuccessors = SI->getNumSuccessors();
1235 ConditionSets.resize(NumSuccessors);
1236 for (auto &Case : SI->cases()) {
1237 unsigned Idx = Case.getSuccessorIndex();
1238 ConstantInt *CaseValue = Case.getCaseValue();
1239
1240 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1241 isl_set *CaseConditionSet =
1242 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1243 ConditionSets[Idx] = isl_set_coalesce(
1244 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1245 }
1246
1247 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1248 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1249 for (unsigned u = 2; u < NumSuccessors; u++)
1250 ConditionSetUnion =
1251 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1252 ConditionSets[0] = setDimensionIds(
1253 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1254
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001255 isl_pw_aff_free(LHS);
1256}
1257
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001258/// @brief Build the conditions sets for the branch condition @p Condition in
1259/// the @p Domain.
1260///
1261/// This will fill @p ConditionSets with the conditions under which control
1262/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001263/// have as many elements as @p TI has successors. If @p TI is nullptr the
1264/// context under which @p Condition is true/false will be returned as the
1265/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001266static void
1267buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1268 __isl_keep isl_set *Domain,
1269 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1270
1271 isl_set *ConsequenceCondSet = nullptr;
1272 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1273 if (CCond->isZero())
1274 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1275 else
1276 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1277 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1278 auto Opcode = BinOp->getOpcode();
1279 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1280
1281 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1282 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1283
1284 isl_set_free(ConditionSets.pop_back_val());
1285 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1286 isl_set_free(ConditionSets.pop_back_val());
1287 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1288
1289 if (Opcode == Instruction::And)
1290 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1291 else
1292 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1293 } else {
1294 auto *ICond = dyn_cast<ICmpInst>(Condition);
1295 assert(ICond &&
1296 "Condition of exiting branch was neither constant nor ICmp!");
1297
1298 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001299 BasicBlock *BB = TI ? TI->getParent() : nullptr;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001300 isl_pw_aff *LHS, *RHS;
1301 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1302 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1303 ConsequenceCondSet =
1304 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1305 }
1306
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001307 // If no terminator was given we are only looking for parameter constraints
1308 // under which @p Condition is true/false.
1309 if (!TI)
1310 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001311 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001312 ConsequenceCondSet = isl_set_coalesce(
1313 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001314
Johannes Doerfert15194912016-04-04 07:59:41 +00001315 isl_set *AlternativeCondSet;
1316 unsigned NumParams = isl_set_n_param(ConsequenceCondSet);
1317 unsigned NumBasicSets = isl_set_n_basic_set(ConsequenceCondSet);
1318 if (NumBasicSets + NumParams < MaxConjunctsInDomain) {
1319 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1320 isl_set_copy(ConsequenceCondSet));
1321 } else {
1322 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
1323 AlternativeCondSet = isl_set_empty(isl_set_get_space(ConsequenceCondSet));
1324 }
1325
1326 ConditionSets.push_back(ConsequenceCondSet);
1327 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001328}
1329
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001330/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1331///
1332/// This will fill @p ConditionSets with the conditions under which control
1333/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1334/// have as many elements as @p TI has successors.
1335static void
1336buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1337 __isl_keep isl_set *Domain,
1338 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1339
1340 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1341 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1342
1343 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1344
1345 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001346 ConditionSets.push_back(isl_set_copy(Domain));
1347 return;
1348 }
1349
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001350 Value *Condition = getConditionFromTerminator(TI);
1351 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001352
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001353 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001354}
1355
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001356void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001357 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001358
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001359 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001360 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001361}
1362
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001363void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP,
1364 ScopDetection &SD) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001365 isl_ctx *Ctx = Parent.getIslCtx();
1366 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1367 Type *Ty = GEP->getPointerOperandType();
1368 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001369
1370 // The set of loads that are required to be invariant.
1371 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001372
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001373 std::vector<const SCEV *> Subscripts;
1374 std::vector<int> Sizes;
1375
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001376 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001377
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001378 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001379 Ty = PtrTy->getElementType();
1380 }
1381
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001382 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001383
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001384 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001385
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001386 auto *NotExecuted = isl_set_complement(isl_set_params(getDomain()));
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001387 for (size_t i = 0; i < Sizes.size(); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001388 auto *Expr = Subscripts[i + IndexOffset];
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001389 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001390
Michael Kruse09eb4452016-03-03 22:10:47 +00001391 auto *Scope = SD.getLI()->getLoopFor(getEntryBlock());
Johannes Doerfert09e36972015-10-07 20:17:36 +00001392 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +00001393 if (!isAffineExpr(&Parent.getRegion(), Scope, Expr, SE, nullptr,
1394 &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +00001395 continue;
1396
1397 bool NonAffine = false;
1398 for (LoadInst *LInst : AccessILS)
1399 if (!ScopRIL.count(LInst))
1400 NonAffine = true;
1401
1402 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001403 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001404
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001405 isl_pw_aff *AccessOffset = getPwAff(Expr);
1406 AccessOffset =
1407 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001408
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001409 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1410 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001411
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001412 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1413 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1414 OutOfBound = isl_set_params(OutOfBound);
1415 isl_set *InBound = isl_set_complement(OutOfBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001416
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001417 // A => B == !A or B
1418 isl_set *InBoundIfExecuted =
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001419 isl_set_union(isl_set_copy(NotExecuted), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001420
Roman Gareev10595a12016-01-08 14:01:59 +00001421 InBoundIfExecuted = isl_set_coalesce(InBoundIfExecuted);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00001422 Parent.recordAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc(),
1423 AS_ASSUMPTION);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001424 }
1425
1426 isl_local_space_free(LSpace);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001427 isl_set_free(NotExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001428}
1429
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001430void ScopStmt::deriveAssumptions(BasicBlock *Block, ScopDetection &SD) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001431 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001432 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001433 deriveAssumptionsFromGEP(GEP, SD);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001434}
1435
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001436void ScopStmt::collectSurroundingLoops() {
1437 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1438 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1439 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1440 isl_id_free(DimId);
1441 }
1442}
1443
Michael Kruse9d080092015-09-11 21:41:48 +00001444ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerfert7c013572016-04-12 09:57:34 +00001445 : Parent(parent), InvalidContext(isl_set_empty(Parent.getParamSpace())),
1446 Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001447
Tobias Grosser16c44032015-07-09 07:31:45 +00001448 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001449}
1450
Michael Kruse9d080092015-09-11 21:41:48 +00001451ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerfert7c013572016-04-12 09:57:34 +00001452 : Parent(parent), InvalidContext(isl_set_empty(Parent.getParamSpace())),
1453 Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001454
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001455 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001456}
1457
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001458void ScopStmt::init(ScopDetection &SD) {
Michael Krusecac948e2015-10-02 13:53:07 +00001459 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001460
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001461 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001462 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001463 buildAccessRelations();
1464
1465 if (BB) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001466 deriveAssumptions(BB, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001467 } else {
1468 for (BasicBlock *Block : R->blocks()) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001469 deriveAssumptions(Block, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001470 }
1471 }
1472
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001473 if (DetectReductions)
1474 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001475}
1476
Johannes Doerferte58a0122014-06-27 20:31:28 +00001477/// @brief Collect loads which might form a reduction chain with @p StoreMA
1478///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001479/// Check if the stored value for @p StoreMA is a binary operator with one or
1480/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001481/// used only once (by @p StoreMA) and its load operands are also used only
1482/// once, we have found a possible reduction chain. It starts at an operand
1483/// load and includes the binary operator and @p StoreMA.
1484///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001485/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001486/// escape this block or into any other store except @p StoreMA.
1487void ScopStmt::collectCandiateReductionLoads(
1488 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1489 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1490 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001491 return;
1492
1493 // Skip if there is not one binary operator between the load and the store
1494 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001495 if (!BinOp)
1496 return;
1497
1498 // Skip if the binary operators has multiple uses
1499 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001500 return;
1501
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001502 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001503 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1504 return;
1505
Johannes Doerfert9890a052014-07-01 00:32:29 +00001506 // Skip if the binary operator is outside the current SCoP
1507 if (BinOp->getParent() != Store->getParent())
1508 return;
1509
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001510 // Skip if it is a multiplicative reduction and we disabled them
1511 if (DisableMultiplicativeReductions &&
1512 (BinOp->getOpcode() == Instruction::Mul ||
1513 BinOp->getOpcode() == Instruction::FMul))
1514 return;
1515
Johannes Doerferte58a0122014-06-27 20:31:28 +00001516 // Check the binary operator operands for a candidate load
1517 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1518 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1519 if (!PossibleLoad0 && !PossibleLoad1)
1520 return;
1521
1522 // A load is only a candidate if it cannot escape (thus has only this use)
1523 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001524 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001525 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001526 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001527 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001528 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001529}
1530
1531/// @brief Check for reductions in this ScopStmt
1532///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001533/// Iterate over all store memory accesses and check for valid binary reduction
1534/// like chains. For all candidates we check if they have the same base address
1535/// and there are no other accesses which overlap with them. The base address
1536/// check rules out impossible reductions candidates early. The overlap check,
1537/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001538/// guarantees that none of the intermediate results will escape during
1539/// execution of the loop nest. We basically check here that no other memory
1540/// access can access the same memory as the potential reduction.
1541void ScopStmt::checkForReductions() {
1542 SmallVector<MemoryAccess *, 2> Loads;
1543 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1544
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001545 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001546 // stores and collecting possible reduction loads.
1547 for (MemoryAccess *StoreMA : MemAccs) {
1548 if (StoreMA->isRead())
1549 continue;
1550
1551 Loads.clear();
1552 collectCandiateReductionLoads(StoreMA, Loads);
1553 for (MemoryAccess *LoadMA : Loads)
1554 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1555 }
1556
1557 // Then check each possible candidate pair.
1558 for (const auto &CandidatePair : Candidates) {
1559 bool Valid = true;
1560 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1561 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1562
1563 // Skip those with obviously unequal base addresses.
1564 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1565 isl_map_free(LoadAccs);
1566 isl_map_free(StoreAccs);
1567 continue;
1568 }
1569
1570 // And check if the remaining for overlap with other memory accesses.
1571 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1572 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1573 isl_set *AllAccs = isl_map_range(AllAccsRel);
1574
1575 for (MemoryAccess *MA : MemAccs) {
1576 if (MA == CandidatePair.first || MA == CandidatePair.second)
1577 continue;
1578
1579 isl_map *AccRel =
1580 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1581 isl_set *Accs = isl_map_range(AccRel);
1582
1583 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1584 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1585 Valid = Valid && isl_set_is_empty(OverlapAccs);
1586 isl_set_free(OverlapAccs);
1587 }
1588 }
1589
1590 isl_set_free(AllAccs);
1591 if (!Valid)
1592 continue;
1593
Johannes Doerfertf6183392014-07-01 20:52:51 +00001594 const LoadInst *Load =
1595 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1596 MemoryAccess::ReductionType RT =
1597 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1598
Johannes Doerferte58a0122014-06-27 20:31:28 +00001599 // If no overlapping access was found we mark the load and store as
1600 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001601 CandidatePair.first->markAsReductionLike(RT);
1602 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001603 }
Tobias Grosser75805372011-04-29 06:27:02 +00001604}
1605
Tobias Grosser74394f02013-01-14 22:40:23 +00001606std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001607
Tobias Grosser54839312015-04-21 11:37:25 +00001608std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001609 auto *S = getSchedule();
1610 auto Str = stringFromIslObj(S);
1611 isl_map_free(S);
1612 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001613}
1614
Johannes Doerfert7c013572016-04-12 09:57:34 +00001615void ScopStmt::setInvalidContext(__isl_take isl_set *IC) {
1616 isl_set_free(InvalidContext);
1617 InvalidContext = IC;
1618}
1619
Michael Kruse375cb5f2016-02-24 22:08:24 +00001620BasicBlock *ScopStmt::getEntryBlock() const {
1621 if (isBlockStmt())
1622 return getBasicBlock();
1623 return getRegion()->getEntry();
1624}
1625
Michael Kruse7b5caa42016-02-24 22:08:28 +00001626RegionNode *ScopStmt::getRegionNode() const {
1627 if (isRegionStmt())
1628 return getRegion()->getNode();
1629 return getParent()->getRegion().getBBNode(getBasicBlock());
1630}
1631
Tobias Grosser74394f02013-01-14 22:40:23 +00001632unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001633
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001634unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001635
Tobias Grosser75805372011-04-29 06:27:02 +00001636const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1637
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001638const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001639 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001640}
1641
Tobias Grosser74394f02013-01-14 22:40:23 +00001642isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001643
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001644__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001645
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001646__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001647 return isl_set_get_space(Domain);
1648}
1649
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001650__isl_give isl_id *ScopStmt::getDomainId() const {
1651 return isl_set_get_tuple_id(Domain);
1652}
Tobias Grossercd95b772012-08-30 11:49:38 +00001653
Johannes Doerfert7c013572016-04-12 09:57:34 +00001654ScopStmt::~ScopStmt() {
1655 isl_set_free(Domain);
1656 isl_set_free(InvalidContext);
1657}
Tobias Grosser75805372011-04-29 06:27:02 +00001658
1659void ScopStmt::print(raw_ostream &OS) const {
1660 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001661 OS.indent(12) << "Domain :=\n";
1662
1663 if (Domain) {
1664 OS.indent(16) << getDomainStr() << ";\n";
1665 } else
1666 OS.indent(16) << "n/a\n";
1667
Tobias Grosser54839312015-04-21 11:37:25 +00001668 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001669
1670 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001671 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001672 } else
1673 OS.indent(16) << "n/a\n";
1674
Tobias Grosser083d3d32014-06-28 08:59:45 +00001675 for (MemoryAccess *Access : MemAccs)
1676 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001677}
1678
1679void ScopStmt::dump() const { print(dbgs()); }
1680
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001681void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001682 // Remove all memory accesses in @p InvMAs from this statement
1683 // together with all scalar accesses that were caused by them.
Michael Krusead28e5a2016-01-26 13:33:15 +00001684 // MK_Value READs have no access instruction, hence would not be removed by
1685 // this function. However, it is only used for invariant LoadInst accesses,
1686 // its arguments are always affine, hence synthesizable, and therefore there
1687 // are no MK_Value READ accesses to be removed.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001688 for (MemoryAccess *MA : InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001689 auto Predicate = [&](MemoryAccess *Acc) {
Tobias Grosser3a6ac9f2015-11-30 21:13:43 +00001690 return Acc->getAccessInstruction() == MA->getAccessInstruction();
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001691 };
1692 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1693 MemAccs.end());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001694 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001695 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001696}
1697
Tobias Grosser75805372011-04-29 06:27:02 +00001698//===----------------------------------------------------------------------===//
1699/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001700
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001701void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001702 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1703 isl_set_free(Context);
1704 Context = NewContext;
1705}
1706
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001707/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1708struct SCEVSensitiveParameterRewriter
1709 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1710 ValueToValueMap &VMap;
1711 ScalarEvolution &SE;
1712
1713public:
1714 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1715 : VMap(VMap), SE(SE) {}
1716
1717 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1718 ValueToValueMap &VMap) {
1719 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1720 return SSPR.visit(E);
1721 }
1722
1723 const SCEV *visit(const SCEV *E) {
1724 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1725 }
1726
1727 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1728
1729 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1730 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1731 }
1732
1733 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1734 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1735 }
1736
1737 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1738 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1739 }
1740
1741 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1742 SmallVector<const SCEV *, 4> Operands;
1743 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1744 Operands.push_back(visit(E->getOperand(i)));
1745 return SE.getAddExpr(Operands);
1746 }
1747
1748 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1749 SmallVector<const SCEV *, 4> Operands;
1750 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1751 Operands.push_back(visit(E->getOperand(i)));
1752 return SE.getMulExpr(Operands);
1753 }
1754
1755 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1756 SmallVector<const SCEV *, 4> Operands;
1757 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1758 Operands.push_back(visit(E->getOperand(i)));
1759 return SE.getSMaxExpr(Operands);
1760 }
1761
1762 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1763 SmallVector<const SCEV *, 4> Operands;
1764 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1765 Operands.push_back(visit(E->getOperand(i)));
1766 return SE.getUMaxExpr(Operands);
1767 }
1768
1769 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1770 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1771 }
1772
1773 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1774 auto *Start = visit(E->getStart());
1775 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1776 visit(E->getStepRecurrence(SE)),
1777 E->getLoop(), SCEV::FlagAnyWrap);
1778 return SE.getAddExpr(Start, AddRec);
1779 }
1780
1781 const SCEV *visitUnknown(const SCEVUnknown *E) {
1782 if (auto *NewValue = VMap.lookup(E->getValue()))
1783 return SE.getUnknown(NewValue);
1784 return E;
1785 }
1786};
1787
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001788const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001789 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001790}
1791
Tobias Grosserabfbe632013-02-05 12:09:06 +00001792void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001793 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001794 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001795
1796 // Normalize the SCEV to get the representing element for an invariant load.
1797 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1798
Tobias Grosser60b54f12011-11-08 15:41:28 +00001799 if (ParameterIds.find(Parameter) != ParameterIds.end())
1800 continue;
1801
1802 int dimension = Parameters.size();
1803
1804 Parameters.push_back(Parameter);
1805 ParameterIds[Parameter] = dimension;
1806 }
1807}
1808
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001809__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001810 // Normalize the SCEV to get the representing element for an invariant load.
1811 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1812
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001813 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001814
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001815 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001816 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001817
Tobias Grosser8f99c162011-11-15 11:38:55 +00001818 std::string ParameterName;
1819
Craig Topper7fb6e472016-01-31 20:36:20 +00001820 ParameterName = "p_" + utostr(IdIter->second);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001821
Tobias Grosser8f99c162011-11-15 11:38:55 +00001822 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1823 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001824
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001825 // If this parameter references a specific Value and this value has a name
1826 // we use this name as it is likely to be unique and more useful than just
1827 // a number.
1828 if (Val->hasName())
1829 ParameterName = Val->getName();
1830 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001831 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001832 if (LoadOrigin->hasName()) {
1833 ParameterName += "_loaded_from_";
1834 ParameterName +=
1835 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1836 }
1837 }
1838 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001839
Tobias Grosser20532b82014-04-11 17:56:49 +00001840 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1841 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001842}
Tobias Grosser75805372011-04-29 06:27:02 +00001843
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001844__isl_give isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001845 isl_set *DomainContext = isl_union_set_params(getDomains());
1846 return isl_set_intersect_params(C, DomainContext);
1847}
1848
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001849void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1850 LoopInfo &LI) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001851 auto *R = &getRegion();
1852 auto &F = *R->getEntry()->getParent();
1853 for (auto &Assumption : AC.assumptions()) {
1854 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1855 if (!CI || CI->getNumArgOperands() != 1)
1856 continue;
1857 if (!DT.dominates(CI->getParent(), R->getEntry()))
1858 continue;
1859
Michael Kruse09eb4452016-03-03 22:10:47 +00001860 auto *L = LI.getLoopFor(CI->getParent());
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001861 auto *Val = CI->getArgOperand(0);
1862 std::vector<const SCEV *> Params;
Michael Kruse09eb4452016-03-03 22:10:47 +00001863 if (!isAffineParamConstraint(Val, R, L, *SE, Params)) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001864 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1865 CI->getDebugLoc(),
1866 "Non-affine user assumption ignored.");
1867 continue;
1868 }
1869
1870 addParams(Params);
1871
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001872 SmallVector<isl_set *, 2> ConditionSets;
1873 buildConditionSets(*this, Val, nullptr, L, Context, ConditionSets);
1874 assert(ConditionSets.size() == 2);
1875 isl_set_free(ConditionSets[1]);
1876
1877 auto *AssumptionCtx = ConditionSets[0];
1878 emitOptimizationRemarkAnalysis(
1879 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1880 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1881 Context = isl_set_intersect(Context, AssumptionCtx);
1882 }
1883}
1884
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001885void Scop::addUserContext() {
1886 if (UserContextStr.empty())
1887 return;
1888
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001889 isl_set *UserContext =
1890 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001891 isl_space *Space = getParamSpace();
1892 if (isl_space_dim(Space, isl_dim_param) !=
1893 isl_set_dim(UserContext, isl_dim_param)) {
1894 auto SpaceStr = isl_space_to_str(Space);
1895 errs() << "Error: the context provided in -polly-context has not the same "
1896 << "number of dimensions than the computed context. Due to this "
1897 << "mismatch, the -polly-context option is ignored. Please provide "
1898 << "the context in the parameter space: " << SpaceStr << ".\n";
1899 free(SpaceStr);
1900 isl_set_free(UserContext);
1901 isl_space_free(Space);
1902 return;
1903 }
1904
1905 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001906 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1907 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001908
1909 if (strcmp(NameContext, NameUserContext) != 0) {
1910 auto SpaceStr = isl_space_to_str(Space);
1911 errs() << "Error: the name of dimension " << i
1912 << " provided in -polly-context "
1913 << "is '" << NameUserContext << "', but the name in the computed "
1914 << "context is '" << NameContext
1915 << "'. Due to this name mismatch, "
1916 << "the -polly-context option is ignored. Please provide "
1917 << "the context in the parameter space: " << SpaceStr << ".\n";
1918 free(SpaceStr);
1919 isl_set_free(UserContext);
1920 isl_space_free(Space);
1921 return;
1922 }
1923
1924 UserContext =
1925 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1926 isl_space_get_dim_id(Space, isl_dim_param, i));
1927 }
1928
1929 Context = isl_set_intersect(Context, UserContext);
1930 isl_space_free(Space);
1931}
1932
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001933void Scop::buildInvariantEquivalenceClasses(ScopDetection &SD) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001934 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001935
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001936 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001937 for (LoadInst *LInst : RIL) {
1938 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1939
Johannes Doerfert96e54712016-02-07 17:30:13 +00001940 Type *Ty = LInst->getType();
1941 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001942 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001943 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001944 continue;
1945 }
1946
1947 ClassRep = LInst;
Johannes Doerfert96e54712016-02-07 17:30:13 +00001948 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(), nullptr,
1949 Ty);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001950 }
1951}
1952
Tobias Grosser6be480c2011-11-08 15:41:13 +00001953void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001954 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001955 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001956 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00001957 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001958}
1959
Tobias Grosser18daaca2012-05-22 10:47:27 +00001960void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001961 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001962 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001963
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001964 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001965
Johannes Doerferte7044942015-02-24 11:58:30 +00001966 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001967 }
1968}
1969
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001970void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001971 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001972 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001973
Tobias Grosser083d3d32014-06-28 08:59:45 +00001974 for (const auto &ParamID : ParameterIds) {
1975 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001976 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001977 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001978 }
1979
1980 // Align the parameters of all data structures to the model.
1981 Context = isl_set_align_params(Context, Space);
1982
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001983 for (ScopStmt &Stmt : *this)
1984 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001985}
1986
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001987static __isl_give isl_set *
1988simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1989 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001990 // If we modelt all blocks in the SCoP that have side effects we can simplify
1991 // the context with the constraints that are needed for anything to be
1992 // executed at all. However, if we have error blocks in the SCoP we already
1993 // assumed some parameter combinations cannot occure and removed them from the
1994 // domains, thus we cannot use the remaining domain to simplify the
1995 // assumptions.
1996 if (!S.hasErrorBlock()) {
1997 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1998 AssumptionContext =
1999 isl_set_gist_params(AssumptionContext, DomainParameters);
2000 }
2001
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002002 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2003 return AssumptionContext;
2004}
2005
2006void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002007 // The parameter constraints of the iteration domains give us a set of
2008 // constraints that need to hold for all cases where at least a single
2009 // statement iteration is executed in the whole scop. We now simplify the
2010 // assumed context under the assumption that such constraints hold and at
2011 // least a single statement iteration is executed. For cases where no
2012 // statement instances are executed, the assumptions we have taken about
2013 // the executed code do not matter and can be changed.
2014 //
2015 // WARNING: This only holds if the assumptions we have taken do not reduce
2016 // the set of statement instances that are executed. Otherwise we
2017 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002018 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002019 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002020 // performed. In such a case, modifying the run-time conditions and
2021 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002022 // to not be executed.
2023 //
2024 // Example:
2025 //
2026 // When delinearizing the following code:
2027 //
2028 // for (long i = 0; i < 100; i++)
2029 // for (long j = 0; j < m; j++)
2030 // A[i+p][j] = 1.0;
2031 //
2032 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002033 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002034 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002035 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002036 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002037}
2038
Johannes Doerfertb164c792014-09-18 11:17:17 +00002039/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002040static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002041 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2042 isl_pw_multi_aff *MinPMA, *MaxPMA;
2043 isl_pw_aff *LastDimAff;
2044 isl_aff *OneAff;
2045 unsigned Pos;
2046
Johannes Doerfert9143d672014-09-27 11:02:39 +00002047 // Restrict the number of parameters involved in the access as the lexmin/
2048 // lexmax computation will take too long if this number is high.
2049 //
2050 // Experiments with a simple test case using an i7 4800MQ:
2051 //
2052 // #Parameters involved | Time (in sec)
2053 // 6 | 0.01
2054 // 7 | 0.04
2055 // 8 | 0.12
2056 // 9 | 0.40
2057 // 10 | 1.54
2058 // 11 | 6.78
2059 // 12 | 30.38
2060 //
2061 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2062 unsigned InvolvedParams = 0;
2063 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2064 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2065 InvolvedParams++;
2066
2067 if (InvolvedParams > RunTimeChecksMaxParameters) {
2068 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002069 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002070 }
2071 }
2072
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00002073 Set = isl_set_remove_divs(Set);
2074
Johannes Doerfertb164c792014-09-18 11:17:17 +00002075 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2076 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2077
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002078 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2079 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2080
Johannes Doerfertb164c792014-09-18 11:17:17 +00002081 // Adjust the last dimension of the maximal access by one as we want to
2082 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2083 // we test during code generation might now point after the end of the
2084 // allocated array but we will never dereference it anyway.
2085 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2086 "Assumed at least one output dimension");
2087 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2088 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2089 OneAff = isl_aff_zero_on_domain(
2090 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2091 OneAff = isl_aff_add_constant_si(OneAff, 1);
2092 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2093 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2094
2095 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2096
2097 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002098 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002099}
2100
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002101static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2102 isl_set *Domain = MA->getStatement()->getDomain();
2103 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2104 return isl_set_reset_tuple_id(Domain);
2105}
2106
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002107/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
2108static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002109 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002110 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002111
2112 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2113 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002114 Locations = isl_union_set_coalesce(Locations);
2115 Locations = isl_union_set_detect_equalities(Locations);
2116 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002117 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002118 isl_union_set_free(Locations);
2119 return Valid;
2120}
2121
Johannes Doerfert96425c22015-08-30 21:13:53 +00002122/// @brief Helper to treat non-affine regions and basic blocks the same.
2123///
2124///{
2125
2126/// @brief Return the block that is the representing block for @p RN.
2127static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2128 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2129 : RN->getNodeAs<BasicBlock>();
2130}
2131
2132/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002133static inline BasicBlock *
2134getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002135 if (RN->isSubRegion()) {
2136 assert(idx == 0);
2137 return RN->getNodeAs<Region>()->getExit();
2138 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002139 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002140}
2141
2142/// @brief Return the smallest loop surrounding @p RN.
2143static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2144 if (!RN->isSubRegion())
2145 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2146
2147 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2148 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2149 while (L && NonAffineSubRegion->contains(L))
2150 L = L->getParentLoop();
2151 return L;
2152}
2153
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002154static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2155 if (!RN->isSubRegion())
2156 return 1;
2157
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002158 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002159 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002160}
2161
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002162static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2163 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002164 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002165 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002166 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002167 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002168 return true;
2169 return false;
2170}
2171
Johannes Doerfert96425c22015-08-30 21:13:53 +00002172///}
2173
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002174static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2175 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002176 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002177 isl_id *DimId =
2178 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2179 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2180}
2181
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002182__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002183 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002184}
2185
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002186__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002187 auto DIt = DomainMap.find(BB);
2188 if (DIt != DomainMap.end())
2189 return isl_set_copy(DIt->getSecond());
2190
2191 auto &RI = *R.getRegionInfo();
2192 auto *BBR = RI.getRegionFor(BB);
2193 while (BBR->getEntry() == BB)
2194 BBR = BBR->getParent();
2195 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002196}
2197
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002198bool Scop::buildDomains(Region *R, ScopDetection &SD, DominatorTree &DT,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002199 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002200
Johannes Doerfert432658d2016-01-26 11:01:41 +00002201 bool IsOnlyNonAffineRegion = SD.isNonAffineSubRegion(R, R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002202 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002203 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2204 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002205 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002206
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002207 while (LD-- >= 0) {
2208 S = addDomainDimId(S, LD + 1, L);
2209 L = L->getParentLoop();
2210 }
2211
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002212 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002213
Johannes Doerfert432658d2016-01-26 11:01:41 +00002214 if (IsOnlyNonAffineRegion)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002215 return true;
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002216
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002217 if (!buildDomainsWithBranchConstraints(R, SD, DT, LI))
2218 return false;
2219
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002220 propagateDomainConstraints(R, SD, DT, LI);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002221
2222 // Error blocks and blocks dominated by them have been assumed to never be
2223 // executed. Representing them in the Scop does not add any value. In fact,
2224 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002225 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002226 // will cause problems when building up a ScopStmt for them.
2227 // Furthermore, basic blocks dominated by error blocks may reference
2228 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002229 // can themselves not be constructed properly. To this end we will replace
2230 // the domains of error blocks and those only reachable via error blocks
2231 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002232 // parameter combination it would be reached via an error block in its
2233 // InvalidContext. This information is needed during load hoisting.
2234 propagateInvalidStmtContexts(R, SD, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002235
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002236 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002237}
2238
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002239static Loop *
2240getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI,
2241 const ScopDetection::BoxedLoopsSetTy &BoxedLoops) {
2242 auto *L = LI.getLoopFor(BB);
2243 while (BoxedLoops.count(L))
2244 L = L->getParentLoop();
2245 return L;
2246}
2247
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002248/// @brief Adjust the dimensions of @p Dom that was constructed for @p OldL
2249/// to be compatible to domains constructed for loop @p NewL.
2250///
2251/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2252/// edge from @p OldL to @p NewL.
2253static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2254 __isl_take isl_set *Dom,
2255 Loop *OldL, Loop *NewL) {
2256
2257 // If the loops are the same there is nothing to do.
2258 if (NewL == OldL)
2259 return Dom;
2260
2261 int OldDepth = S.getRelativeLoopDepth(OldL);
2262 int NewDepth = S.getRelativeLoopDepth(NewL);
2263 // If both loops are non-affine loops there is nothing to do.
2264 if (OldDepth == -1 && NewDepth == -1)
2265 return Dom;
2266
2267 // Distinguish three cases:
2268 // 1) The depth is the same but the loops are not.
2269 // => One loop was left one was entered.
2270 // 2) The depth increased from OldL to NewL.
2271 // => One loop was entered, none was left.
2272 // 3) The depth decreased from OldL to NewL.
2273 // => Loops were left were difference of the depths defines how many.
2274 if (OldDepth == NewDepth) {
2275 assert(OldL->getParentLoop() == NewL->getParentLoop());
2276 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2277 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2278 Dom = addDomainDimId(Dom, NewDepth, NewL);
2279 } else if (OldDepth < NewDepth) {
2280 assert(OldDepth + 1 == NewDepth);
2281 auto &R = S.getRegion();
2282 (void)R;
2283 assert(NewL->getParentLoop() == OldL ||
2284 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2285 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2286 Dom = addDomainDimId(Dom, NewDepth, NewL);
2287 } else {
2288 assert(OldDepth > NewDepth);
2289 int Diff = OldDepth - NewDepth;
2290 int NumDim = isl_set_n_dim(Dom);
2291 assert(NumDim >= Diff);
2292 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2293 }
2294
2295 return Dom;
2296}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002297
Johannes Doerfert7c013572016-04-12 09:57:34 +00002298void Scop::propagateInvalidStmtContexts(Region *R, ScopDetection &SD,
2299 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002300
2301 ReversePostOrderTraversal<Region *> RTraversal(R);
2302 for (auto *RN : RTraversal) {
2303
2304 // Recurse for affine subregions but go on for basic blocks and non-affine
2305 // subregions.
2306 if (RN->isSubRegion()) {
2307 Region *SubRegion = RN->getNodeAs<Region>();
2308 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfert7c013572016-04-12 09:57:34 +00002309 propagateInvalidStmtContexts(SubRegion, SD, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002310 continue;
2311 }
2312 }
2313
2314 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2315 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002316 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002317 isl_set *&Domain = DomainMap[BB];
2318 assert(Domain && "Cannot propagate a nullptr");
2319
Johannes Doerfert7c013572016-04-12 09:57:34 +00002320 auto *InvalidCtx = Stmt->getInvalidContext();
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002321 auto *DomainCtx = isl_set_params(isl_set_copy(Domain));
Johannes Doerfert7c013572016-04-12 09:57:34 +00002322 bool IsInvalidBlock =
2323 ContainsErrorBlock || isl_set_is_subset(DomainCtx, InvalidCtx);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002324
Johannes Doerfert7c013572016-04-12 09:57:34 +00002325 if (IsInvalidBlock) {
2326 InvalidCtx = isl_set_coalesce(isl_set_union(InvalidCtx, DomainCtx));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002327 auto *EmptyDom = isl_set_empty(isl_set_get_space(Domain));
2328 isl_set_free(Domain);
2329 Domain = EmptyDom;
2330 } else {
2331 isl_set_free(DomainCtx);
2332 }
2333
Johannes Doerfert7c013572016-04-12 09:57:34 +00002334 if (isl_set_is_empty(InvalidCtx)) {
2335 isl_set_free(InvalidCtx);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002336 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002337 }
2338
2339 Stmt->setInvalidContext(InvalidCtx);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002340
2341 auto *TI = BB->getTerminator();
2342 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2343 for (unsigned u = 0; u < NumSuccs; u++) {
2344 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002345 auto *SuccStmt = getStmtFor(SuccBB);
2346
2347 // Skip successors outside the SCoP.
2348 if (!SuccStmt)
2349 continue;
2350
2351 auto *SuccInvalidCtx = SuccStmt->getInvalidContext();
2352 SuccInvalidCtx = isl_set_union(SuccInvalidCtx, Stmt->getInvalidContext());
2353 SuccInvalidCtx = isl_set_coalesce(SuccInvalidCtx);
2354 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidCtx);
2355 SuccStmt->setInvalidContext(SuccInvalidCtx);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002356
2357 // Check if the maximal number of domain conjuncts was reached.
2358 // In case this happens we will bail.
Johannes Doerfert7c013572016-04-12 09:57:34 +00002359 if (NumConjucts < MaxConjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002360 continue;
2361
2362 invalidate(COMPLEXITY, TI->getDebugLoc());
2363 return;
2364 }
2365 }
2366}
2367
Johannes Doerfert642594a2016-04-04 07:57:39 +00002368void Scop::propagateDomainConstraintsToRegionExit(
2369 BasicBlock *BB, Loop *BBLoop,
2370 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, ScopDetection &SD,
2371 LoopInfo &LI) {
2372
2373 // Check if the block @p BB is the entry of a region. If so we propagate it's
2374 // domain to the exit block of the region. Otherwise we are done.
2375 auto *RI = R.getRegionInfo();
2376 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2377 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
2378 if (!BBReg || BBReg->getEntry() != BB || !R.contains(ExitBB))
2379 return;
2380
2381 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2382 // Do not propagate the domain if there is a loop backedge inside the region
2383 // that would prevent the exit block from beeing executed.
2384 auto *L = BBLoop;
2385 while (L && R.contains(L)) {
2386 SmallVector<BasicBlock *, 4> LatchBBs;
2387 BBLoop->getLoopLatches(LatchBBs);
2388 for (auto *LatchBB : LatchBBs)
2389 if (BB != LatchBB && BBReg->contains(LatchBB))
2390 return;
2391 L = L->getParentLoop();
2392 }
2393
2394 auto *Domain = DomainMap[BB];
2395 assert(Domain && "Cannot propagate a nullptr");
2396
2397 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2398
2399 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2400 // adjust the domain before we can propagate it.
2401 auto *AdjustedDomain =
2402 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2403 auto *&ExitDomain = DomainMap[ExitBB];
2404
2405 // If the exit domain is not yet created we set it otherwise we "add" the
2406 // current domain.
2407 ExitDomain =
2408 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2409
2410 FinishedExitBlocks.insert(ExitBB);
2411}
2412
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002413bool Scop::buildDomainsWithBranchConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002414 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002415 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002416
2417 // To create the domain for each block in R we iterate over all blocks and
2418 // subregions in R and propagate the conditions under which the current region
2419 // element is executed. To this end we iterate in reverse post order over R as
2420 // it ensures that we first visit all predecessors of a region node (either a
2421 // basic block or a subregion) before we visit the region node itself.
2422 // Initially, only the domain for the SCoP region entry block is set and from
2423 // there we propagate the current domain to all successors, however we add the
2424 // condition that the successor is actually executed next.
2425 // As we are only interested in non-loop carried constraints here we can
2426 // simply skip loop back edges.
2427
Johannes Doerfert642594a2016-04-04 07:57:39 +00002428 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002429 ReversePostOrderTraversal<Region *> RTraversal(R);
2430 for (auto *RN : RTraversal) {
2431
2432 // Recurse for affine subregions but go on for basic blocks and non-affine
2433 // subregions.
2434 if (RN->isSubRegion()) {
2435 Region *SubRegion = RN->getNodeAs<Region>();
2436 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002437 if (!buildDomainsWithBranchConstraints(SubRegion, SD, DT, LI))
2438 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002439 continue;
2440 }
2441 }
2442
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002443 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002444 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002445
Johannes Doerfert96425c22015-08-30 21:13:53 +00002446 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002447 TerminatorInst *TI = BB->getTerminator();
2448
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002449 if (isa<UnreachableInst>(TI))
2450 continue;
2451
Johannes Doerfertf5673802015-10-01 23:48:18 +00002452 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002453 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002454 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002455
Johannes Doerfert642594a2016-04-04 07:57:39 +00002456 auto *BBLoop = getRegionNodeLoop(RN, LI);
2457 // Propagate the domain from BB directly to blocks that have a superset
2458 // domain, at the moment only region exit nodes of regions that start in BB.
2459 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, SD,
2460 LI);
2461
2462 // If all successors of BB have been set a domain through the propagation
2463 // above we do not need to build condition sets but can just skip this
2464 // block. However, it is important to note that this is a local property
2465 // with regards to the region @p R. To this end FinishedExitBlocks is a
2466 // local variable.
2467 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2468 return FinishedExitBlocks.count(SuccBB);
2469 };
2470 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2471 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002472
2473 // Build the condition sets for the successor nodes of the current region
2474 // node. If it is a non-affine subregion we will always execute the single
2475 // exit node, hence the single entry node domain is the condition set. For
2476 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002477 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002478 if (RN->isSubRegion())
2479 ConditionSets.push_back(isl_set_copy(Domain));
2480 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002481 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002482
2483 // Now iterate over the successors and set their initial domain based on
2484 // their condition set. We skip back edges here and have to be careful when
2485 // we leave a loop not to keep constraints over a dimension that doesn't
2486 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002487 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002488 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002489 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002490 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002491
Johannes Doerfert642594a2016-04-04 07:57:39 +00002492 // If we propagate the domain of some block to "SuccBB" we do not have to
2493 // adjust the domain.
2494 if (FinishedExitBlocks.count(SuccBB)) {
2495 isl_set_free(CondSet);
2496 continue;
2497 }
2498
Johannes Doerfert96425c22015-08-30 21:13:53 +00002499 // Skip back edges.
2500 if (DT.dominates(SuccBB, BB)) {
2501 isl_set_free(CondSet);
2502 continue;
2503 }
2504
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002505 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002506 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002507
2508 // Set the domain for the successor or merge it with an existing domain in
2509 // case there are multiple paths (without loop back edges) to the
2510 // successor block.
2511 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002512
Johannes Doerfert96425c22015-08-30 21:13:53 +00002513 if (!SuccDomain)
2514 SuccDomain = CondSet;
2515 else
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002516 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002517
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002518 // Check if the maximal number of domain conjuncts was reached.
2519 // In case this happens we will clean up and bail.
Johannes Doerfert15194912016-04-04 07:59:41 +00002520 if (isl_set_n_basic_set(SuccDomain) < MaxConjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002521 continue;
2522
2523 invalidate(COMPLEXITY, DebugLoc());
2524 while (++u < ConditionSets.size())
2525 isl_set_free(ConditionSets[u]);
2526 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002527 }
2528 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002529
2530 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002531}
2532
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00002533__isl_give isl_set *Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2534 isl_set *Domain,
2535 ScopDetection &SD,
2536 DominatorTree &DT,
2537 LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002538 // If @p BB is the ScopEntry we are done
2539 if (R.getEntry() == BB)
2540 return isl_set_universe(isl_set_get_space(Domain));
2541
2542 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2543 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2544
2545 // The region info of this function.
2546 auto &RI = *R.getRegionInfo();
2547
2548 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2549
2550 // A domain to collect all predecessor domains, thus all conditions under
2551 // which the block is executed. To this end we start with the empty domain.
2552 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2553
2554 // Set of regions of which the entry block domain has been propagated to BB.
2555 // all predecessors inside any of the regions can be skipped.
2556 SmallSet<Region *, 8> PropagatedRegions;
2557
2558 for (auto *PredBB : predecessors(BB)) {
2559 // Skip backedges.
2560 if (DT.dominates(BB, PredBB))
2561 continue;
2562
2563 // If the predecessor is in a region we used for propagation we can skip it.
2564 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2565 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2566 PredBBInRegion)) {
2567 continue;
2568 }
2569
2570 // Check if there is a valid region we can use for propagation, thus look
2571 // for a region that contains the predecessor and has @p BB as exit block.
2572 auto *PredR = RI.getRegionFor(PredBB);
2573 while (PredR->getExit() != BB && !PredR->contains(BB))
2574 PredR->getParent();
2575
2576 // If a valid region for propagation was found use the entry of that region
2577 // for propagation, otherwise the PredBB directly.
2578 if (PredR->getExit() == BB) {
2579 PredBB = PredR->getEntry();
2580 PropagatedRegions.insert(PredR);
2581 }
2582
Johannes Doerfert41cda152016-04-08 10:32:26 +00002583 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002584 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2585 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2586
2587 PredDom = isl_set_union(PredDom, PredBBDom);
2588 }
2589
2590 return PredDom;
2591}
2592
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002593void Scop::propagateDomainConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002594 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002595 // Iterate over the region R and propagate the domain constrains from the
2596 // predecessors to the current node. In contrast to the
2597 // buildDomainsWithBranchConstraints function, this one will pull the domain
2598 // information from the predecessors instead of pushing it to the successors.
2599 // Additionally, we assume the domains to be already present in the domain
2600 // map here. However, we iterate again in reverse post order so we know all
2601 // predecessors have been visited before a block or non-affine subregion is
2602 // visited.
2603
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002604 ReversePostOrderTraversal<Region *> RTraversal(R);
2605 for (auto *RN : RTraversal) {
2606
2607 // Recurse for affine subregions but go on for basic blocks and non-affine
2608 // subregions.
2609 if (RN->isSubRegion()) {
2610 Region *SubRegion = RN->getNodeAs<Region>();
2611 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002612 propagateDomainConstraints(SubRegion, SD, DT, LI);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002613 continue;
2614 }
2615 }
2616
2617 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002618 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002619 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002620
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002621 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002622 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, SD, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002623 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002624 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002625
Johannes Doerfert642594a2016-04-04 07:57:39 +00002626 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002627 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002628 addLoopBoundsToHeaderDomain(BBLoop, LI);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002629
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002630 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002631 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002632 IsOptimized = true;
2633 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002634 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2635 AS_RESTRICTION);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002636 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002637 }
2638}
2639
2640/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2641/// is incremented by one and all other dimensions are equal, e.g.,
2642/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2643/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2644static __isl_give isl_map *
2645createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2646 auto *MapSpace = isl_space_map_from_set(SetSpace);
2647 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2648 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2649 if (u != Dim)
2650 NextIterationMap =
2651 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2652 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2653 C = isl_constraint_set_constant_si(C, 1);
2654 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2655 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2656 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2657 return NextIterationMap;
2658}
2659
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002660void Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002661 int LoopDepth = getRelativeLoopDepth(L);
2662 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002663
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002664 BasicBlock *HeaderBB = L->getHeader();
2665 assert(DomainMap.count(HeaderBB));
2666 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002667
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002668 isl_map *NextIterationMap =
2669 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002670
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002671 isl_set *UnionBackedgeCondition =
2672 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002673
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002674 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2675 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002676
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002677 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002678
2679 // If the latch is only reachable via error statements we skip it.
2680 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2681 if (!LatchBBDom)
2682 continue;
2683
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002684 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002685
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002686 TerminatorInst *TI = LatchBB->getTerminator();
2687 BranchInst *BI = dyn_cast<BranchInst>(TI);
2688 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002689 BackedgeCondition = isl_set_copy(LatchBBDom);
2690 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002691 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002692 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002693 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002694
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002695 // Free the non back edge condition set as we do not need it.
2696 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002697
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002698 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002699 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002700
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002701 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2702 assert(LatchLoopDepth >= LoopDepth);
2703 BackedgeCondition =
2704 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2705 LatchLoopDepth - LoopDepth);
2706 UnionBackedgeCondition =
2707 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002708 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002709
2710 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2711 for (int i = 0; i < LoopDepth; i++)
2712 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2713
2714 isl_set *UnionBackedgeConditionComplement =
2715 isl_set_complement(UnionBackedgeCondition);
2716 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2717 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2718 UnionBackedgeConditionComplement =
2719 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2720 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2721 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2722
2723 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2724 HeaderBBDom = Parts.second;
2725
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002726 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2727 // the bounded assumptions to the context as they are already implied by the
2728 // <nsw> tag.
2729 if (Affinator.hasNSWAddRecForLoop(L)) {
2730 isl_set_free(Parts.first);
2731 return;
2732 }
2733
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002734 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002735 recordAssumption(INFINITELOOP, UnboundedCtx,
2736 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002737}
2738
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002739void Scop::buildAliasChecks(AliasAnalysis &AA) {
2740 if (!PollyUseRuntimeAliasChecks)
2741 return;
2742
2743 if (buildAliasGroups(AA))
2744 return;
2745
2746 // If a problem occurs while building the alias groups we need to delete
2747 // this SCoP and pretend it wasn't valid in the first place. To this end
2748 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002749 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002750
2751 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2752 << " could not be created as the number of parameters involved "
2753 "is too high. The SCoP will be "
2754 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2755 "the maximal number of parameters but be advised that the "
2756 "compile time might increase exponentially.\n\n");
2757}
2758
Johannes Doerfert9143d672014-09-27 11:02:39 +00002759bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002760 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002761 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002762 // for all memory accesses inside the SCoP.
2763 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002764 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002765 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002766 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002767 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002768 // if their access domains intersect, otherwise they are in different
2769 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002770 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002771 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002772 // and maximal accesses to each array of a group in read only and non
2773 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002774 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2775
2776 AliasSetTracker AST(AA);
2777
2778 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002779 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002780 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002781
2782 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002783 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002784 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2785 isl_set_free(StmtDomain);
2786 if (StmtDomainEmpty)
2787 continue;
2788
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002789 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002790 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002791 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002792 if (!MA->isRead())
2793 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002794 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002795 if (MA->isRead() && isa<MemTransferInst>(Acc))
2796 PtrToAcc[cast<MemTransferInst>(Acc)->getSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002797 else
2798 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002799 AST.add(Acc);
2800 }
2801 }
2802
2803 SmallVector<AliasGroupTy, 4> AliasGroups;
2804 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002805 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002806 continue;
2807 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002808 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002809 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002810 if (AG.size() < 2)
2811 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002812 AliasGroups.push_back(std::move(AG));
2813 }
2814
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002815 // Split the alias groups based on their domain.
2816 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2817 AliasGroupTy NewAG;
2818 AliasGroupTy &AG = AliasGroups[u];
2819 AliasGroupTy::iterator AGI = AG.begin();
2820 isl_set *AGDomain = getAccessDomain(*AGI);
2821 while (AGI != AG.end()) {
2822 MemoryAccess *MA = *AGI;
2823 isl_set *MADomain = getAccessDomain(MA);
2824 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2825 NewAG.push_back(MA);
2826 AGI = AG.erase(AGI);
2827 isl_set_free(MADomain);
2828 } else {
2829 AGDomain = isl_set_union(AGDomain, MADomain);
2830 AGI++;
2831 }
2832 }
2833 if (NewAG.size() > 1)
2834 AliasGroups.push_back(std::move(NewAG));
2835 isl_set_free(AGDomain);
2836 }
2837
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002838 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002839 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002840 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2841 for (AliasGroupTy &AG : AliasGroups) {
2842 NonReadOnlyBaseValues.clear();
2843 ReadOnlyPairs.clear();
2844
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002845 if (AG.size() < 2) {
2846 AG.clear();
2847 continue;
2848 }
2849
Johannes Doerfert13771732014-10-01 12:40:46 +00002850 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002851 emitOptimizationRemarkAnalysis(
2852 F.getContext(), DEBUG_TYPE, F,
2853 (*II)->getAccessInstruction()->getDebugLoc(),
2854 "Possibly aliasing pointer, use restrict keyword.");
2855
Johannes Doerfert13771732014-10-01 12:40:46 +00002856 Value *BaseAddr = (*II)->getBaseAddr();
2857 if (HasWriteAccess.count(BaseAddr)) {
2858 NonReadOnlyBaseValues.insert(BaseAddr);
2859 II++;
2860 } else {
2861 ReadOnlyPairs[BaseAddr].insert(*II);
2862 II = AG.erase(II);
2863 }
2864 }
2865
2866 // If we don't have read only pointers check if there are at least two
2867 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002868 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002869 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002870 continue;
2871 }
2872
2873 // If we don't have non read only pointers clear the alias group.
2874 if (NonReadOnlyBaseValues.empty()) {
2875 AG.clear();
2876 continue;
2877 }
2878
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002879 // Check if we have non-affine accesses left, if so bail out as we cannot
2880 // generate a good access range yet.
2881 for (auto *MA : AG)
2882 if (!MA->isAffine()) {
2883 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2884 return false;
2885 }
2886 for (auto &ReadOnlyPair : ReadOnlyPairs)
2887 for (auto *MA : ReadOnlyPair.second)
2888 if (!MA->isAffine()) {
2889 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2890 return false;
2891 }
2892
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002893 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002894 MinMaxAliasGroups.emplace_back();
2895 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2896 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2897 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2898 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002899
2900 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002901
2902 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002903 for (MemoryAccess *MA : AG)
2904 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002905
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002906 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2907 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002908
2909 // Bail out if the number of values we need to compare is too large.
2910 // This is important as the number of comparisions grows quadratically with
2911 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002912 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2913 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002914 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002915
2916 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002917 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002918 Accesses = isl_union_map_empty(getParamSpace());
2919
2920 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2921 for (MemoryAccess *MA : ReadOnlyPair.second)
2922 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2923
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002924 Valid =
2925 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002926
2927 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002928 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002929 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002930
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002931 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002932}
2933
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002934/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002935static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002936 // Start with the smallest loop containing the entry and expand that
2937 // loop until it contains all blocks in the region. If there is a loop
2938 // containing all blocks in the region check if it is itself contained
2939 // and if so take the parent loop as it will be the smallest containing
2940 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002941 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002942 while (L) {
2943 bool AllContained = true;
2944 for (auto *BB : R.blocks())
2945 AllContained &= L->contains(BB);
2946 if (AllContained)
2947 break;
2948 L = L->getParentLoop();
2949 }
2950
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002951 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2952}
2953
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002954static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2955 ScopDetection &SD) {
2956
2957 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2958
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002959 unsigned MinLD = INT_MAX, MaxLD = 0;
2960 for (BasicBlock *BB : R.blocks()) {
2961 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002962 if (!R.contains(L))
2963 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002964 if (BoxedLoops && BoxedLoops->count(L))
2965 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002966 unsigned LD = L->getLoopDepth();
2967 MinLD = std::min(MinLD, LD);
2968 MaxLD = std::max(MaxLD, LD);
2969 }
2970 }
2971
2972 // Handle the case that there is no loop in the SCoP first.
2973 if (MaxLD == 0)
2974 return 1;
2975
2976 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2977 assert(MaxLD >= MinLD &&
2978 "Maximal loop depth was smaller than mininaml loop depth?");
2979 return MaxLD - MinLD + 1;
2980}
2981
Michael Kruse09eb4452016-03-03 22:10:47 +00002982Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
2983 unsigned MaxLoopDepth)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00002984 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002985 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002986 MaxLoopDepth(MaxLoopDepth), IslCtx(isl_ctx_alloc(), isl_ctx_free),
2987 Context(nullptr), Affinator(this, LI), AssumedContext(nullptr),
2988 InvalidContext(nullptr), Schedule(nullptr) {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002989 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00002990 buildContext();
2991}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002992
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002993void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002994 DominatorTree &DT, LoopInfo &LI) {
2995 addUserAssumptions(AC, DT, LI);
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002996 buildInvariantEquivalenceClasses(SD);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002997
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002998 if (!buildDomains(&R, SD, DT, LI))
2999 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003000
Michael Krusecac948e2015-10-02 13:53:07 +00003001 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003002 // Exit early in case there are no executable statements left in this scop.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003003 simplifySCoP(true, DT, LI);
Michael Kruseafe06702015-10-02 16:33:27 +00003004 if (Stmts.empty())
3005 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003006
Michael Krusecac948e2015-10-02 13:53:07 +00003007 // The ScopStmts now have enough information to initialize themselves.
3008 for (ScopStmt &Stmt : Stmts)
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003009 Stmt.init(SD);
Michael Krusecac948e2015-10-02 13:53:07 +00003010
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003011 buildSchedule(SD, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00003012
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003013 if (!hasFeasibleRuntimeContext())
Tobias Grosser8286b832015-11-02 11:29:32 +00003014 return;
3015
3016 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003017 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00003018 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003019 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003020
3021 // After the context was fully constructed, thus all our knowledge about
3022 // the parameters is in there, we add all recorded assumptions to the
3023 // assumed/invalid context.
3024 addRecordedAssumptions();
3025
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003026 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003027 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003028
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003029 hoistInvariantLoads(SD);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003030 verifyInvariantLoads(SD);
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003031 simplifySCoP(false, DT, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00003032}
3033
3034Scop::~Scop() {
3035 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003036 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003037 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003038 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003039
Johannes Doerfert96425c22015-08-30 21:13:53 +00003040 for (auto It : DomainMap)
3041 isl_set_free(It.second);
3042
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003043 for (auto &AS : RecordedAssumptions)
3044 isl_set_free(AS.Set);
3045
Johannes Doerfertb164c792014-09-18 11:17:17 +00003046 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003047 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003048 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003049 isl_pw_multi_aff_free(MMA.first);
3050 isl_pw_multi_aff_free(MMA.second);
3051 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003052 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003053 isl_pw_multi_aff_free(MMA.first);
3054 isl_pw_multi_aff_free(MMA.second);
3055 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003056 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003057
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003058 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003059 isl_set_free(std::get<2>(IAClass));
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003060
3061 // Explicitly release all Scop objects and the underlying isl objects before
3062 // we relase the isl context.
3063 Stmts.clear();
3064 ScopArrayInfoMap.clear();
3065 AccFuncMap.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003066}
3067
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003068void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003069 // Check all array accesses for each base pointer and find a (virtual) element
3070 // size for the base pointer that divides all access functions.
3071 for (auto &Stmt : *this)
3072 for (auto *Access : Stmt) {
3073 if (!Access->isArrayKind())
3074 continue;
3075 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
3076 ScopArrayInfo::MK_Array)];
3077 if (SAI->getNumberOfDimensions() != 1)
3078 continue;
3079 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3080 auto *Subscript = Access->getSubscript(0);
3081 while (!isDivisible(Subscript, DivisibleSize, *SE))
3082 DivisibleSize /= 2;
3083 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3084 SAI->updateElementType(Ty);
3085 }
3086
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003087 for (auto &Stmt : *this)
3088 for (auto &Access : Stmt)
3089 Access->updateDimensionality();
3090}
3091
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003092void Scop::simplifySCoP(bool RemoveIgnoredStmts, DominatorTree &DT,
3093 LoopInfo &LI) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003094 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3095 ScopStmt &Stmt = *StmtIt;
Michael Kruse7b5caa42016-02-24 22:08:28 +00003096 RegionNode *RN = Stmt.getRegionNode();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003097
Johannes Doerferteca9e892015-11-03 16:54:49 +00003098 bool RemoveStmt = StmtIt->isEmpty();
3099 if (!RemoveStmt)
Michael Kruse375cb5f2016-02-24 22:08:24 +00003100 RemoveStmt = isl_set_is_empty(DomainMap[Stmt.getEntryBlock()]);
Johannes Doerferteca9e892015-11-03 16:54:49 +00003101 if (!RemoveStmt)
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003102 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN, DT, LI));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003103
Johannes Doerferteca9e892015-11-03 16:54:49 +00003104 // Remove read only statements only after invariant loop hoisting.
3105 if (!RemoveStmt && !RemoveIgnoredStmts) {
3106 bool OnlyRead = true;
3107 for (MemoryAccess *MA : Stmt) {
3108 if (MA->isRead())
3109 continue;
3110
3111 OnlyRead = false;
3112 break;
3113 }
3114
3115 RemoveStmt = OnlyRead;
3116 }
3117
3118 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00003119 // Remove the statement because it is unnecessary.
3120 if (Stmt.isRegionStmt())
3121 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3122 StmtMap.erase(BB);
3123 else
3124 StmtMap.erase(Stmt.getBasicBlock());
3125
3126 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003127 continue;
3128 }
3129
Michael Krusecac948e2015-10-02 13:53:07 +00003130 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003131 }
3132}
3133
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003134const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
3135 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3136 if (!LInst)
3137 return nullptr;
3138
3139 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3140 LInst = cast<LoadInst>(Rep);
3141
Johannes Doerfert96e54712016-02-07 17:30:13 +00003142 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003143 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003144 for (auto &IAClass : InvariantEquivClasses) {
3145 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
3146 continue;
3147
3148 auto &MAs = std::get<1>(IAClass);
3149 for (auto *MA : MAs)
3150 if (MA->getAccessInstruction() == Val)
3151 return &IAClass;
3152 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003153
3154 return nullptr;
3155}
3156
3157void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
3158
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003159 // Get the context under which the statement is executed but remove the error
3160 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003161 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfert7c013572016-04-12 09:57:34 +00003162 DomainCtx = isl_set_subtract(DomainCtx, Stmt.getInvalidContext());
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003163 DomainCtx = isl_set_remove_redundancies(DomainCtx);
3164 DomainCtx = isl_set_detect_equalities(DomainCtx);
3165 DomainCtx = isl_set_coalesce(DomainCtx);
3166
3167 // Project out all parameters that relate to loads in the statement. Otherwise
3168 // we could have cyclic dependences on the constraints under which the
3169 // hoisted loads are executed and we could not determine an order in which to
3170 // pre-load them. This happens because not only lower bounds are part of the
3171 // domain but also upper bounds.
3172 for (MemoryAccess *MA : InvMAs) {
3173 Instruction *AccInst = MA->getAccessInstruction();
3174 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003175 SetVector<Value *> Values;
3176 for (const SCEV *Parameter : Parameters) {
3177 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003178 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003179 if (!Values.count(AccInst))
3180 continue;
3181
3182 if (isl_id *ParamId = getIdForParam(Parameter)) {
3183 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3184 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3185 isl_id_free(ParamId);
3186 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003187 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003188 }
3189 }
3190
3191 for (MemoryAccess *MA : InvMAs) {
3192 // Check for another invariant access that accesses the same location as
3193 // MA and if found consolidate them. Otherwise create a new equivalence
3194 // class at the end of InvariantEquivClasses.
3195 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003196 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003197 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3198
3199 bool Consolidated = false;
3200 for (auto &IAClass : InvariantEquivClasses) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00003201 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003202 continue;
3203
Johannes Doerfertdf880232016-03-03 12:26:58 +00003204 // If the pointer and the type is equal check if the access function wrt.
3205 // to the domain is equal too. It can happen that the domain fixes
3206 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003207 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003208 // create a new invariant load equivalence class.
3209 auto &MAs = std::get<1>(IAClass);
3210 if (!MAs.empty()) {
3211 auto *LastMA = MAs.front();
3212
3213 auto *AR = isl_map_range(MA->getAccessRelation());
3214 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3215 bool SameAR = isl_set_is_equal(AR, LastAR);
3216 isl_set_free(AR);
3217 isl_set_free(LastAR);
3218
3219 if (!SameAR)
3220 continue;
3221 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003222
3223 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003224 MAs.push_front(MA);
3225
Johannes Doerfertdf880232016-03-03 12:26:58 +00003226 Consolidated = true;
3227
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003228 // Unify the execution context of the class and this statement.
3229 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003230 if (IAClassDomainCtx)
3231 IAClassDomainCtx = isl_set_coalesce(
3232 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
3233 else
3234 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003235 break;
3236 }
3237
3238 if (Consolidated)
3239 continue;
3240
3241 // If we did not consolidate MA, thus did not find an equivalence class
3242 // for it, we create a new one.
3243 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
Johannes Doerfert96e54712016-02-07 17:30:13 +00003244 isl_set_copy(DomainCtx), Ty);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003245 }
3246
3247 isl_set_free(DomainCtx);
3248}
3249
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003250bool Scop::isHoistableAccess(MemoryAccess *Access,
3251 __isl_keep isl_union_map *Writes) {
3252 // TODO: Loads that are not loop carried, hence are in a statement with
3253 // zero iterators, are by construction invariant, though we
3254 // currently "hoist" them anyway. This is necessary because we allow
3255 // them to be treated as parameters (e.g., in conditions) and our code
3256 // generation would otherwise use the old value.
3257
3258 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003259 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003260
3261 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
3262 return false;
3263
3264 // Skip accesses that have an invariant base pointer which is defined but
3265 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3266 // returns a pointer that is used as a base address. However, as we want
3267 // to hoist indirect pointers, we allow the base pointer to be defined in
3268 // the region if it is also a memory access. Each ScopArrayInfo object
3269 // that has a base pointer origin has a base pointer that is loaded and
3270 // that it is invariant, thus it will be hoisted too. However, if there is
3271 // no base pointer origin we check that the base pointer is defined
3272 // outside the region.
3273 const ScopArrayInfo *SAI = Access->getScopArrayInfo();
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003274 auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr());
3275 if (SAI->getBasePtrOriginSAI()) {
3276 assert(BasePtrInst && R.contains(BasePtrInst));
3277 if (!isa<LoadInst>(BasePtrInst))
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003278 return false;
Michael Kruse6f7721f2016-02-24 22:08:19 +00003279 auto *BasePtrStmt = getStmtFor(BasePtrInst);
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003280 assert(BasePtrStmt);
3281 auto *BasePtrMA = BasePtrStmt->getArrayAccessOrNULLFor(BasePtrInst);
3282 if (BasePtrMA && !isHoistableAccess(BasePtrMA, Writes))
3283 return false;
3284 } else if (BasePtrInst && R.contains(BasePtrInst))
3285 return false;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003286
3287 // Skip accesses in non-affine subregions as they might not be executed
3288 // under the same condition as the entry of the non-affine subregion.
3289 if (BB != Access->getAccessInstruction()->getParent())
3290 return false;
3291
3292 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003293 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003294
3295 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3296 Stmt.getNumIterators())) {
3297 isl_map_free(AccessRelation);
3298 return false;
3299 }
3300
3301 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3302 isl_set *AccessRange = isl_map_range(AccessRelation);
3303
3304 isl_union_map *Written = isl_union_map_intersect_range(
3305 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
3306 bool IsWritten = !isl_union_map_is_empty(Written);
3307 isl_union_map_free(Written);
3308
3309 if (IsWritten)
3310 return false;
3311
3312 return true;
3313}
3314
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003315void Scop::verifyInvariantLoads(ScopDetection &SD) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003316 auto &RIL = *SD.getRequiredInvariantLoads(&getRegion());
3317 for (LoadInst *LI : RIL) {
3318 assert(LI && getRegion().contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003319 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003320 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003321 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3322 return;
3323 }
3324 }
3325}
3326
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003327void Scop::hoistInvariantLoads(ScopDetection &SD) {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003328 if (!PollyInvariantLoadHoisting)
3329 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003330
Tobias Grosser0865e7752016-02-29 07:29:42 +00003331 isl_union_map *Writes = getWrites();
3332 for (ScopStmt &Stmt : *this) {
3333 MemoryAccessList InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003334
Tobias Grosser0865e7752016-02-29 07:29:42 +00003335 for (MemoryAccess *Access : Stmt)
3336 if (isHoistableAccess(Access, Writes))
3337 InvariantAccesses.push_front(Access);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003338
Tobias Grosser0865e7752016-02-29 07:29:42 +00003339 // We inserted invariant accesses always in the front but need them to be
3340 // sorted in a "natural order". The statements are already sorted in
3341 // reverse post order and that suffices for the accesses too. The reason
3342 // we require an order in the first place is the dependences between
3343 // invariant loads that can be caused by indirect loads.
3344 InvariantAccesses.reverse();
3345
3346 // Transfer the memory access from the statement to the SCoP.
3347 Stmt.removeMemoryAccesses(InvariantAccesses);
3348 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003349 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003350 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003351}
3352
Johannes Doerfert80ef1102014-11-07 08:31:31 +00003353const ScopArrayInfo *
Tobias Grossercc779502016-02-02 13:22:54 +00003354Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003355 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003356 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003357 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003358 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003359 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003360 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003361 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003362 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003363 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003364 // In case of mismatching array sizes, we bail out by setting the run-time
3365 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003366 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003367 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003368 }
Tobias Grosserab671442015-05-23 05:58:27 +00003369 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003370}
3371
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003372const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003373 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003374 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003375 assert(SAI && "No ScopArrayInfo available for this base pointer");
3376 return SAI;
3377}
3378
Tobias Grosser74394f02013-01-14 22:40:23 +00003379std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003380
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003381std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003382 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003383 return stringFromIslObj(AssumedContext);
3384}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003385
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003386std::string Scop::getInvalidContextStr() const {
3387 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003388}
Tobias Grosser75805372011-04-29 06:27:02 +00003389
3390std::string Scop::getNameStr() const {
3391 std::string ExitName, EntryName;
3392 raw_string_ostream ExitStr(ExitName);
3393 raw_string_ostream EntryStr(EntryName);
3394
Tobias Grosserf240b482014-01-09 10:42:15 +00003395 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003396 EntryStr.str();
3397
3398 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003399 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003400 ExitStr.str();
3401 } else
3402 ExitName = "FunctionExit";
3403
3404 return EntryName + "---" + ExitName;
3405}
3406
Tobias Grosser74394f02013-01-14 22:40:23 +00003407__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003408__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003409 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003410}
3411
Tobias Grossere86109f2013-10-29 21:05:49 +00003412__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003413 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003414 return isl_set_copy(AssumedContext);
3415}
3416
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003417bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003418 auto *PositiveContext = getAssumedContext();
3419 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3420 bool IsFeasible = !isl_set_is_empty(PositiveContext);
3421 isl_set_free(PositiveContext);
3422 if (!IsFeasible)
3423 return false;
3424
3425 auto *NegativeContext = getInvalidContext();
3426 auto *DomainContext = isl_union_set_params(getDomains());
3427 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003428 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003429 isl_set_free(NegativeContext);
3430 isl_set_free(DomainContext);
3431
Johannes Doerfert43788c52015-08-20 05:58:56 +00003432 return IsFeasible;
3433}
3434
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003435static std::string toString(AssumptionKind Kind) {
3436 switch (Kind) {
3437 case ALIASING:
3438 return "No-aliasing";
3439 case INBOUNDS:
3440 return "Inbounds";
3441 case WRAPPING:
3442 return "No-overflows";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003443 case COMPLEXITY:
3444 return "Low complexity";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003445 case ERRORBLOCK:
3446 return "No-error";
3447 case INFINITELOOP:
3448 return "Finite loop";
3449 case INVARIANTLOAD:
3450 return "Invariant load";
3451 case DELINEARIZATION:
3452 return "Delinearization";
3453 }
3454 llvm_unreachable("Unknown AssumptionKind!");
3455}
3456
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003457bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3458 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert2f705842016-04-12 16:09:44 +00003459 if (PollyRemarksMinimal) {
3460 if (Sign == AS_ASSUMPTION) {
3461 if (isl_set_is_subset(Context, Set))
3462 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003463
Johannes Doerfert2f705842016-04-12 16:09:44 +00003464 if (isl_set_is_subset(AssumedContext, Set))
3465 return false;
3466 } else {
3467 if (isl_set_is_disjoint(Set, Context))
3468 return false;
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003469
Johannes Doerfert2f705842016-04-12 16:09:44 +00003470 if (isl_set_is_subset(Set, InvalidContext))
3471 return false;
3472 }
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003473 }
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003474
3475 auto &F = *getRegion().getEntry()->getParent();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003476 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3477 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003478 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003479 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003480}
3481
3482void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003483 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003484 // Simplify the assumptions/restrictions first.
3485 Set = isl_set_gist_params(Set, getContext());
3486
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003487 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3488 isl_set_free(Set);
3489 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003490 }
3491
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003492 if (Sign == AS_ASSUMPTION) {
3493 AssumedContext = isl_set_intersect(AssumedContext, Set);
3494 AssumedContext = isl_set_coalesce(AssumedContext);
3495 } else {
3496 InvalidContext = isl_set_union(InvalidContext, Set);
3497 InvalidContext = isl_set_coalesce(InvalidContext);
3498 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003499}
3500
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003501void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003502 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
3503 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003504}
3505
3506void Scop::addRecordedAssumptions() {
3507 while (!RecordedAssumptions.empty()) {
3508 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003509
3510 isl_set *S = AS.Set;
3511 // If a basic block was given use its domain to simplify the assumption.
3512 if (AS.BB)
3513 S = isl_set_params(isl_set_intersect(S, getDomainConditions(AS.BB)));
3514
3515 addAssumption(AS.Kind, S, AS.Loc, AS.Sign);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003516 }
3517}
3518
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003519void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003520 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003521}
3522
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003523__isl_give isl_set *Scop::getInvalidContext() const {
3524 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003525}
3526
Tobias Grosser75805372011-04-29 06:27:02 +00003527void Scop::printContext(raw_ostream &OS) const {
3528 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003529 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003530
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003531 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003532 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003533
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003534 OS.indent(4) << "Invalid Context:\n";
3535 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003536
Tobias Grosser083d3d32014-06-28 08:59:45 +00003537 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003538 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003539 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3540 }
Tobias Grosser75805372011-04-29 06:27:02 +00003541}
3542
Johannes Doerfertb164c792014-09-18 11:17:17 +00003543void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003544 int noOfGroups = 0;
3545 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003546 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003547 noOfGroups += 1;
3548 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003549 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003550 }
3551
Tobias Grosserbb853c22015-07-25 12:31:03 +00003552 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003553 if (MinMaxAliasGroups.empty()) {
3554 OS.indent(8) << "n/a\n";
3555 return;
3556 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003557
Tobias Grosserbb853c22015-07-25 12:31:03 +00003558 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003559
3560 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003561 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003562 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003563 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003564 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3565 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003566 }
3567 OS << " ]]\n";
3568 }
3569
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003570 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003571 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003572 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003573 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003574 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3575 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003576 }
3577 OS << " ]]\n";
3578 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003579 }
3580}
3581
Tobias Grosser75805372011-04-29 06:27:02 +00003582void Scop::printStatements(raw_ostream &OS) const {
3583 OS << "Statements {\n";
3584
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003585 for (const ScopStmt &Stmt : *this)
3586 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003587
3588 OS.indent(4) << "}\n";
3589}
3590
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003591void Scop::printArrayInfo(raw_ostream &OS) const {
3592 OS << "Arrays {\n";
3593
Tobias Grosserab671442015-05-23 05:58:27 +00003594 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003595 Array.second->print(OS);
3596
3597 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003598
3599 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3600
3601 for (auto &Array : arrays())
3602 Array.second->print(OS, /* SizeAsPwAff */ true);
3603
3604 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003605}
3606
Tobias Grosser75805372011-04-29 06:27:02 +00003607void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003608 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3609 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003610 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003611 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003612 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003613 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003614 const auto &MAs = std::get<1>(IAClass);
3615 if (MAs.empty()) {
3616 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003617 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003618 MAs.front()->print(OS);
3619 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003620 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003621 }
3622 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003623 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003624 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003625 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003626 printStatements(OS.indent(4));
3627}
3628
3629void Scop::dump() const { print(dbgs()); }
3630
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003631isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003632
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003633__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003634 // First try to use the SCEVAffinator to generate a piecewise defined
3635 // affine function from @p E in the context of @p BB. If that tasks becomes to
3636 // complex the affinator might return a nullptr. In such a case we invalidate
3637 // the SCoP and return a dummy value. This way we do not need to add error
3638 // handling cdoe to all users of this function.
3639 auto *PWA = Affinator.getPwAff(E, BB);
3640 if (PWA)
3641 return PWA;
3642
3643 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
3644 invalidate(COMPLEXITY, DL);
3645 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003646}
3647
Tobias Grosser808cd692015-07-14 09:33:13 +00003648__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003649 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003650
Tobias Grosser808cd692015-07-14 09:33:13 +00003651 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003652 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003653
3654 return Domain;
3655}
3656
Tobias Grossere5a35142015-11-12 14:07:09 +00003657__isl_give isl_union_map *
3658Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3659 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003660
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003661 for (ScopStmt &Stmt : *this) {
3662 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003663 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003664 continue;
3665
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003666 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003667 isl_map *AccessDomain = MA->getAccessRelation();
3668 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003669 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003670 }
3671 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003672 return isl_union_map_coalesce(Accesses);
3673}
3674
3675__isl_give isl_union_map *Scop::getMustWrites() {
3676 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003677}
3678
3679__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003680 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003681}
3682
Tobias Grosser37eb4222014-02-20 21:43:54 +00003683__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003684 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003685}
3686
3687__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003688 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003689}
3690
Tobias Grosser2ac23382015-11-12 14:07:13 +00003691__isl_give isl_union_map *Scop::getAccesses() {
3692 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3693}
3694
Tobias Grosser808cd692015-07-14 09:33:13 +00003695__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003696 auto *Tree = getScheduleTree();
3697 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00003698 isl_schedule_free(Tree);
3699 return S;
3700}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003701
Tobias Grosser808cd692015-07-14 09:33:13 +00003702__isl_give isl_schedule *Scop::getScheduleTree() const {
3703 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3704 getDomains());
3705}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003706
Tobias Grosser808cd692015-07-14 09:33:13 +00003707void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3708 auto *S = isl_schedule_from_domain(getDomains());
3709 S = isl_schedule_insert_partial_schedule(
3710 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3711 isl_schedule_free(Schedule);
3712 Schedule = S;
3713}
3714
3715void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3716 isl_schedule_free(Schedule);
3717 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003718}
3719
3720bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3721 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003722 for (ScopStmt &Stmt : *this) {
3723 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003724 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3725 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3726
3727 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3728 isl_union_set_free(StmtDomain);
3729 isl_union_set_free(NewStmtDomain);
3730 continue;
3731 }
3732
3733 Changed = true;
3734
3735 isl_union_set_free(StmtDomain);
3736 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3737
3738 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003739 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003740 isl_union_set_free(NewStmtDomain);
3741 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003742 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003743 }
3744 isl_union_set_free(Domain);
3745 return Changed;
3746}
3747
Tobias Grosser75805372011-04-29 06:27:02 +00003748ScalarEvolution *Scop::getSE() const { return SE; }
3749
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003750bool Scop::isIgnored(RegionNode *RN, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003751 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Kruse6f7721f2016-02-24 22:08:19 +00003752 ScopStmt *Stmt = getStmtFor(RN);
Michael Krusea902ba62015-12-13 19:21:45 +00003753
3754 // If there is no stmt, then it already has been removed.
3755 if (!Stmt)
3756 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00003757
Johannes Doerfertf5673802015-10-01 23:48:18 +00003758 // Check if there are accesses contained.
Michael Krusea902ba62015-12-13 19:21:45 +00003759 if (Stmt->isEmpty())
Johannes Doerfertf5673802015-10-01 23:48:18 +00003760 return true;
3761
3762 // Check for reachability via non-error blocks.
3763 if (!DomainMap.count(BB))
3764 return true;
3765
3766 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003767 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003768 return true;
3769
3770 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003771}
3772
Tobias Grosser808cd692015-07-14 09:33:13 +00003773struct MapToDimensionDataTy {
3774 int N;
3775 isl_union_pw_multi_aff *Res;
3776};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003777
Tobias Grosser808cd692015-07-14 09:33:13 +00003778// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003779// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003780//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003781// @param Set The input set.
3782// @param User->N The dimension to map to.
3783// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003784//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003785// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003786static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3787 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3788 int Dim;
3789 isl_space *Space;
3790 isl_pw_multi_aff *PMA;
3791
3792 Dim = isl_set_dim(Set, isl_dim_set);
3793 Space = isl_set_get_space(Set);
3794 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3795 Dim - Data->N);
3796 if (Data->N > 1)
3797 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3798 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3799
3800 isl_set_free(Set);
3801
3802 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003803}
3804
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003805// @brief Create an isl_multi_union_aff that defines an identity mapping
3806// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003807//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003808// # Example:
3809//
3810// Domain: { A[i,j]; B[i,j,k] }
3811// N: 1
3812//
3813// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
3814//
3815// @param USet A union set describing the elements for which to generate a
3816// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00003817// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003818// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003819static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003820mapToDimension(__isl_take isl_union_set *USet, int N) {
3821 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00003822 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003823 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003824
Tobias Grosser808cd692015-07-14 09:33:13 +00003825 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00003826
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003827 auto *Space = isl_union_set_get_space(USet);
3828 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00003829
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003830 Data = {N, PwAff};
3831
3832 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00003833 (void)Res;
3834
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003835 assert(Res == isl_stat_ok);
3836
3837 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00003838 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3839}
3840
Tobias Grosser316b5b22015-11-11 19:28:14 +00003841void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003842 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003843 Stmts.emplace_back(*this, *BB);
Johannes Doerferta90943d2016-02-21 16:37:25 +00003844 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003845 StmtMap[BB] = Stmt;
3846 } else {
3847 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003848 Stmts.emplace_back(*this, *R);
Johannes Doerferta90943d2016-02-21 16:37:25 +00003849 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003850 for (BasicBlock *BB : R->blocks())
3851 StmtMap[BB] = Stmt;
3852 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003853}
3854
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003855void Scop::buildSchedule(ScopDetection &SD, LoopInfo &LI) {
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003856 Loop *L = getLoopSurroundingRegion(getRegion(), LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003857 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003858 buildSchedule(getRegion().getNode(), LoopStack, SD, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00003859 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
3860 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003861}
3862
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003863/// To generate a schedule for the elements in a Region we traverse the Region
3864/// in reverse-post-order and add the contained RegionNodes in traversal order
3865/// to the schedule of the loop that is currently at the top of the LoopStack.
3866/// For loop-free codes, this results in a correct sequential ordering.
3867///
3868/// Example:
3869/// bb1(0)
3870/// / \.
3871/// bb2(1) bb3(2)
3872/// \ / \.
3873/// bb4(3) bb5(4)
3874/// \ /
3875/// bb6(5)
3876///
3877/// Including loops requires additional processing. Whenever a loop header is
3878/// encountered, the corresponding loop is added to the @p LoopStack. Starting
3879/// from an empty schedule, we first process all RegionNodes that are within
3880/// this loop and complete the sequential schedule at this loop-level before
3881/// processing about any other nodes. To implement this
3882/// loop-nodes-first-processing, the reverse post-order traversal is
3883/// insufficient. Hence, we additionally check if the traversal yields
3884/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
3885/// These region-nodes are then queue and only traverse after the all nodes
3886/// within the current loop have been processed.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003887void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, ScopDetection &SD,
3888 LoopInfo &LI) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003889 Loop *OuterScopLoop = getLoopSurroundingRegion(getRegion(), LI);
3890
3891 ReversePostOrderTraversal<Region *> RTraversal(R);
3892 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
3893 std::deque<RegionNode *> DelayList;
3894 bool LastRNWaiting = false;
3895
3896 // Iterate over the region @p R in reverse post-order but queue
3897 // sub-regions/blocks iff they are not part of the last encountered but not
3898 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
3899 // that we queued the last sub-region/block from the reverse post-order
3900 // iterator. If it is set we have to explore the next sub-region/block from
3901 // the iterator (if any) to guarantee progress. If it is not set we first try
3902 // the next queued sub-region/blocks.
3903 while (!WorkList.empty() || !DelayList.empty()) {
3904 RegionNode *RN;
3905
3906 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
3907 RN = WorkList.front();
3908 WorkList.pop_front();
3909 LastRNWaiting = false;
3910 } else {
3911 RN = DelayList.front();
3912 DelayList.pop_front();
3913 }
3914
3915 Loop *L = getRegionNodeLoop(RN, LI);
3916 if (!getRegion().contains(L))
3917 L = OuterScopLoop;
3918
Tobias Grosser151ae322016-04-03 19:36:52 +00003919 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003920 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00003921 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003922 LastRNWaiting = true;
3923 DelayList.push_back(RN);
3924 continue;
3925 }
3926 LoopStack.push_back({L, nullptr, 0});
3927 }
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003928 buildSchedule(RN, LoopStack, SD, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003929 }
3930
3931 return;
3932}
3933
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003934void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003935 ScopDetection &SD, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00003936
Tobias Grosser8362c262016-01-06 15:30:06 +00003937 if (RN->isSubRegion()) {
3938 auto *LocalRegion = RN->getNodeAs<Region>();
3939 if (!SD.isNonAffineSubRegion(LocalRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003940 buildSchedule(LocalRegion, LoopStack, SD, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00003941 return;
3942 }
3943 }
Michael Kruse046dde42015-08-10 13:01:57 +00003944
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003945 auto &LoopData = LoopStack.back();
3946 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00003947
Michael Kruse6f7721f2016-02-24 22:08:19 +00003948 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00003949 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3950 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003951 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00003952 }
3953
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003954 // Check if we just processed the last node in this loop. If we did, finalize
3955 // the loop by:
3956 //
3957 // - adding new schedule dimensions
3958 // - folding the resulting schedule into the parent loop schedule
3959 // - dropping the loop schedule from the LoopStack.
3960 //
3961 // Then continue to check surrounding loops, which might also have been
3962 // completed by this node.
3963 while (LoopData.L &&
3964 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003965 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003966 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00003967
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003968 LoopStack.pop_back();
3969 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00003970
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003971 if (Schedule) {
3972 auto *Domain = isl_schedule_get_domain(Schedule);
3973 auto *MUPA = mapToDimension(Domain, LoopStack.size());
3974 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
3975 NextLoopData.Schedule =
3976 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003977 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003978
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003979 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
3980 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00003981 }
Tobias Grosser75805372011-04-29 06:27:02 +00003982}
3983
Michael Kruse6f7721f2016-02-24 22:08:19 +00003984ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003985 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003986 if (StmtMapIt == StmtMap.end())
3987 return nullptr;
3988 return StmtMapIt->second;
3989}
3990
Michael Kruse6f7721f2016-02-24 22:08:19 +00003991ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
3992 if (RN->isSubRegion())
3993 return getStmtFor(RN->getNodeAs<Region>());
3994 return getStmtFor(RN->getNodeAs<BasicBlock>());
3995}
3996
3997ScopStmt *Scop::getStmtFor(Region *R) const {
3998 ScopStmt *Stmt = getStmtFor(R->getEntry());
3999 assert(!Stmt || Stmt->getRegion() == R);
4000 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004001}
4002
Johannes Doerfert96425c22015-08-30 21:13:53 +00004003int Scop::getRelativeLoopDepth(const Loop *L) const {
4004 Loop *OuterLoop =
4005 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4006 if (!OuterLoop)
4007 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004008 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4009}
4010
Michael Krused868b5d2015-09-10 15:25:24 +00004011void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00004012 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00004013
4014 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
4015 // true, are not modeled as ordinary PHI nodes as they are not part of the
4016 // region. However, we model the operands in the predecessor blocks that are
4017 // part of the region as regular scalar accesses.
4018
4019 // If we can synthesize a PHI we can skip it, however only if it is in
4020 // the region. If it is not it can only be in the exit block of the region.
4021 // In this case we model the operands but not the PHI itself.
Michael Krusec7e0d9c2016-03-01 21:44:06 +00004022 auto *Scope = LI->getLoopFor(PHI->getParent());
4023 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R, Scope))
Michael Kruse7bf39442015-09-10 12:46:52 +00004024 return;
4025
4026 // PHI nodes are modeled as if they had been demoted prior to the SCoP
4027 // detection. Hence, the PHI is a load of a new memory location in which the
4028 // incoming value was written at the end of the incoming basic block.
4029 bool OnlyNonAffineSubRegionOperands = true;
4030 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
4031 Value *Op = PHI->getIncomingValue(u);
4032 BasicBlock *OpBB = PHI->getIncomingBlock(u);
4033
4034 // Do not build scalar dependences inside a non-affine subregion.
4035 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
4036 continue;
4037
4038 OnlyNonAffineSubRegionOperands = false;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004039 ensurePHIWrite(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00004040 }
4041
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004042 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
4043 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00004044 }
4045}
4046
Michael Kruse2e02d562016-02-06 09:19:40 +00004047void ScopInfo::buildScalarDependences(Instruction *Inst) {
4048 assert(!isa<PHINode>(Inst));
Michael Kruse7bf39442015-09-10 12:46:52 +00004049
Michael Kruse2e02d562016-02-06 09:19:40 +00004050 // Pull-in required operands.
4051 for (Use &Op : Inst->operands())
4052 ensureValueRead(Op.get(), Inst->getParent());
4053}
Michael Kruse7bf39442015-09-10 12:46:52 +00004054
Michael Kruse2e02d562016-02-06 09:19:40 +00004055void ScopInfo::buildEscapingDependences(Instruction *Inst) {
4056 Region *R = &scop->getRegion();
Michael Kruse7bf39442015-09-10 12:46:52 +00004057
Michael Kruse2e02d562016-02-06 09:19:40 +00004058 // Check for uses of this instruction outside the scop. Because we do not
4059 // iterate over such instructions and therefore did not "ensure" the existence
4060 // of a write, we must determine such use here.
4061 for (Use &U : Inst->uses()) {
4062 Instruction *UI = dyn_cast<Instruction>(U.getUser());
4063 if (!UI)
Michael Kruse7bf39442015-09-10 12:46:52 +00004064 continue;
4065
Michael Kruse2e02d562016-02-06 09:19:40 +00004066 BasicBlock *UseParent = getUseBlock(U);
4067 BasicBlock *UserParent = UI->getParent();
Michael Kruse7bf39442015-09-10 12:46:52 +00004068
Michael Kruse2e02d562016-02-06 09:19:40 +00004069 // An escaping value is either used by an instruction not within the scop,
4070 // or (when the scop region's exit needs to be simplified) by a PHI in the
4071 // scop's exit block. This is because region simplification before code
4072 // generation inserts new basic blocks before the PHI such that its incoming
4073 // blocks are not in the scop anymore.
4074 if (!R->contains(UseParent) ||
4075 (isa<PHINode>(UI) && UserParent == R->getExit() &&
4076 R->getExitingBlock())) {
4077 // At least one escaping use found.
4078 ensureValueWrite(Inst);
4079 break;
Michael Kruse7bf39442015-09-10 12:46:52 +00004080 }
4081 }
Michael Kruse7bf39442015-09-10 12:46:52 +00004082}
4083
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004084bool ScopInfo::buildAccessMultiDimFixed(
Michael Kruse70131d32016-01-27 17:09:17 +00004085 MemAccInst Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00004086 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4087 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse70131d32016-01-27 17:09:17 +00004088 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004089 Type *ElementType = Val->getType();
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004090 Value *Address = Inst.getPointerOperand();
Tobias Grosser5fd8c092015-09-17 17:28:15 +00004091 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00004092 const SCEVUnknown *BasePointer =
4093 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004094 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004095 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00004096
Michael Kruse37d136e2016-02-26 16:08:24 +00004097 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
4098 auto *Src = BitCast->getOperand(0);
4099 auto *SrcTy = Src->getType();
4100 auto *DstTy = BitCast->getType();
Johannes Doerfert41725a12016-04-08 19:20:03 +00004101 // Do not try to delinearize non-sized (opaque) pointers.
4102 if ((SrcTy->isPointerTy() && !SrcTy->getPointerElementType()->isSized()) ||
4103 (DstTy->isPointerTy() && !DstTy->getPointerElementType()->isSized())) {
4104 return false;
4105 }
Michael Kruse436c9062016-04-08 16:20:08 +00004106 if (SrcTy->isPointerTy() && DstTy->isPointerTy() &&
4107 DL->getTypeAllocSize(SrcTy->getPointerElementType()) ==
4108 DL->getTypeAllocSize(DstTy->getPointerElementType()))
Michael Kruse37d136e2016-02-26 16:08:24 +00004109 Address = Src;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00004110 }
Michael Kruse37d136e2016-02-26 16:08:24 +00004111
4112 auto *GEP = dyn_cast<GetElementPtrInst>(Address);
4113 if (!GEP)
4114 return false;
4115
4116 std::vector<const SCEV *> Subscripts;
4117 std::vector<int> Sizes;
4118 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
4119 auto *BasePtr = GEP->getOperand(0);
4120
Tobias Grosser535afd82016-04-05 06:23:45 +00004121 if (auto *BasePtrCast = dyn_cast<BitCastInst>(BasePtr))
4122 BasePtr = BasePtrCast->getOperand(0);
4123
4124 // Check for identical base pointers to ensure that we do not miss index
4125 // offsets that have been added before this GEP is applied.
4126 if (BasePtr != BasePointer->getValue())
4127 return false;
4128
Michael Kruse37d136e2016-02-26 16:08:24 +00004129 std::vector<const SCEV *> SizesSCEV;
4130
4131 for (auto *Subscript : Subscripts) {
4132 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +00004133 if (!isAffineExpr(R, L, Subscript, *SE, nullptr, &AccessILS))
Michael Kruse37d136e2016-02-26 16:08:24 +00004134 return false;
4135
4136 for (LoadInst *LInst : AccessILS)
4137 if (!ScopRIL.count(LInst))
4138 return false;
4139 }
4140
4141 if (Sizes.empty())
4142 return false;
4143
4144 for (auto V : Sizes)
4145 SizesSCEV.push_back(SE->getSCEV(
4146 ConstantInt::get(IntegerType::getInt64Ty(BasePtr->getContext()), V)));
4147
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004148 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, true,
Michael Kruse37d136e2016-02-26 16:08:24 +00004149 Subscripts, SizesSCEV, Val);
4150 return true;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004151}
4152
4153bool ScopInfo::buildAccessMultiDimParam(
4154 MemAccInst Inst, Loop *L, Region *R,
4155 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00004156 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Michael Kruse37d136e2016-02-26 16:08:24 +00004157 if (!PollyDelinearize)
4158 return false;
4159
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004160 Value *Address = Inst.getPointerOperand();
4161 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004162 Type *ElementType = Val->getType();
4163 unsigned ElementSize = DL->getTypeAllocSize(ElementType);
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004164 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004165 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004166
4167 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
4168 const SCEVUnknown *BasePointer =
4169 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
4170
4171 assert(BasePointer && "Could not find base pointer");
4172 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00004173
Michael Kruse7bf39442015-09-10 12:46:52 +00004174 auto AccItr = InsnToMemAcc.find(Inst);
Michael Kruse37d136e2016-02-26 16:08:24 +00004175 if (AccItr == InsnToMemAcc.end())
4176 return false;
Tobias Grosser5d51afe2016-02-02 16:46:45 +00004177
Michael Kruse37d136e2016-02-26 16:08:24 +00004178 std::vector<const SCEV *> Sizes(
4179 AccItr->second.Shape->DelinearizedSizes.begin(),
4180 AccItr->second.Shape->DelinearizedSizes.end());
4181 // Remove the element size. This information is already provided by the
4182 // ElementSize parameter. In case the element size of this access and the
4183 // element size used for delinearization differs the delinearization is
4184 // incorrect. Hence, we invalidate the scop.
4185 //
4186 // TODO: Handle delinearization with differing element sizes.
4187 auto DelinearizedSize =
4188 cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue();
4189 Sizes.pop_back();
4190 if (ElementSize != DelinearizedSize)
4191 scop->invalidate(DELINEARIZATION, Inst->getDebugLoc());
4192
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004193 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, true,
Michael Kruse37d136e2016-02-26 16:08:24 +00004194 AccItr->second.DelinearizedSubscripts, Sizes, Val);
4195 return true;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004196}
4197
Johannes Doerfertcea61932016-02-21 19:13:19 +00004198bool ScopInfo::buildAccessMemIntrinsic(
4199 MemAccInst Inst, Loop *L, Region *R,
4200 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4201 const InvariantLoadsSetTy &ScopRIL) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004202 auto *MemIntr = dyn_cast_or_null<MemIntrinsic>(Inst);
4203
4204 if (MemIntr == nullptr)
Johannes Doerfertcea61932016-02-21 19:13:19 +00004205 return false;
4206
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004207 auto *LengthVal = SE->getSCEVAtScope(MemIntr->getLength(), L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00004208 assert(LengthVal);
4209
Johannes Doerferta7920982016-02-25 14:08:48 +00004210 // Check if the length val is actually affine or if we overapproximate it
4211 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +00004212 bool LengthIsAffine = isAffineExpr(R, L, LengthVal, *SE, nullptr, &AccessILS);
Johannes Doerferta7920982016-02-25 14:08:48 +00004213 for (LoadInst *LInst : AccessILS)
4214 if (!ScopRIL.count(LInst))
4215 LengthIsAffine = false;
4216 if (!LengthIsAffine)
4217 LengthVal = nullptr;
4218
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004219 auto *DestPtrVal = MemIntr->getDest();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004220 assert(DestPtrVal);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004221
Johannes Doerfertcea61932016-02-21 19:13:19 +00004222 auto *DestAccFunc = SE->getSCEVAtScope(DestPtrVal, L);
4223 assert(DestAccFunc);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004224 // Ignore accesses to "NULL".
4225 // TODO: We could use this to optimize the region further, e.g., intersect
4226 // the context with
4227 // isl_set_complement(isl_set_params(getDomain()))
4228 // as we know it would be undefined to execute this instruction anyway.
4229 if (DestAccFunc->isZero())
4230 return true;
4231
Johannes Doerfertcea61932016-02-21 19:13:19 +00004232 auto *DestPtrSCEV = dyn_cast<SCEVUnknown>(SE->getPointerBase(DestAccFunc));
4233 assert(DestPtrSCEV);
4234 DestAccFunc = SE->getMinusSCEV(DestAccFunc, DestPtrSCEV);
4235 addArrayAccess(Inst, MemoryAccess::MUST_WRITE, DestPtrSCEV->getValue(),
4236 IntegerType::getInt8Ty(DestPtrVal->getContext()), false,
4237 {DestAccFunc, LengthVal}, {}, Inst.getValueOperand());
4238
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004239 auto *MemTrans = dyn_cast<MemTransferInst>(MemIntr);
4240 if (!MemTrans)
Johannes Doerfertcea61932016-02-21 19:13:19 +00004241 return true;
4242
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004243 auto *SrcPtrVal = MemTrans->getSource();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004244 assert(SrcPtrVal);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004245
Johannes Doerfertcea61932016-02-21 19:13:19 +00004246 auto *SrcAccFunc = SE->getSCEVAtScope(SrcPtrVal, L);
4247 assert(SrcAccFunc);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004248 // Ignore accesses to "NULL".
4249 // TODO: See above TODO
4250 if (SrcAccFunc->isZero())
4251 return true;
4252
Johannes Doerfertcea61932016-02-21 19:13:19 +00004253 auto *SrcPtrSCEV = dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccFunc));
4254 assert(SrcPtrSCEV);
4255 SrcAccFunc = SE->getMinusSCEV(SrcAccFunc, SrcPtrSCEV);
4256 addArrayAccess(Inst, MemoryAccess::READ, SrcPtrSCEV->getValue(),
4257 IntegerType::getInt8Ty(SrcPtrVal->getContext()), false,
4258 {SrcAccFunc, LengthVal}, {}, Inst.getValueOperand());
4259
4260 return true;
4261}
4262
Johannes Doerferta7920982016-02-25 14:08:48 +00004263bool ScopInfo::buildAccessCallInst(
4264 MemAccInst Inst, Loop *L, Region *R,
4265 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4266 const InvariantLoadsSetTy &ScopRIL) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004267 auto *CI = dyn_cast_or_null<CallInst>(Inst);
4268
4269 if (CI == nullptr)
Johannes Doerferta7920982016-02-25 14:08:48 +00004270 return false;
4271
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004272 if (CI->doesNotAccessMemory() || isIgnoredIntrinsic(CI))
Johannes Doerferta7920982016-02-25 14:08:48 +00004273 return true;
4274
4275 bool ReadOnly = false;
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004276 auto *AF = SE->getConstant(IntegerType::getInt64Ty(CI->getContext()), 0);
4277 auto *CalledFunction = CI->getCalledFunction();
Johannes Doerferta7920982016-02-25 14:08:48 +00004278 switch (AA->getModRefBehavior(CalledFunction)) {
4279 case llvm::FMRB_UnknownModRefBehavior:
4280 llvm_unreachable("Unknown mod ref behaviour cannot be represented.");
4281 case llvm::FMRB_DoesNotAccessMemory:
4282 return true;
4283 case llvm::FMRB_OnlyReadsMemory:
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004284 GlobalReads.push_back(CI);
Johannes Doerferta7920982016-02-25 14:08:48 +00004285 return true;
4286 case llvm::FMRB_OnlyReadsArgumentPointees:
4287 ReadOnly = true;
4288 // Fall through
4289 case llvm::FMRB_OnlyAccessesArgumentPointees:
4290 auto AccType = ReadOnly ? MemoryAccess::READ : MemoryAccess::MAY_WRITE;
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004291 for (const auto &Arg : CI->arg_operands()) {
Johannes Doerferta7920982016-02-25 14:08:48 +00004292 if (!Arg->getType()->isPointerTy())
4293 continue;
4294
4295 auto *ArgSCEV = SE->getSCEVAtScope(Arg, L);
4296 if (ArgSCEV->isZero())
4297 continue;
4298
4299 auto *ArgBasePtr = cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
4300 addArrayAccess(Inst, AccType, ArgBasePtr->getValue(),
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004301 ArgBasePtr->getType(), false, {AF}, {}, CI);
Johannes Doerferta7920982016-02-25 14:08:48 +00004302 }
4303 return true;
4304 }
4305
4306 return true;
4307}
4308
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004309void ScopInfo::buildAccessSingleDim(
4310 MemAccInst Inst, Loop *L, Region *R,
4311 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4312 const InvariantLoadsSetTy &ScopRIL) {
4313 Value *Address = Inst.getPointerOperand();
4314 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004315 Type *ElementType = Val->getType();
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004316 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004317 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004318
4319 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
4320 const SCEVUnknown *BasePointer =
4321 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
4322
4323 assert(BasePointer && "Could not find base pointer");
4324 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Michael Kruse7bf39442015-09-10 12:46:52 +00004325
4326 // Check if the access depends on a loop contained in a non-affine subregion.
4327 bool isVariantInNonAffineLoop = false;
4328 if (BoxedLoops) {
4329 SetVector<const Loop *> Loops;
4330 findLoops(AccessFunction, Loops);
4331 for (const Loop *L : Loops)
4332 if (BoxedLoops->count(L))
4333 isVariantInNonAffineLoop = true;
4334 }
4335
Johannes Doerfert09e36972015-10-07 20:17:36 +00004336 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +00004337 bool IsAffine = !isVariantInNonAffineLoop &&
4338 isAffineExpr(R, L, AccessFunction, *SE,
4339 BasePointer->getValue(), &AccessILS);
Johannes Doerfert09e36972015-10-07 20:17:36 +00004340
4341 for (LoadInst *LInst : AccessILS)
4342 if (!ScopRIL.count(LInst))
4343 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00004344
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004345 if (!IsAffine && AccType == MemoryAccess::MUST_WRITE)
4346 AccType = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00004347
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004348 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, IsAffine,
Tobias Grosser5d51afe2016-02-02 16:46:45 +00004349 {AccessFunction}, {}, Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00004350}
4351
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004352void ScopInfo::buildMemoryAccess(
4353 MemAccInst Inst, Loop *L, Region *R,
4354 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00004355 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004356
Johannes Doerfertcea61932016-02-21 19:13:19 +00004357 if (buildAccessMemIntrinsic(Inst, L, R, BoxedLoops, ScopRIL))
4358 return;
4359
Johannes Doerferta7920982016-02-25 14:08:48 +00004360 if (buildAccessCallInst(Inst, L, R, BoxedLoops, ScopRIL))
4361 return;
4362
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004363 if (buildAccessMultiDimFixed(Inst, L, R, BoxedLoops, ScopRIL))
4364 return;
4365
Hongbin Zheng22623202016-02-15 00:20:58 +00004366 if (buildAccessMultiDimParam(Inst, L, R, BoxedLoops, ScopRIL, InsnToMemAcc))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004367 return;
4368
4369 buildAccessSingleDim(Inst, L, R, BoxedLoops, ScopRIL);
4370}
4371
Hongbin Zheng22623202016-02-15 00:20:58 +00004372void ScopInfo::buildAccessFunctions(Region &R, Region &SR,
4373 const MapInsnToMemAcc &InsnToMemAcc) {
Michael Kruse7bf39442015-09-10 12:46:52 +00004374
4375 if (SD->isNonAffineSubRegion(&SR, &R)) {
4376 for (BasicBlock *BB : SR.blocks())
Hongbin Zheng22623202016-02-15 00:20:58 +00004377 buildAccessFunctions(R, *BB, InsnToMemAcc, &SR);
Michael Kruse7bf39442015-09-10 12:46:52 +00004378 return;
4379 }
4380
4381 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4382 if (I->isSubRegion())
Hongbin Zheng22623202016-02-15 00:20:58 +00004383 buildAccessFunctions(R, *I->getNodeAs<Region>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004384 else
Hongbin Zheng22623202016-02-15 00:20:58 +00004385 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004386}
4387
Johannes Doerferta8781032016-02-02 14:14:40 +00004388void ScopInfo::buildStmts(Region &R, Region &SR) {
Michael Krusecac948e2015-10-02 13:53:07 +00004389
Johannes Doerferta8781032016-02-02 14:14:40 +00004390 if (SD->isNonAffineSubRegion(&SR, &R)) {
Michael Krusecac948e2015-10-02 13:53:07 +00004391 scop->addScopStmt(nullptr, &SR);
4392 return;
4393 }
4394
4395 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4396 if (I->isSubRegion())
Johannes Doerferta8781032016-02-02 14:14:40 +00004397 buildStmts(R, *I->getNodeAs<Region>());
Michael Krusecac948e2015-10-02 13:53:07 +00004398 else
4399 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
4400}
4401
Michael Krused868b5d2015-09-10 15:25:24 +00004402void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
Hongbin Zheng22623202016-02-15 00:20:58 +00004403 const MapInsnToMemAcc &InsnToMemAcc,
Michael Krused868b5d2015-09-10 15:25:24 +00004404 Region *NonAffineSubRegion,
4405 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00004406 // We do not build access functions for error blocks, as they may contain
4407 // instructions we can not model.
Johannes Doerfertc36d39b2016-02-02 14:14:20 +00004408 if (isErrorBlock(BB, R, *LI, *DT) && !IsExitBlock)
Tobias Grosser910cf262015-11-11 20:15:49 +00004409 return;
4410
Michael Kruse7bf39442015-09-10 12:46:52 +00004411 Loop *L = LI->getLoopFor(&BB);
4412
4413 // The set of loops contained in non-affine subregions that are part of R.
4414 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
4415
Johannes Doerfert09e36972015-10-07 20:17:36 +00004416 // The set of loads that are required to be invariant.
4417 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
4418
Michael Kruse2e02d562016-02-06 09:19:40 +00004419 for (Instruction &Inst : BB) {
4420 PHINode *PHI = dyn_cast<PHINode>(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004421 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00004422 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00004423
4424 // For the exit block we stop modeling after the last PHI node.
4425 if (!PHI && IsExitBlock)
4426 break;
4427
Johannes Doerfert09e36972015-10-07 20:17:36 +00004428 // TODO: At this point we only know that elements of ScopRIL have to be
4429 // invariant and will be hoisted for the SCoP to be processed. Though,
4430 // there might be other invariant accesses that will be hoisted and
4431 // that would allow to make a non-affine access affine.
Michael Kruse70131d32016-01-27 17:09:17 +00004432 if (auto MemInst = MemAccInst::dyn_cast(Inst))
Hongbin Zheng22623202016-02-15 00:20:58 +00004433 buildMemoryAccess(MemInst, L, &R, BoxedLoops, ScopRIL, InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004434
Michael Kruse2e02d562016-02-06 09:19:40 +00004435 if (isIgnoredIntrinsic(&Inst))
Michael Kruse7bf39442015-09-10 12:46:52 +00004436 continue;
4437
Tobias Grosser0904c692016-03-16 23:33:54 +00004438 // PHI nodes have already been modeled above and TerminatorInsts that are
4439 // not part of a non-affine subregion are fully modeled and regenerated
4440 // from the polyhedral domains. Hence, they do not need to be modeled as
4441 // explicit data dependences.
4442 if (!PHI && (!isa<TerminatorInst>(&Inst) || NonAffineSubRegion))
Michael Kruse2e02d562016-02-06 09:19:40 +00004443 buildScalarDependences(&Inst);
Tobias Grosser0904c692016-03-16 23:33:54 +00004444
Michael Kruse2e02d562016-02-06 09:19:40 +00004445 if (!IsExitBlock)
4446 buildEscapingDependences(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004447 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00004448}
Michael Kruse7bf39442015-09-10 12:46:52 +00004449
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004450MemoryAccess *ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004451 MemoryAccess::AccessType AccType,
4452 Value *BaseAddress, Type *ElementType,
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004453 bool Affine, Value *AccessValue,
4454 ArrayRef<const SCEV *> Subscripts,
4455 ArrayRef<const SCEV *> Sizes,
4456 ScopArrayInfo::MemoryKind Kind) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004457 ScopStmt *Stmt = scop->getStmtFor(BB);
Michael Krusecac948e2015-10-02 13:53:07 +00004458
4459 // Do not create a memory access for anything not in the SCoP. It would be
4460 // ignored anyway.
4461 if (!Stmt)
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004462 return nullptr;
Michael Krusecac948e2015-10-02 13:53:07 +00004463
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00004464 AccFuncSetType &AccList = scop->getOrCreateAccessFunctions(BB);
Michael Krusee2bccbb2015-09-18 19:59:43 +00004465 Value *BaseAddr = BaseAddress;
4466 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
4467
Tobias Grosserf4f68702015-12-14 15:05:37 +00004468 bool isKnownMustAccess = false;
4469
4470 // Accesses in single-basic block statements are always excuted.
4471 if (Stmt->isBlockStmt())
4472 isKnownMustAccess = true;
4473
4474 if (Stmt->isRegionStmt()) {
4475 // Accesses that dominate the exit block of a non-affine region are always
4476 // executed. In non-affine regions there may exist MK_Values that do not
4477 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs
4478 // only if there is at most one PHI_WRITE in the non-affine region.
4479 if (DT->dominates(BB, Stmt->getRegion()->getExit()))
4480 isKnownMustAccess = true;
4481 }
4482
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004483 // Non-affine PHI writes do not "happen" at a particular instruction, but
4484 // after exiting the statement. Therefore they are guaranteed execute and
4485 // overwrite the old value.
4486 if (Kind == ScopArrayInfo::MK_PHI || Kind == ScopArrayInfo::MK_ExitPHI)
4487 isKnownMustAccess = true;
4488
Johannes Doerfertcea61932016-02-21 19:13:19 +00004489 if (!isKnownMustAccess && AccType == MemoryAccess::MUST_WRITE)
4490 AccType = MemoryAccess::MAY_WRITE;
Michael Krusecac948e2015-10-02 13:53:07 +00004491
Johannes Doerfertcea61932016-02-21 19:13:19 +00004492 AccList.emplace_back(Stmt, Inst, AccType, BaseAddress, ElementType, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00004493 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00004494 Stmt->addAccess(&AccList.back());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004495 return &AccList.back();
Michael Kruse7bf39442015-09-10 12:46:52 +00004496}
4497
Michael Kruse70131d32016-01-27 17:09:17 +00004498void ScopInfo::addArrayAccess(MemAccInst MemAccInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004499 MemoryAccess::AccessType AccType,
4500 Value *BaseAddress, Type *ElementType,
4501 bool IsAffine, ArrayRef<const SCEV *> Subscripts,
Tobias Grossera535dff2015-12-13 19:59:01 +00004502 ArrayRef<const SCEV *> Sizes,
4503 Value *AccessValue) {
Johannes Doerferta7920982016-02-25 14:08:48 +00004504 ArrayBasePointers.insert(BaseAddress);
Hongbin Zhengf3d66122016-02-26 09:47:11 +00004505 addMemoryAccess(MemAccInst->getParent(), MemAccInst, AccType, BaseAddress,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004506 ElementType, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00004507 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004508}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004509
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004510void ScopInfo::ensureValueWrite(Instruction *Inst) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004511 ScopStmt *Stmt = scop->getStmtFor(Inst);
Michael Kruse436db622016-01-26 13:33:10 +00004512
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004513 // Inst not defined within this SCoP.
Michael Kruse436db622016-01-26 13:33:10 +00004514 if (!Stmt)
4515 return;
4516
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004517 // Do not process further if the instruction is already written.
4518 if (Stmt->lookupValueWriteOf(Inst))
Michael Kruse436db622016-01-26 13:33:10 +00004519 return;
4520
Johannes Doerfertcea61932016-02-21 19:13:19 +00004521 addMemoryAccess(Inst->getParent(), Inst, MemoryAccess::MUST_WRITE, Inst,
4522 Inst->getType(), true, Inst, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004523 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004524}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004525
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004526void ScopInfo::ensureValueRead(Value *V, BasicBlock *UserBB) {
Michael Krusefd463082016-01-27 22:51:56 +00004527
Michael Kruse2e02d562016-02-06 09:19:40 +00004528 // There cannot be an "access" for literal constants. BasicBlock references
4529 // (jump destinations) also never change.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004530 if ((isa<Constant>(V) && !isa<GlobalVariable>(V)) || isa<BasicBlock>(V))
Michael Kruse2e02d562016-02-06 09:19:40 +00004531 return;
4532
Michael Krusefd463082016-01-27 22:51:56 +00004533 // If the instruction can be synthesized and the user is in the region we do
4534 // not need to add a value dependences.
4535 Region &ScopRegion = scop->getRegion();
Michael Krusec7e0d9c2016-03-01 21:44:06 +00004536 auto *Scope = LI->getLoopFor(UserBB);
4537 if (canSynthesize(V, LI, SE, &ScopRegion, Scope))
Michael Krusefd463082016-01-27 22:51:56 +00004538 return;
4539
Michael Kruse2e02d562016-02-06 09:19:40 +00004540 // Do not build scalar dependences for required invariant loads as we will
4541 // hoist them later on anyway or drop the SCoP if we cannot.
Johannes Doerferta90943d2016-02-21 16:37:25 +00004542 auto *ScopRIL = SD->getRequiredInvariantLoads(&ScopRegion);
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004543 if (ScopRIL->count(dyn_cast<LoadInst>(V)))
Michael Kruse2e02d562016-02-06 09:19:40 +00004544 return;
4545
4546 // Determine the ScopStmt containing the value's definition and use. There is
4547 // no defining ScopStmt if the value is a function argument, a global value,
4548 // or defined outside the SCoP.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004549 Instruction *ValueInst = dyn_cast<Instruction>(V);
Michael Kruse6f7721f2016-02-24 22:08:19 +00004550 ScopStmt *ValueStmt = ValueInst ? scop->getStmtFor(ValueInst) : nullptr;
Michael Kruse2e02d562016-02-06 09:19:40 +00004551
Michael Kruse6f7721f2016-02-24 22:08:19 +00004552 ScopStmt *UserStmt = scop->getStmtFor(UserBB);
Michael Krusead28e5a2016-01-26 13:33:15 +00004553
4554 // We do not model uses outside the scop.
4555 if (!UserStmt)
4556 return;
4557
Michael Kruse2e02d562016-02-06 09:19:40 +00004558 // Add MemoryAccess for invariant values only if requested.
4559 if (!ModelReadOnlyScalars && !ValueStmt)
4560 return;
4561
4562 // Ignore use-def chains within the same ScopStmt.
4563 if (ValueStmt == UserStmt)
4564 return;
4565
Michael Krusead28e5a2016-01-26 13:33:15 +00004566 // Do not create another MemoryAccess for reloading the value if one already
4567 // exists.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004568 if (UserStmt->lookupValueReadOf(V))
Michael Krusead28e5a2016-01-26 13:33:15 +00004569 return;
4570
Johannes Doerfert2075b5d2016-04-03 11:16:00 +00004571 // For exit PHIs use the MK_ExitPHI MemoryKind not MK_Value.
4572 ScopArrayInfo::MemoryKind Kind = ScopArrayInfo::MK_Value;
4573 if (!ValueStmt && isa<PHINode>(V))
4574 Kind = ScopArrayInfo::MK_ExitPHI;
4575
Johannes Doerfertcea61932016-02-21 19:13:19 +00004576 addMemoryAccess(UserBB, nullptr, MemoryAccess::READ, V, V->getType(), true, V,
Johannes Doerfert2075b5d2016-04-03 11:16:00 +00004577 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(), Kind);
Michael Kruse2e02d562016-02-06 09:19:40 +00004578 if (ValueInst)
4579 ensureValueWrite(ValueInst);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004580}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004581
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004582void ScopInfo::ensurePHIWrite(PHINode *PHI, BasicBlock *IncomingBlock,
4583 Value *IncomingValue, bool IsExitBlock) {
Johannes Doerfert57c5f0b2016-04-05 13:44:21 +00004584 // As the incoming block might turn out to be an error statement ensure we
4585 // will create an exit PHI SAI object. It is needed during code generation
4586 // and would be created later anyway.
4587 if (IsExitBlock)
4588 scop->getOrCreateScopArrayInfo(PHI, PHI->getType(), {},
4589 ScopArrayInfo::MK_ExitPHI);
4590
Michael Kruse6f7721f2016-02-24 22:08:19 +00004591 ScopStmt *IncomingStmt = scop->getStmtFor(IncomingBlock);
Michael Kruse2e02d562016-02-06 09:19:40 +00004592 if (!IncomingStmt)
4593 return;
4594
4595 // Take care for the incoming value being available in the incoming block.
4596 // This must be done before the check for multiple PHI writes because multiple
4597 // exiting edges from subregion each can be the effective written value of the
4598 // subregion. As such, all of them must be made available in the subregion
4599 // statement.
4600 ensureValueRead(IncomingValue, IncomingBlock);
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004601
4602 // Do not add more than one MemoryAccess per PHINode and ScopStmt.
4603 if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) {
4604 assert(Acc->getAccessInstruction() == PHI);
4605 Acc->addIncoming(IncomingBlock, IncomingValue);
4606 return;
4607 }
4608
4609 MemoryAccess *Acc = addMemoryAccess(
Michael Kruse375cb5f2016-02-24 22:08:24 +00004610 IncomingStmt->getEntryBlock(), PHI, MemoryAccess::MUST_WRITE, PHI,
4611 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4612 ArrayRef<const SCEV *>(),
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004613 IsExitBlock ? ScopArrayInfo::MK_ExitPHI : ScopArrayInfo::MK_PHI);
4614 assert(Acc);
4615 Acc->addIncoming(IncomingBlock, IncomingValue);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004616}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004617
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004618void ScopInfo::addPHIReadAccess(PHINode *PHI) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00004619 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI,
4620 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4621 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004622}
4623
Michael Krusedaf66942015-12-13 22:10:37 +00004624void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00004625 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Michael Kruse09eb4452016-03-03 22:10:47 +00004626 scop.reset(new Scop(R, *SE, *LI, MaxLoopDepth));
Michael Kruse7bf39442015-09-10 12:46:52 +00004627
Johannes Doerferta8781032016-02-02 14:14:40 +00004628 buildStmts(R, R);
Hongbin Zheng22623202016-02-15 00:20:58 +00004629 buildAccessFunctions(R, R, *SD->getInsnToMemAccMap(&R));
Michael Kruse7bf39442015-09-10 12:46:52 +00004630
4631 // In case the region does not have an exiting block we will later (during
4632 // code generation) split the exit block. This will move potential PHI nodes
4633 // from the current exit block into the new region exiting block. Hence, PHI
4634 // nodes that are at this point not part of the region will be.
4635 // To handle these PHI nodes later we will now model their operands as scalar
4636 // accesses. Note that we do not model anything in the exit block if we have
4637 // an exiting block in the region, as there will not be any splitting later.
4638 if (!R.getExitingBlock())
Hongbin Zheng22623202016-02-15 00:20:58 +00004639 buildAccessFunctions(R, *R.getExit(), *SD->getInsnToMemAccMap(&R), nullptr,
4640 /* IsExitBlock */ true);
Michael Kruse7bf39442015-09-10 12:46:52 +00004641
Johannes Doerferta7920982016-02-25 14:08:48 +00004642 // Create memory accesses for global reads since all arrays are now known.
4643 auto *AF = SE->getConstant(IntegerType::getInt64Ty(SE->getContext()), 0);
4644 for (auto *GlobalRead : GlobalReads)
4645 for (auto *BP : ArrayBasePointers)
4646 addArrayAccess(MemAccInst(GlobalRead), MemoryAccess::READ, BP,
4647 BP->getType(), false, {AF}, {}, GlobalRead);
4648
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004649 scop->init(*AA, AC, *SD, *DT, *LI);
Michael Kruse7bf39442015-09-10 12:46:52 +00004650}
4651
Michael Krused868b5d2015-09-10 15:25:24 +00004652void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00004653 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00004654 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00004655 return;
4656 }
4657
Michael Kruse9d080092015-09-11 21:41:48 +00004658 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00004659}
4660
Hongbin Zhengfec32802016-02-13 15:13:02 +00004661void ScopInfo::clear() { scop.reset(); }
Michael Kruse7bf39442015-09-10 12:46:52 +00004662
4663//===----------------------------------------------------------------------===//
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004664ScopInfo::ScopInfo() : RegionPass(ID) {}
Tobias Grosserb76f38532011-08-20 11:11:25 +00004665
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004666ScopInfo::~ScopInfo() { clear(); }
Tobias Grosserb76f38532011-08-20 11:11:25 +00004667
Tobias Grosser75805372011-04-29 06:27:02 +00004668void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00004669 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00004670 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00004671 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00004672 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4673 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004674 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004675 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00004676 AU.setPreservesAll();
4677}
4678
4679bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004680 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004681
Michael Krused868b5d2015-09-10 15:25:24 +00004682 if (!SD->isMaxRegionInScop(*R))
4683 return false;
4684
4685 Function *F = R->getEntry()->getParent();
4686 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4687 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4688 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Johannes Doerferta1f291e2016-02-02 14:15:13 +00004689 DL = &F->getParent()->getDataLayout();
Michael Krusedaf66942015-12-13 22:10:37 +00004690 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004691 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004692
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004693 DebugLoc Beg, End;
4694 getDebugLocations(R, Beg, End);
4695 std::string Msg = "SCoP begins here.";
4696 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4697
Michael Krusedaf66942015-12-13 22:10:37 +00004698 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004699
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004700 DEBUG(scop->print(dbgs()));
4701
Michael Kruseafe06702015-10-02 16:33:27 +00004702 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004703 Msg = "SCoP ends here but was dismissed.";
Hongbin Zhengfec32802016-02-13 15:13:02 +00004704 scop.reset();
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004705 } else {
4706 Msg = "SCoP ends here.";
4707 ++ScopFound;
4708 if (scop->getMaxLoopDepth() > 0)
4709 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004710 }
4711
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004712 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4713
Tobias Grosser75805372011-04-29 06:27:02 +00004714 return false;
4715}
4716
4717char ScopInfo::ID = 0;
4718
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004719Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4720
Tobias Grosser73600b82011-10-08 00:30:40 +00004721INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4722 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004723 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004724INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004725INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004726INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004727INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004728INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004729INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004730INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004731INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4732 "Polly - Create polyhedral description of Scops", false,
4733 false)