blob: 1243272d2e7af7af9d1699031eb0818c97931a41 [file] [log] [blame]
Johannes Doerfert58a7c752015-09-28 09:48:53 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser5624d3c2015-12-21 12:38:56 +000020#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000021#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000022#include "polly/Options.h"
Tobias Grosser75805372011-04-29 06:27:02 +000023#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000024#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000025#include "polly/Support/ScopHelper.h"
Tobias Grosser9737c7b2015-11-22 11:06:51 +000026#include "llvm/ADT/DepthFirstIterator.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000027#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000028#include "llvm/ADT/PostOrderIterator.h"
29#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000030#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000031#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000032#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000033#include "llvm/Analysis/AliasAnalysis.h"
Johannes Doerfert2af10e22015-11-12 03:25:01 +000034#include "llvm/Analysis/AssumptionCache.h"
Johannes Doerfert1dc12af2016-04-23 12:59:18 +000035#include "llvm/Analysis/Loads.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000036#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000037#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000038#include "llvm/Analysis/RegionIterator.h"
39#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000040#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000041#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000042#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000043#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000044#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000045#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000046#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000047#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000048#include "isl/schedule.h"
49#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000050#include "isl/set.h"
51#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000052#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000053#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000054#include <sstream>
55#include <string>
56#include <vector>
57
58using namespace llvm;
59using namespace polly;
60
Chandler Carruth95fef942014-04-22 03:30:19 +000061#define DEBUG_TYPE "polly-scops"
62
Tobias Grosser74394f02013-01-14 22:40:23 +000063STATISTIC(ScopFound, "Number of valid Scops");
64STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000065
Tobias Grosser75dc40c2015-12-20 13:31:48 +000066// The maximal number of basic sets we allow during domain construction to
67// be created. More complex scops will result in very high compile time and
68// are also unlikely to result in good code
69static int const MaxConjunctsInDomain = 20;
70
Johannes Doerfert2f705842016-04-12 16:09:44 +000071static cl::opt<bool> PollyRemarksMinimal(
72 "polly-remarks-minimal",
73 cl::desc("Do not emit remarks about assumptions that are known"),
74 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
75
Michael Kruse7bf39442015-09-10 12:46:52 +000076static cl::opt<bool> ModelReadOnlyScalars(
77 "polly-analyze-read-only-scalars",
78 cl::desc("Model read-only scalar values in the scop description"),
79 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
80
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000081// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000082// operations can overflow easily. Additive reductions and bit operations
83// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000084static cl::opt<bool> DisableMultiplicativeReductions(
85 "polly-disable-multiplicative-reductions",
86 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
87 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000088
Johannes Doerfert9143d672014-09-27 11:02:39 +000089static cl::opt<unsigned> RunTimeChecksMaxParameters(
90 "polly-rtc-max-parameters",
91 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
92 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
93
Tobias Grosser71500722015-03-28 15:11:14 +000094static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
95 "polly-rtc-max-arrays-per-group",
96 cl::desc("The maximal number of arrays to compare in each alias group."),
97 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000098static cl::opt<std::string> UserContextStr(
99 "polly-context", cl::value_desc("isl parameter set"),
100 cl::desc("Provide additional constraints on the context parameters"),
101 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000102
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000103static cl::opt<bool> DetectReductions("polly-detect-reductions",
104 cl::desc("Detect and exploit reductions"),
105 cl::Hidden, cl::ZeroOrMore,
106 cl::init(true), cl::cat(PollyCategory));
107
Michael Kruse7bf39442015-09-10 12:46:52 +0000108//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000109
Michael Kruse046dde42015-08-10 13:01:57 +0000110// Create a sequence of two schedules. Either argument may be null and is
111// interpreted as the empty schedule. Can also return null if both schedules are
112// empty.
113static __isl_give isl_schedule *
114combineInSequence(__isl_take isl_schedule *Prev,
115 __isl_take isl_schedule *Succ) {
116 if (!Prev)
117 return Succ;
118 if (!Succ)
119 return Prev;
120
121 return isl_schedule_sequence(Prev, Succ);
122}
123
Johannes Doerferte7044942015-02-24 11:58:30 +0000124static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
125 const ConstantRange &Range,
126 int dim,
127 enum isl_dim_type type) {
128 isl_val *V;
129 isl_ctx *ctx = isl_set_get_ctx(S);
130
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000131 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
132 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000133 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000134 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
135
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000136 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000137 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000138 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000139 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000140 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
141
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000142 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000143 return isl_set_union(SLB, SUB);
144 else
145 return isl_set_intersect(SLB, SUB);
146}
147
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000148static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
149 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
150 if (!BasePtrLI)
151 return nullptr;
152
153 if (!S->getRegion().contains(BasePtrLI))
154 return nullptr;
155
156 ScalarEvolution &SE = *S->getSE();
157
158 auto *OriginBaseSCEV =
159 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
160 if (!OriginBaseSCEV)
161 return nullptr;
162
163 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
164 if (!OriginBaseSCEVUnknown)
165 return nullptr;
166
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000167 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000168 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000169}
170
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000171ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000172 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000173 const DataLayout &DL, Scop *S)
174 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000175 std::string BasePtrName =
Tobias Grossera535dff2015-12-13 19:59:01 +0000176 getIslCompatibleName("MemRef_", BasePtr, Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000177 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000178
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000179 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000180 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
181 if (BasePtrOriginSAI)
182 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000183}
184
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000185__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000186 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000187 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
188 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
189 return Space;
190}
191
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000192void ScopArrayInfo::updateElementType(Type *NewElementType) {
193 if (NewElementType == ElementType)
194 return;
195
Tobias Grosserd840fc72016-02-04 13:18:42 +0000196 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
197 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
198
Johannes Doerferta7920982016-02-25 14:08:48 +0000199 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000200 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000201
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000202 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
203 ElementType = NewElementType;
204 } else {
205 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
206 ElementType = IntegerType::get(ElementType->getContext(), GCD);
207 }
208}
209
210bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000211 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
212 int ExtraDimsNew = NewSizes.size() - SharedDims;
213 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000214 for (int i = 0; i < SharedDims; i++)
215 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
216 return false;
217
218 if (DimensionSizes.size() >= NewSizes.size())
219 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000220
221 DimensionSizes.clear();
222 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
223 NewSizes.end());
224 for (isl_pw_aff *Size : DimensionSizesPw)
225 isl_pw_aff_free(Size);
226 DimensionSizesPw.clear();
227 for (const SCEV *Expr : DimensionSizes) {
228 isl_pw_aff *Size = S.getPwAff(Expr);
229 DimensionSizesPw.push_back(Size);
230 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000231 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000232}
233
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000234ScopArrayInfo::~ScopArrayInfo() {
235 isl_id_free(Id);
236 for (isl_pw_aff *Size : DimensionSizesPw)
237 isl_pw_aff_free(Size);
238}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000239
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000240std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
241
242int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000243 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000244}
245
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000246__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
247 return isl_id_copy(Id);
248}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000249
250void ScopArrayInfo::dump() const { print(errs()); }
251
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000252void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000253 OS.indent(8) << *getElementType() << " " << getName();
254 if (getNumberOfDimensions() > 0)
255 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000256 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000257 OS << "[";
258
Tobias Grosser26253842015-11-10 14:24:21 +0000259 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000260 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000261 OS << " " << Size << " ";
262 isl_pw_aff_free(Size);
263 } else {
264 OS << *getDimensionSize(u);
265 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000266
267 OS << "]";
268 }
269
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000270 OS << ";";
271
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000272 if (BasePtrOriginSAI)
273 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
274
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000275 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000276}
277
278const ScopArrayInfo *
279ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
280 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
281 assert(Id && "Output dimension didn't have an ID");
282 return getFromId(Id);
283}
284
285const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
286 void *User = isl_id_get_user(Id);
287 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
288 isl_id_free(Id);
289 return SAI;
290}
291
Michael Kruse3b425ff2016-04-11 14:34:08 +0000292void MemoryAccess::wrapConstantDimensions() {
293 auto *SAI = getScopArrayInfo();
294 auto *ArraySpace = SAI->getSpace();
295 auto *Ctx = isl_space_get_ctx(ArraySpace);
296 unsigned DimsArray = SAI->getNumberOfDimensions();
297
298 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
299 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
300 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
301
302 // Begin with last dimension, to iteratively carry into higher dimensions.
303 for (int i = DimsArray - 1; i > 0; i--) {
304 auto *DimSize = SAI->getDimensionSize(i);
305 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
306
307 // This transformation is not applicable to dimensions with dynamic size.
308 if (!DimSizeCst)
309 continue;
310
311 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
312 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
313 isl_dim_set, i);
314 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
315 isl_dim_set, i - 1);
316
317 // Compute: index % size
318 // Modulo must apply in the divide of the previous iteration, if any.
319 auto *Modulo = isl_aff_copy(Var);
320 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
321 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
322
323 // Compute: floor(index / size)
324 auto *Divide = Var;
325 Divide = isl_aff_div(
326 Divide,
327 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
328 Divide = isl_aff_floor(Divide);
329 Divide = isl_aff_add(Divide, PrevVar);
330 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
331
332 // Apply Modulo and Divide.
333 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
334 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
335 }
336
337 // Apply all modulo/divides on the accesses.
338 AccessRelation =
339 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
340 AccessRelation = isl_map_detect_equalities(AccessRelation);
341 isl_local_space_free(LArraySpace);
342}
343
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000344void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000345 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000346 auto *ArraySpace = SAI->getSpace();
347 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000348 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000349
350 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
351 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
352 auto DimsMissing = DimsArray - DimsAccess;
353
Michael Kruse375cb5f2016-02-24 22:08:24 +0000354 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000355 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000356 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000357 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000358
Johannes Doerferta90943d2016-02-21 16:37:25 +0000359 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000360 isl_set_universe(AccessSpace),
361 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000362
363 for (unsigned i = 0; i < DimsMissing; i++)
364 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
365
366 for (unsigned i = DimsMissing; i < DimsArray; i++)
367 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
368
369 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000370
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000371 // For the non delinearized arrays, divide the access function of the last
372 // subscript by the size of the elements in the array.
373 //
374 // A stride one array access in C expressed as A[i] is expressed in
375 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
376 // two subsequent values of 'i' index two values that are stored next to
377 // each other in memory. By this division we make this characteristic
378 // obvious again. If the base pointer was accessed with offsets not divisible
379 // by the accesses element size, we will have choosen a smaller ArrayElemSize
380 // that divides the offsets of all accesses to this base pointer.
381 if (DimsAccess == 1) {
382 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
383 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
384 }
385
Michael Kruse3b425ff2016-04-11 14:34:08 +0000386 // We currently do this only if we added at least one dimension, which means
387 // some dimension's indices have not been specified, an indicator that some
388 // index values have been added together.
389 // TODO: Investigate general usefulness; Effect on unit tests is to make index
390 // expressions more complicated.
391 if (DimsMissing)
392 wrapConstantDimensions();
393
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000394 if (!isAffine())
395 computeBoundsOnAccessRelation(ArrayElemSize);
396
Tobias Grosserd840fc72016-02-04 13:18:42 +0000397 // Introduce multi-element accesses in case the type loaded by this memory
398 // access is larger than the canonical element type of the array.
399 //
400 // An access ((float *)A)[i] to an array char *A is modeled as
401 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000402 if (ElemBytes > ArrayElemSize) {
403 assert(ElemBytes % ArrayElemSize == 0 &&
404 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000405 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000406 isl_set_universe(isl_space_copy(ArraySpace)),
407 isl_set_universe(isl_space_copy(ArraySpace)));
408 for (unsigned i = 0; i < DimsArray - 1; i++)
409 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
410
Tobias Grosserd840fc72016-02-04 13:18:42 +0000411 isl_constraint *C;
412 isl_local_space *LS;
413
414 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000415 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
416
417 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
418 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000419 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000420 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
421 Map = isl_map_add_constraint(Map, C);
422
423 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000424 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000425 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
426 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
427 Map = isl_map_add_constraint(Map, C);
428 AccessRelation = isl_map_apply_range(AccessRelation, Map);
429 }
430
431 isl_space_free(ArraySpace);
432
Roman Gareev10595a12016-01-08 14:01:59 +0000433 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000434}
435
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000436const std::string
437MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
438 switch (RT) {
439 case MemoryAccess::RT_NONE:
440 llvm_unreachable("Requested a reduction operator string for a memory "
441 "access which isn't a reduction");
442 case MemoryAccess::RT_ADD:
443 return "+";
444 case MemoryAccess::RT_MUL:
445 return "*";
446 case MemoryAccess::RT_BOR:
447 return "|";
448 case MemoryAccess::RT_BXOR:
449 return "^";
450 case MemoryAccess::RT_BAND:
451 return "&";
452 }
453 llvm_unreachable("Unknown reduction type");
454 return "";
455}
456
Johannes Doerfertf6183392014-07-01 20:52:51 +0000457/// @brief Return the reduction type for a given binary operator
458static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
459 const Instruction *Load) {
460 if (!BinOp)
461 return MemoryAccess::RT_NONE;
462 switch (BinOp->getOpcode()) {
463 case Instruction::FAdd:
464 if (!BinOp->hasUnsafeAlgebra())
465 return MemoryAccess::RT_NONE;
466 // Fall through
467 case Instruction::Add:
468 return MemoryAccess::RT_ADD;
469 case Instruction::Or:
470 return MemoryAccess::RT_BOR;
471 case Instruction::Xor:
472 return MemoryAccess::RT_BXOR;
473 case Instruction::And:
474 return MemoryAccess::RT_BAND;
475 case Instruction::FMul:
476 if (!BinOp->hasUnsafeAlgebra())
477 return MemoryAccess::RT_NONE;
478 // Fall through
479 case Instruction::Mul:
480 if (DisableMultiplicativeReductions)
481 return MemoryAccess::RT_NONE;
482 return MemoryAccess::RT_MUL;
483 default:
484 return MemoryAccess::RT_NONE;
485 }
486}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000487
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000488/// @brief Derive the individual index expressions from a GEP instruction
489///
490/// This function optimistically assumes the GEP references into a fixed size
491/// array. If this is actually true, this function returns a list of array
492/// subscript expressions as SCEV as well as a list of integers describing
493/// the size of the individual array dimensions. Both lists have either equal
494/// length of the size list is one element shorter in case there is no known
495/// size available for the outermost array dimension.
496///
497/// @param GEP The GetElementPtr instruction to analyze.
498///
499/// @return A tuple with the subscript expressions and the dimension sizes.
500static std::tuple<std::vector<const SCEV *>, std::vector<int>>
501getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
502 std::vector<const SCEV *> Subscripts;
503 std::vector<int> Sizes;
504
505 Type *Ty = GEP->getPointerOperandType();
506
507 bool DroppedFirstDim = false;
508
Michael Kruse26ed65e2015-09-24 17:32:49 +0000509 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000510
511 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
512
513 if (i == 1) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000514 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000515 Ty = PtrTy->getElementType();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000516 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000517 Ty = ArrayTy->getElementType();
518 } else {
519 Subscripts.clear();
520 Sizes.clear();
521 break;
522 }
Johannes Doerferta90943d2016-02-21 16:37:25 +0000523 if (auto *Const = dyn_cast<SCEVConstant>(Expr))
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000524 if (Const->getValue()->isZero()) {
525 DroppedFirstDim = true;
526 continue;
527 }
528 Subscripts.push_back(Expr);
529 continue;
530 }
531
Johannes Doerferta90943d2016-02-21 16:37:25 +0000532 auto *ArrayTy = dyn_cast<ArrayType>(Ty);
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000533 if (!ArrayTy) {
534 Subscripts.clear();
535 Sizes.clear();
536 break;
537 }
538
539 Subscripts.push_back(Expr);
540 if (!(DroppedFirstDim && i == 2))
541 Sizes.push_back(ArrayTy->getNumElements());
542
543 Ty = ArrayTy->getElementType();
544 }
545
546 return std::make_tuple(Subscripts, Sizes);
547}
548
Tobias Grosser75805372011-04-29 06:27:02 +0000549MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000550 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000551 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000552 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000553}
554
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000555const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
556 isl_id *ArrayId = getArrayId();
557 void *User = isl_id_get_user(ArrayId);
558 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
559 isl_id_free(ArrayId);
560 return SAI;
561}
562
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000563__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000564 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
565}
566
Tobias Grosserd840fc72016-02-04 13:18:42 +0000567__isl_give isl_map *MemoryAccess::getAddressFunction() const {
568 return isl_map_lexmin(getAccessRelation());
569}
570
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000571__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
572 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000573 isl_map *Schedule, *ScheduledAccRel;
574 isl_union_set *UDomain;
575
576 UDomain = isl_union_set_from_set(getStatement()->getDomain());
577 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
578 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000579 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000580 return isl_pw_multi_aff_from_map(ScheduledAccRel);
581}
582
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000583__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000584 return isl_map_copy(AccessRelation);
585}
586
Johannes Doerferta99130f2014-10-13 12:58:03 +0000587std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000588 return stringFromIslObj(AccessRelation);
589}
590
Johannes Doerferta99130f2014-10-13 12:58:03 +0000591__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000592 return isl_map_get_space(AccessRelation);
593}
594
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000595__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000596 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000597}
598
Tobias Grosser6f730082015-09-05 07:46:47 +0000599std::string MemoryAccess::getNewAccessRelationStr() const {
600 return stringFromIslObj(NewAccessRelation);
601}
602
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000603__isl_give isl_basic_map *
604MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000605 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000606 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000607
Tobias Grosser084d8f72012-05-29 09:29:44 +0000608 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000609 isl_basic_set_universe(Statement->getDomainSpace()),
610 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000611}
612
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000613// Formalize no out-of-bound access assumption
614//
615// When delinearizing array accesses we optimistically assume that the
616// delinearized accesses do not access out of bound locations (the subscript
617// expression of each array evaluates for each statement instance that is
618// executed to a value that is larger than zero and strictly smaller than the
619// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000620// dimension for which we do not need to assume any upper bound. At this point
621// we formalize this assumption to ensure that at code generation time the
622// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000623//
624// To find the set of constraints necessary to avoid out of bound accesses, we
625// first build the set of data locations that are not within array bounds. We
626// then apply the reverse access relation to obtain the set of iterations that
627// may contain invalid accesses and reduce this set of iterations to the ones
628// that are actually executed by intersecting them with the domain of the
629// statement. If we now project out all loop dimensions, we obtain a set of
630// parameters that may cause statement instances to be executed that may
631// possibly yield out of bound memory accesses. The complement of these
632// constraints is the set of constraints that needs to be assumed to ensure such
633// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000634void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000635 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000636 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000637 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000638 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000639 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
640 isl_pw_aff *Var =
641 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
642 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
643
644 isl_set *DimOutside;
645
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000646 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000647 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000648 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
649 isl_space_dim(Space, isl_dim_set));
650 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
651 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000652
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000653 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000654
655 Outside = isl_set_union(Outside, DimOutside);
656 }
657
658 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
659 Outside = isl_set_intersect(Outside, Statement->getDomain());
660 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000661
662 // Remove divs to avoid the construction of overly complicated assumptions.
663 // Doing so increases the set of parameter combinations that are assumed to
664 // not appear. This is always save, but may make the resulting run-time check
665 // bail out more often than strictly necessary.
666 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000667 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000668 const auto &Loc = getAccessInstruction()
669 ? getAccessInstruction()->getDebugLoc()
670 : DebugLoc();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000671 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
672 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000673 isl_space_free(Space);
674}
675
Johannes Doerfertcea61932016-02-21 19:13:19 +0000676void MemoryAccess::buildMemIntrinsicAccessRelation() {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000677 assert(isa<MemIntrinsic>(getAccessInstruction()));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000678 assert(Subscripts.size() == 2 && Sizes.size() == 0);
679
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000680 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000681 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000682
683 isl_map *LengthMap;
684 if (Subscripts[1] == nullptr) {
685 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
686 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000687 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000688 LengthMap = isl_map_from_pw_aff(LengthPWA);
689 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
690 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
691 }
692 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
693 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000694 SubscriptMap =
695 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000696 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
697 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
698 getStatement()->getDomainId());
699}
700
Johannes Doerferte7044942015-02-24 11:58:30 +0000701void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
702 ScalarEvolution *SE = Statement->getParent()->getSE();
703
Johannes Doerfertcea61932016-02-21 19:13:19 +0000704 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000705 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000706 return;
707
708 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000709 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
710 return;
711
712 auto *PtrSCEV = SE->getSCEV(Ptr);
713 if (isa<SCEVCouldNotCompute>(PtrSCEV))
714 return;
715
716 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
717 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
718 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
719
720 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
721 if (Range.isFullSet())
722 return;
723
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000724 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000725 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000726 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000727 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000728 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000729
730 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000731 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000732
733 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
734 AccessRange =
735 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
736 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
737}
738
Michael Krusee2bccbb2015-09-18 19:59:43 +0000739__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000740 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000741 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000742
743 for (int i = Size - 2; i >= 0; --i) {
744 isl_space *Space;
745 isl_map *MapOne, *MapTwo;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000746 isl_pw_aff *DimSize = getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000747
748 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
749 isl_pw_aff_free(DimSize);
750 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
751
752 Space = isl_map_get_space(AccessRelation);
753 Space = isl_space_map_from_set(isl_space_range(Space));
754 Space = isl_space_align_params(Space, SpaceSize);
755
756 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
757 isl_id_free(ParamId);
758
759 MapOne = isl_map_universe(isl_space_copy(Space));
760 for (int j = 0; j < Size; ++j)
761 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
762 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
763
764 MapTwo = isl_map_universe(isl_space_copy(Space));
765 for (int j = 0; j < Size; ++j)
766 if (j < i || j > i + 1)
767 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
768
769 isl_local_space *LS = isl_local_space_from_space(Space);
770 isl_constraint *C;
771 C = isl_equality_alloc(isl_local_space_copy(LS));
772 C = isl_constraint_set_constant_si(C, -1);
773 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
774 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
775 MapTwo = isl_map_add_constraint(MapTwo, C);
776 C = isl_equality_alloc(LS);
777 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
778 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
779 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
780 MapTwo = isl_map_add_constraint(MapTwo, C);
781 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
782
783 MapOne = isl_map_union(MapOne, MapTwo);
784 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
785 }
786 return AccessRelation;
787}
788
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000789/// @brief Check if @p Expr is divisible by @p Size.
790static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000791 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000792 if (Size == 1)
793 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000794
795 // Only one factor needs to be divisible.
796 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
797 for (auto *FactorExpr : MulExpr->operands())
798 if (isDivisible(FactorExpr, Size, SE))
799 return true;
800 return false;
801 }
802
803 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
804 // to be divisble.
805 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
806 for (auto *OpExpr : NAryExpr->operands())
807 if (!isDivisible(OpExpr, Size, SE))
808 return false;
809 return true;
810 }
811
812 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
813 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
814 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
815 return MulSCEV == Expr;
816}
817
Michael Krusee2bccbb2015-09-18 19:59:43 +0000818void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
819 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000820
Michael Krusee2bccbb2015-09-18 19:59:43 +0000821 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000822 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000823
Michael Krusee2bccbb2015-09-18 19:59:43 +0000824 if (!isAffine()) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000825 if (isa<MemIntrinsic>(getAccessInstruction()))
826 buildMemIntrinsicAccessRelation();
827
Tobias Grosser4f967492013-06-23 05:21:18 +0000828 // We overapproximate non-affine accesses with a possible access to the
829 // whole array. For read accesses it does not make a difference, if an
830 // access must or may happen. However, for write accesses it is important to
831 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000832 if (!AccessRelation)
833 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
834
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000835 AccessRelation =
836 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000837 return;
838 }
839
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000840 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000841 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000842
Michael Krusee2bccbb2015-09-18 19:59:43 +0000843 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000844 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000845 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000846 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000847 }
848
Tobias Grosser5d51afe2016-02-02 16:46:45 +0000849 if (Sizes.size() >= 1 && !isa<SCEVConstant>(Sizes[0]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000850 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000851
Tobias Grosser79baa212014-04-10 08:38:02 +0000852 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000853 AccessRelation = isl_map_set_tuple_id(
854 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000855 AccessRelation =
856 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
857
Tobias Grosseraa660a92015-03-30 00:07:50 +0000858 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000859 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000860}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000861
Michael Krusecac948e2015-10-02 13:53:07 +0000862MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000863 AccessType AccType, Value *BaseAddress,
864 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000865 ArrayRef<const SCEV *> Subscripts,
866 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000867 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000868 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
869 BaseAddr(BaseAddress), BaseName(BaseName), ElementType(ElementType),
Michael Krusecac948e2015-10-02 13:53:07 +0000870 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
871 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000872 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000873 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000874 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000875 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000876
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000877 std::string IdName =
878 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000879 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
880}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000881
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000882void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000883 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000884 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000885}
886
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000887const std::string MemoryAccess::getReductionOperatorStr() const {
888 return MemoryAccess::getReductionOperatorStr(getReductionType());
889}
890
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000891__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
892
Johannes Doerfertf6183392014-07-01 20:52:51 +0000893raw_ostream &polly::operator<<(raw_ostream &OS,
894 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000895 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000896 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000897 else
898 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000899 return OS;
900}
901
Tobias Grosser75805372011-04-29 06:27:02 +0000902void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000903 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000904 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000905 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000906 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000907 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000908 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000909 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000910 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000911 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000912 break;
913 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000914 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000915 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000916 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000917 if (hasNewAccessRelation())
918 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000919}
920
Tobias Grosser74394f02013-01-14 22:40:23 +0000921void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000922
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000923__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
924 auto *Stmt = getStatement();
925 return Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
926}
927
Tobias Grosser75805372011-04-29 06:27:02 +0000928// Create a map in the size of the provided set domain, that maps from the
929// one element of the provided set domain to another element of the provided
930// set domain.
931// The mapping is limited to all points that are equal in all but the last
932// dimension and for which the last dimension of the input is strict smaller
933// than the last dimension of the output.
934//
935// getEqualAndLarger(set[i0, i1, ..., iX]):
936//
937// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
938// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
939//
Tobias Grosserf5338802011-10-06 00:03:35 +0000940static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000941 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000942 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000943 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000944
945 // Set all but the last dimension to be equal for the input and output
946 //
947 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
948 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000949 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000950 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000951
952 // Set the last dimension of the input to be strict smaller than the
953 // last dimension of the output.
954 //
955 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000956 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
957 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000958 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000959}
960
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000961__isl_give isl_set *
962MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000963 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000964 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000965 isl_space *Space = isl_space_range(isl_map_get_space(S));
966 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000967
Sebastian Popa00a0292012-12-18 07:46:06 +0000968 S = isl_map_reverse(S);
969 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000970
Sebastian Popa00a0292012-12-18 07:46:06 +0000971 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
972 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
973 NextScatt = isl_map_apply_domain(NextScatt, S);
974 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000975
Sebastian Popa00a0292012-12-18 07:46:06 +0000976 isl_set *Deltas = isl_map_deltas(NextScatt);
977 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000978}
979
Sebastian Popa00a0292012-12-18 07:46:06 +0000980bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000981 int StrideWidth) const {
982 isl_set *Stride, *StrideX;
983 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000984
Sebastian Popa00a0292012-12-18 07:46:06 +0000985 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000986 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000987 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
988 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
989 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
990 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000991 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000992
Tobias Grosser28dd4862012-01-24 16:42:16 +0000993 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000994 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000995
Tobias Grosser28dd4862012-01-24 16:42:16 +0000996 return IsStrideX;
997}
998
Sebastian Popa00a0292012-12-18 07:46:06 +0000999bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
1000 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001001}
1002
Sebastian Popa00a0292012-12-18 07:46:06 +00001003bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
1004 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001005}
1006
Tobias Grosser166c4222015-09-05 07:46:40 +00001007void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
1008 isl_map_free(NewAccessRelation);
1009 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001010}
Tobias Grosser75805372011-04-29 06:27:02 +00001011
1012//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001013
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001014__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001015 isl_set *Domain = getDomain();
1016 if (isl_set_is_empty(Domain)) {
1017 isl_set_free(Domain);
1018 return isl_map_from_aff(
1019 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1020 }
1021 auto *Schedule = getParent()->getSchedule();
1022 Schedule = isl_union_map_intersect_domain(
1023 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1024 if (isl_union_map_is_empty(Schedule)) {
1025 isl_set_free(Domain);
1026 isl_union_map_free(Schedule);
1027 return isl_map_from_aff(
1028 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1029 }
1030 auto *M = isl_map_from_union_map(Schedule);
1031 M = isl_map_coalesce(M);
1032 M = isl_map_gist_domain(M, Domain);
1033 M = isl_map_coalesce(M);
1034 return M;
1035}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001036
Johannes Doerfert574182d2015-08-12 10:19:50 +00001037__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Michael Kruse375cb5f2016-02-24 22:08:24 +00001038 return getParent()->getPwAff(E, getEntryBlock());
Johannes Doerfert574182d2015-08-12 10:19:50 +00001039}
1040
Tobias Grosser37eb4222014-02-20 21:43:54 +00001041void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1042 assert(isl_set_is_subset(NewDomain, Domain) &&
1043 "New domain is not a subset of old domain!");
1044 isl_set_free(Domain);
1045 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001046}
1047
Michael Krusecac948e2015-10-02 13:53:07 +00001048void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001049 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001050 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001051 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001052
Tobias Grossera535dff2015-12-13 19:59:01 +00001053 ScopArrayInfo::MemoryKind Ty;
1054 if (Access->isPHIKind())
1055 Ty = ScopArrayInfo::MK_PHI;
1056 else if (Access->isExitPHIKind())
1057 Ty = ScopArrayInfo::MK_ExitPHI;
1058 else if (Access->isValueKind())
1059 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001060 else
Tobias Grossera535dff2015-12-13 19:59:01 +00001061 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001062
Johannes Doerfertadeab372016-02-07 13:57:32 +00001063 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1064 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001065 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001066 }
1067}
1068
Michael Krusecac948e2015-10-02 13:53:07 +00001069void ScopStmt::addAccess(MemoryAccess *Access) {
1070 Instruction *AccessInst = Access->getAccessInstruction();
1071
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001072 if (Access->isArrayKind()) {
1073 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1074 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001075 } else if (Access->isValueKind() && Access->isWrite()) {
1076 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001077 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001078 assert(!ValueWrites.lookup(AccessVal));
1079
1080 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001081 } else if (Access->isValueKind() && Access->isRead()) {
1082 Value *AccessVal = Access->getAccessValue();
1083 assert(!ValueReads.lookup(AccessVal));
1084
1085 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001086 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1087 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1088 assert(!PHIWrites.lookup(PHI));
1089
1090 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001091 }
1092
1093 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001094}
1095
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001096void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001097 for (MemoryAccess *MA : *this)
1098 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001099
Johannes Doerfert7c013572016-04-12 09:57:34 +00001100 InvalidContext = isl_set_align_params(InvalidContext, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001101 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001102}
1103
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001104/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
1105static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1106 void *User) {
1107 isl_set **BoundedParts = static_cast<isl_set **>(User);
1108 if (isl_basic_set_is_bounded(BSet))
1109 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1110 else
1111 isl_basic_set_free(BSet);
1112 return isl_stat_ok;
1113}
1114
1115/// @brief Return the bounded parts of @p S.
1116static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1117 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1118 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1119 isl_set_free(S);
1120 return BoundedParts;
1121}
1122
1123/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
1124///
1125/// @returns A separation of @p S into first an unbounded then a bounded subset,
1126/// both with regards to the dimension @p Dim.
1127static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1128partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1129
1130 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001131 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001132
1133 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001134 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001135
1136 // Remove dimensions that are greater than Dim as they are not interesting.
1137 assert(NumDimsS >= Dim + 1);
1138 OnlyDimS =
1139 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1140
1141 // Create artificial parametric upper bounds for dimensions smaller than Dim
1142 // as we are not interested in them.
1143 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1144 for (unsigned u = 0; u < Dim; u++) {
1145 isl_constraint *C = isl_inequality_alloc(
1146 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1147 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1148 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1149 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1150 }
1151
1152 // Collect all bounded parts of OnlyDimS.
1153 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1154
1155 // Create the dimensions greater than Dim again.
1156 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1157 NumDimsS - Dim - 1);
1158
1159 // Remove the artificial upper bound parameters again.
1160 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1161
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001162 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001163 return std::make_pair(UnboundedParts, BoundedParts);
1164}
1165
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001166/// @brief Set the dimension Ids from @p From in @p To.
1167static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1168 __isl_take isl_set *To) {
1169 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1170 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1171 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1172 }
1173 return To;
1174}
1175
1176/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001177static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001178 __isl_take isl_pw_aff *L,
1179 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001180 switch (Pred) {
1181 case ICmpInst::ICMP_EQ:
1182 return isl_pw_aff_eq_set(L, R);
1183 case ICmpInst::ICMP_NE:
1184 return isl_pw_aff_ne_set(L, R);
1185 case ICmpInst::ICMP_SLT:
1186 return isl_pw_aff_lt_set(L, R);
1187 case ICmpInst::ICMP_SLE:
1188 return isl_pw_aff_le_set(L, R);
1189 case ICmpInst::ICMP_SGT:
1190 return isl_pw_aff_gt_set(L, R);
1191 case ICmpInst::ICMP_SGE:
1192 return isl_pw_aff_ge_set(L, R);
1193 case ICmpInst::ICMP_ULT:
1194 return isl_pw_aff_lt_set(L, R);
1195 case ICmpInst::ICMP_UGT:
1196 return isl_pw_aff_gt_set(L, R);
1197 case ICmpInst::ICMP_ULE:
1198 return isl_pw_aff_le_set(L, R);
1199 case ICmpInst::ICMP_UGE:
1200 return isl_pw_aff_ge_set(L, R);
1201 default:
1202 llvm_unreachable("Non integer predicate not supported");
1203 }
1204}
1205
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001206/// @brief Create the conditions under which @p L @p Pred @p R is true.
1207///
1208/// Helper function that will make sure the dimensions of the result have the
1209/// same isl_id's as the @p Domain.
1210static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1211 __isl_take isl_pw_aff *L,
1212 __isl_take isl_pw_aff *R,
1213 __isl_keep isl_set *Domain) {
1214 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1215 return setDimensionIds(Domain, ConsequenceCondSet);
1216}
1217
1218/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001219///
1220/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001221/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1222/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001223static void
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001224buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1225 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001226 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1227
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001228 Value *Condition = getConditionFromTerminator(SI);
1229 assert(Condition && "No condition for switch");
1230
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001231 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001232 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001233 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001234 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001235
1236 unsigned NumSuccessors = SI->getNumSuccessors();
1237 ConditionSets.resize(NumSuccessors);
1238 for (auto &Case : SI->cases()) {
1239 unsigned Idx = Case.getSuccessorIndex();
1240 ConstantInt *CaseValue = Case.getCaseValue();
1241
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001242 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001243 isl_set *CaseConditionSet =
1244 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1245 ConditionSets[Idx] = isl_set_coalesce(
1246 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1247 }
1248
1249 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1250 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1251 for (unsigned u = 2; u < NumSuccessors; u++)
1252 ConditionSetUnion =
1253 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1254 ConditionSets[0] = setDimensionIds(
1255 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1256
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001257 isl_pw_aff_free(LHS);
1258}
1259
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001260/// @brief Build the conditions sets for the branch condition @p Condition in
1261/// the @p Domain.
1262///
1263/// This will fill @p ConditionSets with the conditions under which control
1264/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001265/// have as many elements as @p TI has successors. If @p TI is nullptr the
1266/// context under which @p Condition is true/false will be returned as the
1267/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001268static void
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001269buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1270 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001271 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1272
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001273 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001274 isl_set *ConsequenceCondSet = nullptr;
1275 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1276 if (CCond->isZero())
1277 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1278 else
1279 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1280 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1281 auto Opcode = BinOp->getOpcode();
1282 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1283
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001284 buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1285 ConditionSets);
1286 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1287 ConditionSets);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001288
1289 isl_set_free(ConditionSets.pop_back_val());
1290 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1291 isl_set_free(ConditionSets.pop_back_val());
1292 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1293
1294 if (Opcode == Instruction::And)
1295 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1296 else
1297 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1298 } else {
1299 auto *ICond = dyn_cast<ICmpInst>(Condition);
1300 assert(ICond &&
1301 "Condition of exiting branch was neither constant nor ICmp!");
1302
1303 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001304 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001305 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L));
1306 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001307 ConsequenceCondSet =
1308 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1309 }
1310
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001311 // If no terminator was given we are only looking for parameter constraints
1312 // under which @p Condition is true/false.
1313 if (!TI)
1314 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001315 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001316 ConsequenceCondSet = isl_set_coalesce(
1317 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001318
Johannes Doerfert15194912016-04-04 07:59:41 +00001319 isl_set *AlternativeCondSet;
1320 unsigned NumParams = isl_set_n_param(ConsequenceCondSet);
1321 unsigned NumBasicSets = isl_set_n_basic_set(ConsequenceCondSet);
1322 if (NumBasicSets + NumParams < MaxConjunctsInDomain) {
1323 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1324 isl_set_copy(ConsequenceCondSet));
1325 } else {
1326 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
1327 AlternativeCondSet = isl_set_empty(isl_set_get_space(ConsequenceCondSet));
1328 }
1329
1330 ConditionSets.push_back(ConsequenceCondSet);
1331 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001332}
1333
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001334/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1335///
1336/// This will fill @p ConditionSets with the conditions under which control
1337/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1338/// have as many elements as @p TI has successors.
1339static void
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001340buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001341 __isl_keep isl_set *Domain,
1342 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1343
1344 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001345 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001346
1347 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1348
1349 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001350 ConditionSets.push_back(isl_set_copy(Domain));
1351 return;
1352 }
1353
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001354 Value *Condition = getConditionFromTerminator(TI);
1355 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001356
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001357 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001358}
1359
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001360void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001361 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001362
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001363 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001364 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001365}
1366
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001367void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP,
1368 ScopDetection &SD) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001369 isl_ctx *Ctx = Parent.getIslCtx();
1370 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1371 Type *Ty = GEP->getPointerOperandType();
1372 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001373
1374 // The set of loads that are required to be invariant.
1375 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001376
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001377 std::vector<const SCEV *> Subscripts;
1378 std::vector<int> Sizes;
1379
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001380 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001381
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001382 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001383 Ty = PtrTy->getElementType();
1384 }
1385
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001386 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001387
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001388 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001389
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001390 auto *NotExecuted = isl_set_complement(isl_set_params(getDomain()));
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001391 for (size_t i = 0; i < Sizes.size(); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001392 auto *Expr = Subscripts[i + IndexOffset];
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001393 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001394
Michael Kruse09eb4452016-03-03 22:10:47 +00001395 auto *Scope = SD.getLI()->getLoopFor(getEntryBlock());
Johannes Doerfert09e36972015-10-07 20:17:36 +00001396 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +00001397 if (!isAffineExpr(&Parent.getRegion(), Scope, Expr, SE, nullptr,
1398 &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +00001399 continue;
1400
1401 bool NonAffine = false;
1402 for (LoadInst *LInst : AccessILS)
1403 if (!ScopRIL.count(LInst))
1404 NonAffine = true;
1405
1406 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001407 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001408
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001409 isl_pw_aff *AccessOffset = getPwAff(Expr);
1410 AccessOffset =
1411 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001412
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001413 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1414 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001415
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001416 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1417 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1418 OutOfBound = isl_set_params(OutOfBound);
1419 isl_set *InBound = isl_set_complement(OutOfBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001420
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001421 // A => B == !A or B
1422 isl_set *InBoundIfExecuted =
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001423 isl_set_union(isl_set_copy(NotExecuted), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001424
Roman Gareev10595a12016-01-08 14:01:59 +00001425 InBoundIfExecuted = isl_set_coalesce(InBoundIfExecuted);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00001426 Parent.recordAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc(),
1427 AS_ASSUMPTION);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001428 }
1429
1430 isl_local_space_free(LSpace);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001431 isl_set_free(NotExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001432}
1433
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001434void ScopStmt::deriveAssumptions(BasicBlock *Block, ScopDetection &SD) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001435 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001436 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001437 deriveAssumptionsFromGEP(GEP, SD);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001438}
1439
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001440void ScopStmt::collectSurroundingLoops() {
1441 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1442 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1443 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1444 isl_id_free(DimId);
1445 }
1446}
1447
Michael Kruse9d080092015-09-11 21:41:48 +00001448ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerfert7c013572016-04-12 09:57:34 +00001449 : Parent(parent), InvalidContext(isl_set_empty(Parent.getParamSpace())),
1450 Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001451
Tobias Grosser16c44032015-07-09 07:31:45 +00001452 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001453}
1454
Michael Kruse9d080092015-09-11 21:41:48 +00001455ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerfert7c013572016-04-12 09:57:34 +00001456 : Parent(parent), InvalidContext(isl_set_empty(Parent.getParamSpace())),
1457 Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001458
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001459 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001460}
1461
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001462void ScopStmt::init(ScopDetection &SD) {
Michael Krusecac948e2015-10-02 13:53:07 +00001463 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001464
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001465 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001466 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001467 buildAccessRelations();
1468
1469 if (BB) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001470 deriveAssumptions(BB, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001471 } else {
1472 for (BasicBlock *Block : R->blocks()) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001473 deriveAssumptions(Block, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001474 }
1475 }
1476
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001477 if (DetectReductions)
1478 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001479}
1480
Johannes Doerferte58a0122014-06-27 20:31:28 +00001481/// @brief Collect loads which might form a reduction chain with @p StoreMA
1482///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001483/// Check if the stored value for @p StoreMA is a binary operator with one or
1484/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001485/// used only once (by @p StoreMA) and its load operands are also used only
1486/// once, we have found a possible reduction chain. It starts at an operand
1487/// load and includes the binary operator and @p StoreMA.
1488///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001489/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001490/// escape this block or into any other store except @p StoreMA.
1491void ScopStmt::collectCandiateReductionLoads(
1492 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1493 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1494 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001495 return;
1496
1497 // Skip if there is not one binary operator between the load and the store
1498 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001499 if (!BinOp)
1500 return;
1501
1502 // Skip if the binary operators has multiple uses
1503 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001504 return;
1505
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001506 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001507 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1508 return;
1509
Johannes Doerfert9890a052014-07-01 00:32:29 +00001510 // Skip if the binary operator is outside the current SCoP
1511 if (BinOp->getParent() != Store->getParent())
1512 return;
1513
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001514 // Skip if it is a multiplicative reduction and we disabled them
1515 if (DisableMultiplicativeReductions &&
1516 (BinOp->getOpcode() == Instruction::Mul ||
1517 BinOp->getOpcode() == Instruction::FMul))
1518 return;
1519
Johannes Doerferte58a0122014-06-27 20:31:28 +00001520 // Check the binary operator operands for a candidate load
1521 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1522 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1523 if (!PossibleLoad0 && !PossibleLoad1)
1524 return;
1525
1526 // A load is only a candidate if it cannot escape (thus has only this use)
1527 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001528 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001529 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001530 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001531 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001532 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001533}
1534
1535/// @brief Check for reductions in this ScopStmt
1536///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001537/// Iterate over all store memory accesses and check for valid binary reduction
1538/// like chains. For all candidates we check if they have the same base address
1539/// and there are no other accesses which overlap with them. The base address
1540/// check rules out impossible reductions candidates early. The overlap check,
1541/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001542/// guarantees that none of the intermediate results will escape during
1543/// execution of the loop nest. We basically check here that no other memory
1544/// access can access the same memory as the potential reduction.
1545void ScopStmt::checkForReductions() {
1546 SmallVector<MemoryAccess *, 2> Loads;
1547 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1548
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001549 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001550 // stores and collecting possible reduction loads.
1551 for (MemoryAccess *StoreMA : MemAccs) {
1552 if (StoreMA->isRead())
1553 continue;
1554
1555 Loads.clear();
1556 collectCandiateReductionLoads(StoreMA, Loads);
1557 for (MemoryAccess *LoadMA : Loads)
1558 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1559 }
1560
1561 // Then check each possible candidate pair.
1562 for (const auto &CandidatePair : Candidates) {
1563 bool Valid = true;
1564 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1565 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1566
1567 // Skip those with obviously unequal base addresses.
1568 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1569 isl_map_free(LoadAccs);
1570 isl_map_free(StoreAccs);
1571 continue;
1572 }
1573
1574 // And check if the remaining for overlap with other memory accesses.
1575 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1576 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1577 isl_set *AllAccs = isl_map_range(AllAccsRel);
1578
1579 for (MemoryAccess *MA : MemAccs) {
1580 if (MA == CandidatePair.first || MA == CandidatePair.second)
1581 continue;
1582
1583 isl_map *AccRel =
1584 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1585 isl_set *Accs = isl_map_range(AccRel);
1586
1587 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1588 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1589 Valid = Valid && isl_set_is_empty(OverlapAccs);
1590 isl_set_free(OverlapAccs);
1591 }
1592 }
1593
1594 isl_set_free(AllAccs);
1595 if (!Valid)
1596 continue;
1597
Johannes Doerfertf6183392014-07-01 20:52:51 +00001598 const LoadInst *Load =
1599 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1600 MemoryAccess::ReductionType RT =
1601 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1602
Johannes Doerferte58a0122014-06-27 20:31:28 +00001603 // If no overlapping access was found we mark the load and store as
1604 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001605 CandidatePair.first->markAsReductionLike(RT);
1606 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001607 }
Tobias Grosser75805372011-04-29 06:27:02 +00001608}
1609
Tobias Grosser74394f02013-01-14 22:40:23 +00001610std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001611
Tobias Grosser54839312015-04-21 11:37:25 +00001612std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001613 auto *S = getSchedule();
1614 auto Str = stringFromIslObj(S);
1615 isl_map_free(S);
1616 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001617}
1618
Johannes Doerfert7c013572016-04-12 09:57:34 +00001619void ScopStmt::setInvalidContext(__isl_take isl_set *IC) {
1620 isl_set_free(InvalidContext);
1621 InvalidContext = IC;
1622}
1623
Michael Kruse375cb5f2016-02-24 22:08:24 +00001624BasicBlock *ScopStmt::getEntryBlock() const {
1625 if (isBlockStmt())
1626 return getBasicBlock();
1627 return getRegion()->getEntry();
1628}
1629
Michael Kruse7b5caa42016-02-24 22:08:28 +00001630RegionNode *ScopStmt::getRegionNode() const {
1631 if (isRegionStmt())
1632 return getRegion()->getNode();
1633 return getParent()->getRegion().getBBNode(getBasicBlock());
1634}
1635
Tobias Grosser74394f02013-01-14 22:40:23 +00001636unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001637
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001638unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001639
Tobias Grosser75805372011-04-29 06:27:02 +00001640const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1641
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001642const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001643 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001644}
1645
Tobias Grosser74394f02013-01-14 22:40:23 +00001646isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001647
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001648__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001649
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001650__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001651 return isl_set_get_space(Domain);
1652}
1653
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001654__isl_give isl_id *ScopStmt::getDomainId() const {
1655 return isl_set_get_tuple_id(Domain);
1656}
Tobias Grossercd95b772012-08-30 11:49:38 +00001657
Johannes Doerfert7c013572016-04-12 09:57:34 +00001658ScopStmt::~ScopStmt() {
1659 isl_set_free(Domain);
1660 isl_set_free(InvalidContext);
1661}
Tobias Grosser75805372011-04-29 06:27:02 +00001662
1663void ScopStmt::print(raw_ostream &OS) const {
1664 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001665 OS.indent(12) << "Domain :=\n";
1666
1667 if (Domain) {
1668 OS.indent(16) << getDomainStr() << ";\n";
1669 } else
1670 OS.indent(16) << "n/a\n";
1671
Tobias Grosser54839312015-04-21 11:37:25 +00001672 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001673
1674 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001675 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001676 } else
1677 OS.indent(16) << "n/a\n";
1678
Tobias Grosser083d3d32014-06-28 08:59:45 +00001679 for (MemoryAccess *Access : MemAccs)
1680 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001681}
1682
1683void ScopStmt::dump() const { print(dbgs()); }
1684
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001685void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001686 // Remove all memory accesses in @p InvMAs from this statement
1687 // together with all scalar accesses that were caused by them.
Michael Krusead28e5a2016-01-26 13:33:15 +00001688 // MK_Value READs have no access instruction, hence would not be removed by
1689 // this function. However, it is only used for invariant LoadInst accesses,
1690 // its arguments are always affine, hence synthesizable, and therefore there
1691 // are no MK_Value READ accesses to be removed.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001692 for (MemoryAccess *MA : InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001693 auto Predicate = [&](MemoryAccess *Acc) {
Tobias Grosser3a6ac9f2015-11-30 21:13:43 +00001694 return Acc->getAccessInstruction() == MA->getAccessInstruction();
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001695 };
1696 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1697 MemAccs.end());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001698 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001699 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001700}
1701
Tobias Grosser75805372011-04-29 06:27:02 +00001702//===----------------------------------------------------------------------===//
1703/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001704
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001705void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001706 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1707 isl_set_free(Context);
1708 Context = NewContext;
1709}
1710
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001711/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1712struct SCEVSensitiveParameterRewriter
1713 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1714 ValueToValueMap &VMap;
1715 ScalarEvolution &SE;
1716
1717public:
1718 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1719 : VMap(VMap), SE(SE) {}
1720
1721 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1722 ValueToValueMap &VMap) {
1723 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1724 return SSPR.visit(E);
1725 }
1726
1727 const SCEV *visit(const SCEV *E) {
1728 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1729 }
1730
1731 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1732
1733 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1734 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1735 }
1736
1737 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1738 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1739 }
1740
1741 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1742 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1743 }
1744
1745 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1746 SmallVector<const SCEV *, 4> Operands;
1747 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1748 Operands.push_back(visit(E->getOperand(i)));
1749 return SE.getAddExpr(Operands);
1750 }
1751
1752 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1753 SmallVector<const SCEV *, 4> Operands;
1754 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1755 Operands.push_back(visit(E->getOperand(i)));
1756 return SE.getMulExpr(Operands);
1757 }
1758
1759 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1760 SmallVector<const SCEV *, 4> Operands;
1761 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1762 Operands.push_back(visit(E->getOperand(i)));
1763 return SE.getSMaxExpr(Operands);
1764 }
1765
1766 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1767 SmallVector<const SCEV *, 4> Operands;
1768 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1769 Operands.push_back(visit(E->getOperand(i)));
1770 return SE.getUMaxExpr(Operands);
1771 }
1772
1773 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1774 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1775 }
1776
1777 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1778 auto *Start = visit(E->getStart());
1779 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1780 visit(E->getStepRecurrence(SE)),
1781 E->getLoop(), SCEV::FlagAnyWrap);
1782 return SE.getAddExpr(Start, AddRec);
1783 }
1784
1785 const SCEV *visitUnknown(const SCEVUnknown *E) {
1786 if (auto *NewValue = VMap.lookup(E->getValue()))
1787 return SE.getUnknown(NewValue);
1788 return E;
1789 }
1790};
1791
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001792const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001793 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001794}
1795
Tobias Grosserabfbe632013-02-05 12:09:06 +00001796void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001797 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001798 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001799
1800 // Normalize the SCEV to get the representing element for an invariant load.
1801 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1802
Tobias Grosser60b54f12011-11-08 15:41:28 +00001803 if (ParameterIds.find(Parameter) != ParameterIds.end())
1804 continue;
1805
1806 int dimension = Parameters.size();
1807
1808 Parameters.push_back(Parameter);
1809 ParameterIds[Parameter] = dimension;
1810 }
1811}
1812
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001813__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001814 // Normalize the SCEV to get the representing element for an invariant load.
1815 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1816
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001817 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001818
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001819 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001820 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001821
Tobias Grosser8f99c162011-11-15 11:38:55 +00001822 std::string ParameterName;
1823
Craig Topper7fb6e472016-01-31 20:36:20 +00001824 ParameterName = "p_" + utostr(IdIter->second);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001825
Tobias Grosser8f99c162011-11-15 11:38:55 +00001826 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1827 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001828
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001829 // If this parameter references a specific Value and this value has a name
1830 // we use this name as it is likely to be unique and more useful than just
1831 // a number.
1832 if (Val->hasName())
1833 ParameterName = Val->getName();
1834 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001835 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001836 if (LoadOrigin->hasName()) {
1837 ParameterName += "_loaded_from_";
1838 ParameterName +=
1839 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1840 }
1841 }
1842 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001843
Tobias Grosser20532b82014-04-11 17:56:49 +00001844 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1845 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001846}
Tobias Grosser75805372011-04-29 06:27:02 +00001847
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001848__isl_give isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001849 isl_set *DomainContext = isl_union_set_params(getDomains());
1850 return isl_set_intersect_params(C, DomainContext);
1851}
1852
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001853void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1854 LoopInfo &LI) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001855 auto *R = &getRegion();
1856 auto &F = *R->getEntry()->getParent();
1857 for (auto &Assumption : AC.assumptions()) {
1858 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1859 if (!CI || CI->getNumArgOperands() != 1)
1860 continue;
1861 if (!DT.dominates(CI->getParent(), R->getEntry()))
1862 continue;
1863
Michael Kruse09eb4452016-03-03 22:10:47 +00001864 auto *L = LI.getLoopFor(CI->getParent());
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001865 auto *Val = CI->getArgOperand(0);
1866 std::vector<const SCEV *> Params;
Michael Kruse09eb4452016-03-03 22:10:47 +00001867 if (!isAffineParamConstraint(Val, R, L, *SE, Params)) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001868 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1869 CI->getDebugLoc(),
1870 "Non-affine user assumption ignored.");
1871 continue;
1872 }
1873
1874 addParams(Params);
1875
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001876 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001877 buildConditionSets(*Stmts.begin(), Val, nullptr, L, Context, ConditionSets);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001878 assert(ConditionSets.size() == 2);
1879 isl_set_free(ConditionSets[1]);
1880
1881 auto *AssumptionCtx = ConditionSets[0];
1882 emitOptimizationRemarkAnalysis(
1883 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1884 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1885 Context = isl_set_intersect(Context, AssumptionCtx);
1886 }
1887}
1888
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001889void Scop::addUserContext() {
1890 if (UserContextStr.empty())
1891 return;
1892
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001893 isl_set *UserContext =
1894 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001895 isl_space *Space = getParamSpace();
1896 if (isl_space_dim(Space, isl_dim_param) !=
1897 isl_set_dim(UserContext, isl_dim_param)) {
1898 auto SpaceStr = isl_space_to_str(Space);
1899 errs() << "Error: the context provided in -polly-context has not the same "
1900 << "number of dimensions than the computed context. Due to this "
1901 << "mismatch, the -polly-context option is ignored. Please provide "
1902 << "the context in the parameter space: " << SpaceStr << ".\n";
1903 free(SpaceStr);
1904 isl_set_free(UserContext);
1905 isl_space_free(Space);
1906 return;
1907 }
1908
1909 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001910 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1911 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001912
1913 if (strcmp(NameContext, NameUserContext) != 0) {
1914 auto SpaceStr = isl_space_to_str(Space);
1915 errs() << "Error: the name of dimension " << i
1916 << " provided in -polly-context "
1917 << "is '" << NameUserContext << "', but the name in the computed "
1918 << "context is '" << NameContext
1919 << "'. Due to this name mismatch, "
1920 << "the -polly-context option is ignored. Please provide "
1921 << "the context in the parameter space: " << SpaceStr << ".\n";
1922 free(SpaceStr);
1923 isl_set_free(UserContext);
1924 isl_space_free(Space);
1925 return;
1926 }
1927
1928 UserContext =
1929 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1930 isl_space_get_dim_id(Space, isl_dim_param, i));
1931 }
1932
1933 Context = isl_set_intersect(Context, UserContext);
1934 isl_space_free(Space);
1935}
1936
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001937void Scop::buildInvariantEquivalenceClasses(ScopDetection &SD) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001938 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001939
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001940 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001941 for (LoadInst *LInst : RIL) {
1942 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1943
Johannes Doerfert96e54712016-02-07 17:30:13 +00001944 Type *Ty = LInst->getType();
1945 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001946 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001947 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001948 continue;
1949 }
1950
1951 ClassRep = LInst;
Johannes Doerfert96e54712016-02-07 17:30:13 +00001952 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(), nullptr,
1953 Ty);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001954 }
1955}
1956
Tobias Grosser6be480c2011-11-08 15:41:13 +00001957void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001958 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001959 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001960 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00001961 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001962}
1963
Tobias Grosser18daaca2012-05-22 10:47:27 +00001964void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001965 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001966 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001967
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001968 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001969
Johannes Doerferte7044942015-02-24 11:58:30 +00001970 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001971 }
1972}
1973
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001974void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001975 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001976 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001977
Tobias Grosser083d3d32014-06-28 08:59:45 +00001978 for (const auto &ParamID : ParameterIds) {
1979 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001980 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001981 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001982 }
1983
1984 // Align the parameters of all data structures to the model.
1985 Context = isl_set_align_params(Context, Space);
1986
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001987 for (ScopStmt &Stmt : *this)
1988 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001989}
1990
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001991static __isl_give isl_set *
1992simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1993 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001994 // If we modelt all blocks in the SCoP that have side effects we can simplify
1995 // the context with the constraints that are needed for anything to be
1996 // executed at all. However, if we have error blocks in the SCoP we already
1997 // assumed some parameter combinations cannot occure and removed them from the
1998 // domains, thus we cannot use the remaining domain to simplify the
1999 // assumptions.
2000 if (!S.hasErrorBlock()) {
2001 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2002 AssumptionContext =
2003 isl_set_gist_params(AssumptionContext, DomainParameters);
2004 }
2005
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002006 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2007 return AssumptionContext;
2008}
2009
2010void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002011 // The parameter constraints of the iteration domains give us a set of
2012 // constraints that need to hold for all cases where at least a single
2013 // statement iteration is executed in the whole scop. We now simplify the
2014 // assumed context under the assumption that such constraints hold and at
2015 // least a single statement iteration is executed. For cases where no
2016 // statement instances are executed, the assumptions we have taken about
2017 // the executed code do not matter and can be changed.
2018 //
2019 // WARNING: This only holds if the assumptions we have taken do not reduce
2020 // the set of statement instances that are executed. Otherwise we
2021 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002022 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002023 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002024 // performed. In such a case, modifying the run-time conditions and
2025 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002026 // to not be executed.
2027 //
2028 // Example:
2029 //
2030 // When delinearizing the following code:
2031 //
2032 // for (long i = 0; i < 100; i++)
2033 // for (long j = 0; j < m; j++)
2034 // A[i+p][j] = 1.0;
2035 //
2036 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002037 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002038 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002039 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002040 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002041}
2042
Johannes Doerfertb164c792014-09-18 11:17:17 +00002043/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002044static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002045 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2046 isl_pw_multi_aff *MinPMA, *MaxPMA;
2047 isl_pw_aff *LastDimAff;
2048 isl_aff *OneAff;
2049 unsigned Pos;
2050
Johannes Doerfert6296d952016-04-22 11:38:19 +00002051 Set = isl_set_remove_divs(Set);
2052
2053 if (isl_set_n_basic_set(Set) >= MaxConjunctsInDomain) {
2054 isl_set_free(Set);
2055 return isl_stat_error;
2056 }
2057
Johannes Doerfert9143d672014-09-27 11:02:39 +00002058 // Restrict the number of parameters involved in the access as the lexmin/
2059 // lexmax computation will take too long if this number is high.
2060 //
2061 // Experiments with a simple test case using an i7 4800MQ:
2062 //
2063 // #Parameters involved | Time (in sec)
2064 // 6 | 0.01
2065 // 7 | 0.04
2066 // 8 | 0.12
2067 // 9 | 0.40
2068 // 10 | 1.54
2069 // 11 | 6.78
2070 // 12 | 30.38
2071 //
2072 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2073 unsigned InvolvedParams = 0;
2074 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2075 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2076 InvolvedParams++;
2077
2078 if (InvolvedParams > RunTimeChecksMaxParameters) {
2079 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002080 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002081 }
2082 }
2083
Johannes Doerfertb164c792014-09-18 11:17:17 +00002084 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2085 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2086
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002087 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2088 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2089
Johannes Doerfertb164c792014-09-18 11:17:17 +00002090 // Adjust the last dimension of the maximal access by one as we want to
2091 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2092 // we test during code generation might now point after the end of the
2093 // allocated array but we will never dereference it anyway.
2094 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2095 "Assumed at least one output dimension");
2096 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2097 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2098 OneAff = isl_aff_zero_on_domain(
2099 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2100 OneAff = isl_aff_add_constant_si(OneAff, 1);
2101 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2102 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2103
2104 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2105
2106 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002107 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002108}
2109
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002110static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2111 isl_set *Domain = MA->getStatement()->getDomain();
2112 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2113 return isl_set_reset_tuple_id(Domain);
2114}
2115
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002116/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
2117static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002118 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002119 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002120
2121 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2122 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002123 Locations = isl_union_set_coalesce(Locations);
2124 Locations = isl_union_set_detect_equalities(Locations);
2125 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002126 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002127 isl_union_set_free(Locations);
2128 return Valid;
2129}
2130
Johannes Doerfert96425c22015-08-30 21:13:53 +00002131/// @brief Helper to treat non-affine regions and basic blocks the same.
2132///
2133///{
2134
2135/// @brief Return the block that is the representing block for @p RN.
2136static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2137 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2138 : RN->getNodeAs<BasicBlock>();
2139}
2140
2141/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002142static inline BasicBlock *
2143getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002144 if (RN->isSubRegion()) {
2145 assert(idx == 0);
2146 return RN->getNodeAs<Region>()->getExit();
2147 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002148 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002149}
2150
2151/// @brief Return the smallest loop surrounding @p RN.
2152static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2153 if (!RN->isSubRegion())
2154 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2155
2156 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2157 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2158 while (L && NonAffineSubRegion->contains(L))
2159 L = L->getParentLoop();
2160 return L;
2161}
2162
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002163static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2164 if (!RN->isSubRegion())
2165 return 1;
2166
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002167 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002168 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002169}
2170
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002171static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2172 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002173 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002174 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002175 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002176 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002177 return true;
2178 return false;
2179}
2180
Johannes Doerfert96425c22015-08-30 21:13:53 +00002181///}
2182
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002183static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2184 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002185 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002186 isl_id *DimId =
2187 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2188 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2189}
2190
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002191__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002192 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002193}
2194
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002195__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002196 auto DIt = DomainMap.find(BB);
2197 if (DIt != DomainMap.end())
2198 return isl_set_copy(DIt->getSecond());
2199
2200 auto &RI = *R.getRegionInfo();
2201 auto *BBR = RI.getRegionFor(BB);
2202 while (BBR->getEntry() == BB)
2203 BBR = BBR->getParent();
2204 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002205}
2206
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002207bool Scop::buildDomains(Region *R, ScopDetection &SD, DominatorTree &DT,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002208 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002209
Johannes Doerfert432658d2016-01-26 11:01:41 +00002210 bool IsOnlyNonAffineRegion = SD.isNonAffineSubRegion(R, R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002211 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002212 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2213 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002214 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002215
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002216 while (LD-- >= 0) {
2217 S = addDomainDimId(S, LD + 1, L);
2218 L = L->getParentLoop();
2219 }
2220
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002221 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002222
Johannes Doerfert432658d2016-01-26 11:01:41 +00002223 if (IsOnlyNonAffineRegion)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002224 return true;
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002225
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002226 if (!buildDomainsWithBranchConstraints(R, SD, DT, LI))
2227 return false;
2228
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002229 propagateDomainConstraints(R, SD, DT, LI);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002230
2231 // Error blocks and blocks dominated by them have been assumed to never be
2232 // executed. Representing them in the Scop does not add any value. In fact,
2233 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002234 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002235 // will cause problems when building up a ScopStmt for them.
2236 // Furthermore, basic blocks dominated by error blocks may reference
2237 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002238 // can themselves not be constructed properly. To this end we will replace
2239 // the domains of error blocks and those only reachable via error blocks
2240 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002241 // parameter combination it would be reached via an error block in its
2242 // InvalidContext. This information is needed during load hoisting.
2243 propagateInvalidStmtContexts(R, SD, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002244
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002245 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002246}
2247
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002248static Loop *
2249getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI,
2250 const ScopDetection::BoxedLoopsSetTy &BoxedLoops) {
2251 auto *L = LI.getLoopFor(BB);
2252 while (BoxedLoops.count(L))
2253 L = L->getParentLoop();
2254 return L;
2255}
2256
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002257/// @brief Adjust the dimensions of @p Dom that was constructed for @p OldL
2258/// to be compatible to domains constructed for loop @p NewL.
2259///
2260/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2261/// edge from @p OldL to @p NewL.
2262static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2263 __isl_take isl_set *Dom,
2264 Loop *OldL, Loop *NewL) {
2265
2266 // If the loops are the same there is nothing to do.
2267 if (NewL == OldL)
2268 return Dom;
2269
2270 int OldDepth = S.getRelativeLoopDepth(OldL);
2271 int NewDepth = S.getRelativeLoopDepth(NewL);
2272 // If both loops are non-affine loops there is nothing to do.
2273 if (OldDepth == -1 && NewDepth == -1)
2274 return Dom;
2275
2276 // Distinguish three cases:
2277 // 1) The depth is the same but the loops are not.
2278 // => One loop was left one was entered.
2279 // 2) The depth increased from OldL to NewL.
2280 // => One loop was entered, none was left.
2281 // 3) The depth decreased from OldL to NewL.
2282 // => Loops were left were difference of the depths defines how many.
2283 if (OldDepth == NewDepth) {
2284 assert(OldL->getParentLoop() == NewL->getParentLoop());
2285 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2286 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2287 Dom = addDomainDimId(Dom, NewDepth, NewL);
2288 } else if (OldDepth < NewDepth) {
2289 assert(OldDepth + 1 == NewDepth);
2290 auto &R = S.getRegion();
2291 (void)R;
2292 assert(NewL->getParentLoop() == OldL ||
2293 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2294 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2295 Dom = addDomainDimId(Dom, NewDepth, NewL);
2296 } else {
2297 assert(OldDepth > NewDepth);
2298 int Diff = OldDepth - NewDepth;
2299 int NumDim = isl_set_n_dim(Dom);
2300 assert(NumDim >= Diff);
2301 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2302 }
2303
2304 return Dom;
2305}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002306
Johannes Doerfert7c013572016-04-12 09:57:34 +00002307void Scop::propagateInvalidStmtContexts(Region *R, ScopDetection &SD,
2308 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002309
2310 ReversePostOrderTraversal<Region *> RTraversal(R);
2311 for (auto *RN : RTraversal) {
2312
2313 // Recurse for affine subregions but go on for basic blocks and non-affine
2314 // subregions.
2315 if (RN->isSubRegion()) {
2316 Region *SubRegion = RN->getNodeAs<Region>();
2317 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfert7c013572016-04-12 09:57:34 +00002318 propagateInvalidStmtContexts(SubRegion, SD, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002319 continue;
2320 }
2321 }
2322
2323 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2324 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002325 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002326 isl_set *&Domain = DomainMap[BB];
2327 assert(Domain && "Cannot propagate a nullptr");
2328
Johannes Doerfert7c013572016-04-12 09:57:34 +00002329 auto *InvalidCtx = Stmt->getInvalidContext();
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002330 auto *DomainCtx = isl_set_params(isl_set_copy(Domain));
Johannes Doerfert7c013572016-04-12 09:57:34 +00002331 bool IsInvalidBlock =
2332 ContainsErrorBlock || isl_set_is_subset(DomainCtx, InvalidCtx);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002333
Johannes Doerfert7c013572016-04-12 09:57:34 +00002334 if (IsInvalidBlock) {
2335 InvalidCtx = isl_set_coalesce(isl_set_union(InvalidCtx, DomainCtx));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002336 auto *EmptyDom = isl_set_empty(isl_set_get_space(Domain));
2337 isl_set_free(Domain);
2338 Domain = EmptyDom;
2339 } else {
2340 isl_set_free(DomainCtx);
2341 }
2342
Johannes Doerfert7c013572016-04-12 09:57:34 +00002343 if (isl_set_is_empty(InvalidCtx)) {
2344 isl_set_free(InvalidCtx);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002345 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002346 }
2347
2348 Stmt->setInvalidContext(InvalidCtx);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002349
2350 auto *TI = BB->getTerminator();
2351 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2352 for (unsigned u = 0; u < NumSuccs; u++) {
2353 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002354 auto *SuccStmt = getStmtFor(SuccBB);
2355
2356 // Skip successors outside the SCoP.
2357 if (!SuccStmt)
2358 continue;
2359
2360 auto *SuccInvalidCtx = SuccStmt->getInvalidContext();
2361 SuccInvalidCtx = isl_set_union(SuccInvalidCtx, Stmt->getInvalidContext());
2362 SuccInvalidCtx = isl_set_coalesce(SuccInvalidCtx);
2363 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidCtx);
2364 SuccStmt->setInvalidContext(SuccInvalidCtx);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002365
2366 // Check if the maximal number of domain conjuncts was reached.
2367 // In case this happens we will bail.
Johannes Doerfert7c013572016-04-12 09:57:34 +00002368 if (NumConjucts < MaxConjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002369 continue;
2370
2371 invalidate(COMPLEXITY, TI->getDebugLoc());
2372 return;
2373 }
2374 }
2375}
2376
Johannes Doerfert642594a2016-04-04 07:57:39 +00002377void Scop::propagateDomainConstraintsToRegionExit(
2378 BasicBlock *BB, Loop *BBLoop,
2379 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, ScopDetection &SD,
2380 LoopInfo &LI) {
2381
2382 // Check if the block @p BB is the entry of a region. If so we propagate it's
2383 // domain to the exit block of the region. Otherwise we are done.
2384 auto *RI = R.getRegionInfo();
2385 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2386 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
2387 if (!BBReg || BBReg->getEntry() != BB || !R.contains(ExitBB))
2388 return;
2389
2390 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2391 // Do not propagate the domain if there is a loop backedge inside the region
2392 // that would prevent the exit block from beeing executed.
2393 auto *L = BBLoop;
2394 while (L && R.contains(L)) {
2395 SmallVector<BasicBlock *, 4> LatchBBs;
2396 BBLoop->getLoopLatches(LatchBBs);
2397 for (auto *LatchBB : LatchBBs)
2398 if (BB != LatchBB && BBReg->contains(LatchBB))
2399 return;
2400 L = L->getParentLoop();
2401 }
2402
2403 auto *Domain = DomainMap[BB];
2404 assert(Domain && "Cannot propagate a nullptr");
2405
2406 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2407
2408 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2409 // adjust the domain before we can propagate it.
2410 auto *AdjustedDomain =
2411 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2412 auto *&ExitDomain = DomainMap[ExitBB];
2413
2414 // If the exit domain is not yet created we set it otherwise we "add" the
2415 // current domain.
2416 ExitDomain =
2417 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2418
2419 FinishedExitBlocks.insert(ExitBB);
2420}
2421
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002422bool Scop::buildDomainsWithBranchConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002423 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002424 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002425
2426 // To create the domain for each block in R we iterate over all blocks and
2427 // subregions in R and propagate the conditions under which the current region
2428 // element is executed. To this end we iterate in reverse post order over R as
2429 // it ensures that we first visit all predecessors of a region node (either a
2430 // basic block or a subregion) before we visit the region node itself.
2431 // Initially, only the domain for the SCoP region entry block is set and from
2432 // there we propagate the current domain to all successors, however we add the
2433 // condition that the successor is actually executed next.
2434 // As we are only interested in non-loop carried constraints here we can
2435 // simply skip loop back edges.
2436
Johannes Doerfert642594a2016-04-04 07:57:39 +00002437 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002438 ReversePostOrderTraversal<Region *> RTraversal(R);
2439 for (auto *RN : RTraversal) {
2440
2441 // Recurse for affine subregions but go on for basic blocks and non-affine
2442 // subregions.
2443 if (RN->isSubRegion()) {
2444 Region *SubRegion = RN->getNodeAs<Region>();
2445 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002446 if (!buildDomainsWithBranchConstraints(SubRegion, SD, DT, LI))
2447 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002448 continue;
2449 }
2450 }
2451
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002452 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002453 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002454
Johannes Doerfert96425c22015-08-30 21:13:53 +00002455 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002456 TerminatorInst *TI = BB->getTerminator();
2457
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002458 if (isa<UnreachableInst>(TI))
2459 continue;
2460
Johannes Doerfertf5673802015-10-01 23:48:18 +00002461 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002462 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002463 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002464
Johannes Doerfert642594a2016-04-04 07:57:39 +00002465 auto *BBLoop = getRegionNodeLoop(RN, LI);
2466 // Propagate the domain from BB directly to blocks that have a superset
2467 // domain, at the moment only region exit nodes of regions that start in BB.
2468 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, SD,
2469 LI);
2470
2471 // If all successors of BB have been set a domain through the propagation
2472 // above we do not need to build condition sets but can just skip this
2473 // block. However, it is important to note that this is a local property
2474 // with regards to the region @p R. To this end FinishedExitBlocks is a
2475 // local variable.
2476 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2477 return FinishedExitBlocks.count(SuccBB);
2478 };
2479 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2480 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002481
2482 // Build the condition sets for the successor nodes of the current region
2483 // node. If it is a non-affine subregion we will always execute the single
2484 // exit node, hence the single entry node domain is the condition set. For
2485 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002486 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002487 if (RN->isSubRegion())
2488 ConditionSets.push_back(isl_set_copy(Domain));
2489 else
Johannes Doerfert171b92f2016-04-19 14:53:13 +00002490 buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002491
2492 // Now iterate over the successors and set their initial domain based on
2493 // their condition set. We skip back edges here and have to be careful when
2494 // we leave a loop not to keep constraints over a dimension that doesn't
2495 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002496 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002497 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002498 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002499 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002500
Johannes Doerfert535de032016-04-19 14:49:05 +00002501 auto *SuccStmt = getStmtFor(SuccBB);
2502 // Skip blocks outside the region.
2503 if (!SuccStmt) {
2504 isl_set_free(CondSet);
2505 continue;
2506 }
2507
Johannes Doerfert642594a2016-04-04 07:57:39 +00002508 // If we propagate the domain of some block to "SuccBB" we do not have to
2509 // adjust the domain.
2510 if (FinishedExitBlocks.count(SuccBB)) {
2511 isl_set_free(CondSet);
2512 continue;
2513 }
2514
Johannes Doerfert96425c22015-08-30 21:13:53 +00002515 // Skip back edges.
2516 if (DT.dominates(SuccBB, BB)) {
2517 isl_set_free(CondSet);
2518 continue;
2519 }
2520
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002521 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002522 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002523
2524 // Set the domain for the successor or merge it with an existing domain in
2525 // case there are multiple paths (without loop back edges) to the
2526 // successor block.
2527 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002528
Johannes Doerfert96425c22015-08-30 21:13:53 +00002529 if (!SuccDomain)
2530 SuccDomain = CondSet;
2531 else
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002532 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002533
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002534 // Check if the maximal number of domain conjuncts was reached.
2535 // In case this happens we will clean up and bail.
Johannes Doerfert15194912016-04-04 07:59:41 +00002536 if (isl_set_n_basic_set(SuccDomain) < MaxConjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002537 continue;
2538
2539 invalidate(COMPLEXITY, DebugLoc());
2540 while (++u < ConditionSets.size())
2541 isl_set_free(ConditionSets[u]);
2542 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002543 }
2544 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002545
2546 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002547}
2548
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00002549__isl_give isl_set *Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2550 isl_set *Domain,
2551 ScopDetection &SD,
2552 DominatorTree &DT,
2553 LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002554 // If @p BB is the ScopEntry we are done
2555 if (R.getEntry() == BB)
2556 return isl_set_universe(isl_set_get_space(Domain));
2557
2558 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2559 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2560
2561 // The region info of this function.
2562 auto &RI = *R.getRegionInfo();
2563
2564 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2565
2566 // A domain to collect all predecessor domains, thus all conditions under
2567 // which the block is executed. To this end we start with the empty domain.
2568 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2569
2570 // Set of regions of which the entry block domain has been propagated to BB.
2571 // all predecessors inside any of the regions can be skipped.
2572 SmallSet<Region *, 8> PropagatedRegions;
2573
2574 for (auto *PredBB : predecessors(BB)) {
2575 // Skip backedges.
2576 if (DT.dominates(BB, PredBB))
2577 continue;
2578
2579 // If the predecessor is in a region we used for propagation we can skip it.
2580 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2581 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2582 PredBBInRegion)) {
2583 continue;
2584 }
2585
2586 // Check if there is a valid region we can use for propagation, thus look
2587 // for a region that contains the predecessor and has @p BB as exit block.
2588 auto *PredR = RI.getRegionFor(PredBB);
2589 while (PredR->getExit() != BB && !PredR->contains(BB))
2590 PredR->getParent();
2591
2592 // If a valid region for propagation was found use the entry of that region
2593 // for propagation, otherwise the PredBB directly.
2594 if (PredR->getExit() == BB) {
2595 PredBB = PredR->getEntry();
2596 PropagatedRegions.insert(PredR);
2597 }
2598
Johannes Doerfert41cda152016-04-08 10:32:26 +00002599 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002600 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2601 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2602
2603 PredDom = isl_set_union(PredDom, PredBBDom);
2604 }
2605
2606 return PredDom;
2607}
2608
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002609void Scop::propagateDomainConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002610 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002611 // Iterate over the region R and propagate the domain constrains from the
2612 // predecessors to the current node. In contrast to the
2613 // buildDomainsWithBranchConstraints function, this one will pull the domain
2614 // information from the predecessors instead of pushing it to the successors.
2615 // Additionally, we assume the domains to be already present in the domain
2616 // map here. However, we iterate again in reverse post order so we know all
2617 // predecessors have been visited before a block or non-affine subregion is
2618 // visited.
2619
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002620 ReversePostOrderTraversal<Region *> RTraversal(R);
2621 for (auto *RN : RTraversal) {
2622
2623 // Recurse for affine subregions but go on for basic blocks and non-affine
2624 // subregions.
2625 if (RN->isSubRegion()) {
2626 Region *SubRegion = RN->getNodeAs<Region>();
2627 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002628 propagateDomainConstraints(SubRegion, SD, DT, LI);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002629 continue;
2630 }
2631 }
2632
2633 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002634 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002635 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002636
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002637 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002638 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, SD, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002639 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002640 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002641
Johannes Doerfert642594a2016-04-04 07:57:39 +00002642 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002643 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002644 addLoopBoundsToHeaderDomain(BBLoop, LI);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002645
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002646 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002647 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002648 IsOptimized = true;
2649 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002650 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2651 AS_RESTRICTION);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002652 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002653 }
2654}
2655
2656/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2657/// is incremented by one and all other dimensions are equal, e.g.,
2658/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2659/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2660static __isl_give isl_map *
2661createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2662 auto *MapSpace = isl_space_map_from_set(SetSpace);
2663 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2664 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2665 if (u != Dim)
2666 NextIterationMap =
2667 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2668 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2669 C = isl_constraint_set_constant_si(C, 1);
2670 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2671 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2672 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2673 return NextIterationMap;
2674}
2675
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002676void Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002677 int LoopDepth = getRelativeLoopDepth(L);
2678 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002679
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002680 BasicBlock *HeaderBB = L->getHeader();
2681 assert(DomainMap.count(HeaderBB));
2682 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002683
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002684 isl_map *NextIterationMap =
2685 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002686
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002687 isl_set *UnionBackedgeCondition =
2688 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002689
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002690 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2691 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002692
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002693 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002694
2695 // If the latch is only reachable via error statements we skip it.
2696 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2697 if (!LatchBBDom)
2698 continue;
2699
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002700 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002701
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002702 TerminatorInst *TI = LatchBB->getTerminator();
2703 BranchInst *BI = dyn_cast<BranchInst>(TI);
2704 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002705 BackedgeCondition = isl_set_copy(LatchBBDom);
2706 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002707 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002708 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00002709 buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
2710 ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002711
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002712 // Free the non back edge condition set as we do not need it.
2713 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002714
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002715 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002716 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002717
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002718 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2719 assert(LatchLoopDepth >= LoopDepth);
2720 BackedgeCondition =
2721 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2722 LatchLoopDepth - LoopDepth);
2723 UnionBackedgeCondition =
2724 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002725 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002726
2727 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2728 for (int i = 0; i < LoopDepth; i++)
2729 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2730
2731 isl_set *UnionBackedgeConditionComplement =
2732 isl_set_complement(UnionBackedgeCondition);
2733 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2734 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2735 UnionBackedgeConditionComplement =
2736 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2737 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2738 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2739
2740 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2741 HeaderBBDom = Parts.second;
2742
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002743 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2744 // the bounded assumptions to the context as they are already implied by the
2745 // <nsw> tag.
2746 if (Affinator.hasNSWAddRecForLoop(L)) {
2747 isl_set_free(Parts.first);
2748 return;
2749 }
2750
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002751 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002752 recordAssumption(INFINITELOOP, UnboundedCtx,
2753 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002754}
2755
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002756void Scop::buildAliasChecks(AliasAnalysis &AA) {
2757 if (!PollyUseRuntimeAliasChecks)
2758 return;
2759
2760 if (buildAliasGroups(AA))
2761 return;
2762
2763 // If a problem occurs while building the alias groups we need to delete
2764 // this SCoP and pretend it wasn't valid in the first place. To this end
2765 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002766 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002767
2768 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2769 << " could not be created as the number of parameters involved "
2770 "is too high. The SCoP will be "
2771 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2772 "the maximal number of parameters but be advised that the "
2773 "compile time might increase exponentially.\n\n");
2774}
2775
Johannes Doerfert9143d672014-09-27 11:02:39 +00002776bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002777 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002778 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002779 // for all memory accesses inside the SCoP.
2780 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002781 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002782 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002783 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002784 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002785 // if their access domains intersect, otherwise they are in different
2786 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002787 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002788 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002789 // and maximal accesses to each array of a group in read only and non
2790 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002791 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2792
2793 AliasSetTracker AST(AA);
2794
2795 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002796 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002797 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002798
2799 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002800 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002801 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2802 isl_set_free(StmtDomain);
2803 if (StmtDomainEmpty)
2804 continue;
2805
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002806 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002807 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002808 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002809 if (!MA->isRead())
2810 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002811 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002812 if (MA->isRead() && isa<MemTransferInst>(Acc))
2813 PtrToAcc[cast<MemTransferInst>(Acc)->getSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002814 else
2815 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002816 AST.add(Acc);
2817 }
2818 }
2819
2820 SmallVector<AliasGroupTy, 4> AliasGroups;
2821 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002822 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002823 continue;
2824 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002825 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002826 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002827 if (AG.size() < 2)
2828 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002829 AliasGroups.push_back(std::move(AG));
2830 }
2831
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002832 // Split the alias groups based on their domain.
2833 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2834 AliasGroupTy NewAG;
2835 AliasGroupTy &AG = AliasGroups[u];
2836 AliasGroupTy::iterator AGI = AG.begin();
2837 isl_set *AGDomain = getAccessDomain(*AGI);
2838 while (AGI != AG.end()) {
2839 MemoryAccess *MA = *AGI;
2840 isl_set *MADomain = getAccessDomain(MA);
2841 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2842 NewAG.push_back(MA);
2843 AGI = AG.erase(AGI);
2844 isl_set_free(MADomain);
2845 } else {
2846 AGDomain = isl_set_union(AGDomain, MADomain);
2847 AGI++;
2848 }
2849 }
2850 if (NewAG.size() > 1)
2851 AliasGroups.push_back(std::move(NewAG));
2852 isl_set_free(AGDomain);
2853 }
2854
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002855 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002856 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002857 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2858 for (AliasGroupTy &AG : AliasGroups) {
2859 NonReadOnlyBaseValues.clear();
2860 ReadOnlyPairs.clear();
2861
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002862 if (AG.size() < 2) {
2863 AG.clear();
2864 continue;
2865 }
2866
Johannes Doerfert13771732014-10-01 12:40:46 +00002867 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002868 emitOptimizationRemarkAnalysis(
2869 F.getContext(), DEBUG_TYPE, F,
2870 (*II)->getAccessInstruction()->getDebugLoc(),
2871 "Possibly aliasing pointer, use restrict keyword.");
2872
Johannes Doerfert13771732014-10-01 12:40:46 +00002873 Value *BaseAddr = (*II)->getBaseAddr();
2874 if (HasWriteAccess.count(BaseAddr)) {
2875 NonReadOnlyBaseValues.insert(BaseAddr);
2876 II++;
2877 } else {
2878 ReadOnlyPairs[BaseAddr].insert(*II);
2879 II = AG.erase(II);
2880 }
2881 }
2882
2883 // If we don't have read only pointers check if there are at least two
2884 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002885 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002886 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002887 continue;
2888 }
2889
2890 // If we don't have non read only pointers clear the alias group.
2891 if (NonReadOnlyBaseValues.empty()) {
2892 AG.clear();
2893 continue;
2894 }
2895
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002896 // Check if we have non-affine accesses left, if so bail out as we cannot
2897 // generate a good access range yet.
2898 for (auto *MA : AG)
2899 if (!MA->isAffine()) {
2900 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2901 return false;
2902 }
2903 for (auto &ReadOnlyPair : ReadOnlyPairs)
2904 for (auto *MA : ReadOnlyPair.second)
2905 if (!MA->isAffine()) {
2906 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2907 return false;
2908 }
2909
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002910 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002911 MinMaxAliasGroups.emplace_back();
2912 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2913 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2914 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2915 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002916
2917 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002918
2919 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002920 for (MemoryAccess *MA : AG)
2921 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002922
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002923 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2924 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002925
2926 // Bail out if the number of values we need to compare is too large.
2927 // This is important as the number of comparisions grows quadratically with
2928 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002929 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2930 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002931 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002932
2933 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002934 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002935 Accesses = isl_union_map_empty(getParamSpace());
2936
2937 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2938 for (MemoryAccess *MA : ReadOnlyPair.second)
2939 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2940
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002941 Valid =
2942 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002943
2944 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002945 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002946 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002947
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002948 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002949}
2950
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002951/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002952static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002953 // Start with the smallest loop containing the entry and expand that
2954 // loop until it contains all blocks in the region. If there is a loop
2955 // containing all blocks in the region check if it is itself contained
2956 // and if so take the parent loop as it will be the smallest containing
2957 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002958 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002959 while (L) {
2960 bool AllContained = true;
2961 for (auto *BB : R.blocks())
2962 AllContained &= L->contains(BB);
2963 if (AllContained)
2964 break;
2965 L = L->getParentLoop();
2966 }
2967
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002968 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2969}
2970
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002971static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2972 ScopDetection &SD) {
2973
2974 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2975
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002976 unsigned MinLD = INT_MAX, MaxLD = 0;
2977 for (BasicBlock *BB : R.blocks()) {
2978 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002979 if (!R.contains(L))
2980 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002981 if (BoxedLoops && BoxedLoops->count(L))
2982 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002983 unsigned LD = L->getLoopDepth();
2984 MinLD = std::min(MinLD, LD);
2985 MaxLD = std::max(MaxLD, LD);
2986 }
2987 }
2988
2989 // Handle the case that there is no loop in the SCoP first.
2990 if (MaxLD == 0)
2991 return 1;
2992
2993 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2994 assert(MaxLD >= MinLD &&
2995 "Maximal loop depth was smaller than mininaml loop depth?");
2996 return MaxLD - MinLD + 1;
2997}
2998
Michael Kruse09eb4452016-03-03 22:10:47 +00002999Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
3000 unsigned MaxLoopDepth)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003001 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003002 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003003 MaxLoopDepth(MaxLoopDepth), IslCtx(isl_ctx_alloc(), isl_ctx_free),
3004 Context(nullptr), Affinator(this, LI), AssumedContext(nullptr),
3005 InvalidContext(nullptr), Schedule(nullptr) {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003006 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003007 buildContext();
3008}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003009
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00003010void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003011 DominatorTree &DT, LoopInfo &LI) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003012 buildInvariantEquivalenceClasses(SD);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003013
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003014 if (!buildDomains(&R, SD, DT, LI))
3015 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003016
Johannes Doerfertff68f462016-04-19 14:49:42 +00003017 addUserAssumptions(AC, DT, LI);
3018
Michael Krusecac948e2015-10-02 13:53:07 +00003019 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003020 // Exit early in case there are no executable statements left in this scop.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003021 simplifySCoP(true, DT, LI);
Michael Kruseafe06702015-10-02 16:33:27 +00003022 if (Stmts.empty())
3023 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003024
Michael Krusecac948e2015-10-02 13:53:07 +00003025 // The ScopStmts now have enough information to initialize themselves.
3026 for (ScopStmt &Stmt : Stmts)
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003027 Stmt.init(SD);
Michael Krusecac948e2015-10-02 13:53:07 +00003028
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003029 buildSchedule(SD, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00003030
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003031 if (!hasFeasibleRuntimeContext())
Tobias Grosser8286b832015-11-02 11:29:32 +00003032 return;
3033
3034 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003035 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00003036 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003037 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003038
3039 // After the context was fully constructed, thus all our knowledge about
3040 // the parameters is in there, we add all recorded assumptions to the
3041 // assumed/invalid context.
3042 addRecordedAssumptions();
3043
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003044 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003045 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003046
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003047 hoistInvariantLoads(SD);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003048 verifyInvariantLoads(SD);
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003049 simplifySCoP(false, DT, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00003050}
3051
3052Scop::~Scop() {
3053 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003054 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003055 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003056 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003057
Johannes Doerfert96425c22015-08-30 21:13:53 +00003058 for (auto It : DomainMap)
3059 isl_set_free(It.second);
3060
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003061 for (auto &AS : RecordedAssumptions)
3062 isl_set_free(AS.Set);
3063
Johannes Doerfertb164c792014-09-18 11:17:17 +00003064 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003065 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003066 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003067 isl_pw_multi_aff_free(MMA.first);
3068 isl_pw_multi_aff_free(MMA.second);
3069 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003070 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003071 isl_pw_multi_aff_free(MMA.first);
3072 isl_pw_multi_aff_free(MMA.second);
3073 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003074 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003075
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003076 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003077 isl_set_free(std::get<2>(IAClass));
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003078
3079 // Explicitly release all Scop objects and the underlying isl objects before
3080 // we relase the isl context.
3081 Stmts.clear();
3082 ScopArrayInfoMap.clear();
3083 AccFuncMap.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003084}
3085
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003086void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003087 // Check all array accesses for each base pointer and find a (virtual) element
3088 // size for the base pointer that divides all access functions.
3089 for (auto &Stmt : *this)
3090 for (auto *Access : Stmt) {
3091 if (!Access->isArrayKind())
3092 continue;
3093 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
3094 ScopArrayInfo::MK_Array)];
3095 if (SAI->getNumberOfDimensions() != 1)
3096 continue;
3097 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3098 auto *Subscript = Access->getSubscript(0);
3099 while (!isDivisible(Subscript, DivisibleSize, *SE))
3100 DivisibleSize /= 2;
3101 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3102 SAI->updateElementType(Ty);
3103 }
3104
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003105 for (auto &Stmt : *this)
3106 for (auto &Access : Stmt)
3107 Access->updateDimensionality();
3108}
3109
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003110void Scop::simplifySCoP(bool RemoveIgnoredStmts, DominatorTree &DT,
3111 LoopInfo &LI) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003112 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3113 ScopStmt &Stmt = *StmtIt;
Michael Kruse7b5caa42016-02-24 22:08:28 +00003114 RegionNode *RN = Stmt.getRegionNode();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003115
Johannes Doerferteca9e892015-11-03 16:54:49 +00003116 bool RemoveStmt = StmtIt->isEmpty();
3117 if (!RemoveStmt)
Michael Kruse375cb5f2016-02-24 22:08:24 +00003118 RemoveStmt = isl_set_is_empty(DomainMap[Stmt.getEntryBlock()]);
Johannes Doerferteca9e892015-11-03 16:54:49 +00003119 if (!RemoveStmt)
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003120 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN, DT, LI));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003121
Johannes Doerferteca9e892015-11-03 16:54:49 +00003122 // Remove read only statements only after invariant loop hoisting.
3123 if (!RemoveStmt && !RemoveIgnoredStmts) {
3124 bool OnlyRead = true;
3125 for (MemoryAccess *MA : Stmt) {
3126 if (MA->isRead())
3127 continue;
3128
3129 OnlyRead = false;
3130 break;
3131 }
3132
3133 RemoveStmt = OnlyRead;
3134 }
3135
3136 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00003137 // Remove the statement because it is unnecessary.
3138 if (Stmt.isRegionStmt())
3139 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3140 StmtMap.erase(BB);
3141 else
3142 StmtMap.erase(Stmt.getBasicBlock());
3143
3144 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003145 continue;
3146 }
3147
Michael Krusecac948e2015-10-02 13:53:07 +00003148 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003149 }
3150}
3151
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003152const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
3153 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3154 if (!LInst)
3155 return nullptr;
3156
3157 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3158 LInst = cast<LoadInst>(Rep);
3159
Johannes Doerfert96e54712016-02-07 17:30:13 +00003160 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003161 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003162 for (auto &IAClass : InvariantEquivClasses) {
3163 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
3164 continue;
3165
3166 auto &MAs = std::get<1>(IAClass);
3167 for (auto *MA : MAs)
3168 if (MA->getAccessInstruction() == Val)
3169 return &IAClass;
3170 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003171
3172 return nullptr;
3173}
3174
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003175/// @brief Check if @p MA can always be hoisted without execution context.
3176static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty) {
3177 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3178 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3179 // TODO: We can provide more information for better but more expensive
3180 // results.
3181 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3182 LInst->getAlignment(), DL))
3183 return false;
3184
3185 // If a dereferencable load is in a statement that is modeled precisely we can
3186 // hoist it.
3187 if (StmtInvalidCtxIsEmpty)
3188 return true;
3189
3190 // Even if the statement is not modeled precisely we can hoist the load if it
3191 // does not involve any parameters that might have been specilized by the
3192 // statement domain.
3193 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3194 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3195 return false;
3196 return true;
3197}
3198
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003199void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
3200
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003201 if (InvMAs.empty())
3202 return;
3203
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003204 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003205 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003206
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003207 // Get the context under which the statement is executed but remove the error
3208 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003209 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003210 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003211
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003212 if (isl_set_n_basic_set(DomainCtx) >= MaxConjunctsInDomain) {
3213 auto *AccInst = InvMAs.front()->getAccessInstruction();
3214 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3215 isl_set_free(DomainCtx);
3216 return;
3217 }
3218
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003219 // Project out all parameters that relate to loads in the statement. Otherwise
3220 // we could have cyclic dependences on the constraints under which the
3221 // hoisted loads are executed and we could not determine an order in which to
3222 // pre-load them. This happens because not only lower bounds are part of the
3223 // domain but also upper bounds.
3224 for (MemoryAccess *MA : InvMAs) {
3225 Instruction *AccInst = MA->getAccessInstruction();
3226 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003227 SetVector<Value *> Values;
3228 for (const SCEV *Parameter : Parameters) {
3229 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003230 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003231 if (!Values.count(AccInst))
3232 continue;
3233
3234 if (isl_id *ParamId = getIdForParam(Parameter)) {
3235 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3236 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3237 isl_id_free(ParamId);
3238 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003239 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003240 }
3241 }
3242
3243 for (MemoryAccess *MA : InvMAs) {
3244 // Check for another invariant access that accesses the same location as
3245 // MA and if found consolidate them. Otherwise create a new equivalence
3246 // class at the end of InvariantEquivClasses.
3247 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003248 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003249 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3250
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003251 isl_set *MACtx;
3252 // Check if we know that this pointer can be speculatively accessed.
3253 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty)) {
3254 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
3255 } else {
3256 MACtx = isl_set_copy(DomainCtx);
3257 MACtx = isl_set_gist_params(MACtx, getContext());
3258 }
3259
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003260 bool Consolidated = false;
3261 for (auto &IAClass : InvariantEquivClasses) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00003262 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003263 continue;
3264
Johannes Doerfertdf880232016-03-03 12:26:58 +00003265 // If the pointer and the type is equal check if the access function wrt.
3266 // to the domain is equal too. It can happen that the domain fixes
3267 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003268 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003269 // create a new invariant load equivalence class.
3270 auto &MAs = std::get<1>(IAClass);
3271 if (!MAs.empty()) {
3272 auto *LastMA = MAs.front();
3273
3274 auto *AR = isl_map_range(MA->getAccessRelation());
3275 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3276 bool SameAR = isl_set_is_equal(AR, LastAR);
3277 isl_set_free(AR);
3278 isl_set_free(LastAR);
3279
3280 if (!SameAR)
3281 continue;
3282 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003283
3284 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003285 MAs.push_front(MA);
3286
Johannes Doerfertdf880232016-03-03 12:26:58 +00003287 Consolidated = true;
3288
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003289 // Unify the execution context of the class and this statement.
3290 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003291 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003292 IAClassDomainCtx =
3293 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003294 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003295 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003296 break;
3297 }
3298
3299 if (Consolidated)
3300 continue;
3301
3302 // If we did not consolidate MA, thus did not find an equivalence class
3303 // for it, we create a new one.
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003304 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA}, MACtx,
3305 Ty);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003306 }
3307
3308 isl_set_free(DomainCtx);
3309}
3310
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003311bool Scop::isHoistableAccess(MemoryAccess *Access,
3312 __isl_keep isl_union_map *Writes) {
3313 // TODO: Loads that are not loop carried, hence are in a statement with
3314 // zero iterators, are by construction invariant, though we
3315 // currently "hoist" them anyway. This is necessary because we allow
3316 // them to be treated as parameters (e.g., in conditions) and our code
3317 // generation would otherwise use the old value.
3318
3319 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003320 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003321
3322 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
3323 return false;
3324
3325 // Skip accesses that have an invariant base pointer which is defined but
3326 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3327 // returns a pointer that is used as a base address. However, as we want
3328 // to hoist indirect pointers, we allow the base pointer to be defined in
3329 // the region if it is also a memory access. Each ScopArrayInfo object
3330 // that has a base pointer origin has a base pointer that is loaded and
3331 // that it is invariant, thus it will be hoisted too. However, if there is
3332 // no base pointer origin we check that the base pointer is defined
3333 // outside the region.
3334 const ScopArrayInfo *SAI = Access->getScopArrayInfo();
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003335 auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr());
3336 if (SAI->getBasePtrOriginSAI()) {
3337 assert(BasePtrInst && R.contains(BasePtrInst));
3338 if (!isa<LoadInst>(BasePtrInst))
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003339 return false;
Michael Kruse6f7721f2016-02-24 22:08:19 +00003340 auto *BasePtrStmt = getStmtFor(BasePtrInst);
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003341 assert(BasePtrStmt);
3342 auto *BasePtrMA = BasePtrStmt->getArrayAccessOrNULLFor(BasePtrInst);
3343 if (BasePtrMA && !isHoistableAccess(BasePtrMA, Writes))
3344 return false;
3345 } else if (BasePtrInst && R.contains(BasePtrInst))
3346 return false;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003347
3348 // Skip accesses in non-affine subregions as they might not be executed
3349 // under the same condition as the entry of the non-affine subregion.
3350 if (BB != Access->getAccessInstruction()->getParent())
3351 return false;
3352
3353 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003354 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003355
3356 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3357 Stmt.getNumIterators())) {
3358 isl_map_free(AccessRelation);
3359 return false;
3360 }
3361
3362 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3363 isl_set *AccessRange = isl_map_range(AccessRelation);
3364
3365 isl_union_map *Written = isl_union_map_intersect_range(
3366 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
3367 bool IsWritten = !isl_union_map_is_empty(Written);
3368 isl_union_map_free(Written);
3369
3370 if (IsWritten)
3371 return false;
3372
3373 return true;
3374}
3375
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003376void Scop::verifyInvariantLoads(ScopDetection &SD) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003377 auto &RIL = *SD.getRequiredInvariantLoads(&getRegion());
3378 for (LoadInst *LI : RIL) {
3379 assert(LI && getRegion().contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003380 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003381 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003382 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3383 return;
3384 }
3385 }
3386}
3387
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003388void Scop::hoistInvariantLoads(ScopDetection &SD) {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003389 if (!PollyInvariantLoadHoisting)
3390 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003391
Tobias Grosser0865e7752016-02-29 07:29:42 +00003392 isl_union_map *Writes = getWrites();
3393 for (ScopStmt &Stmt : *this) {
3394 MemoryAccessList InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003395
Tobias Grosser0865e7752016-02-29 07:29:42 +00003396 for (MemoryAccess *Access : Stmt)
3397 if (isHoistableAccess(Access, Writes))
3398 InvariantAccesses.push_front(Access);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003399
Tobias Grosser0865e7752016-02-29 07:29:42 +00003400 // We inserted invariant accesses always in the front but need them to be
3401 // sorted in a "natural order". The statements are already sorted in
3402 // reverse post order and that suffices for the accesses too. The reason
3403 // we require an order in the first place is the dependences between
3404 // invariant loads that can be caused by indirect loads.
3405 InvariantAccesses.reverse();
3406
3407 // Transfer the memory access from the statement to the SCoP.
3408 Stmt.removeMemoryAccesses(InvariantAccesses);
3409 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003410 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003411 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003412}
3413
Johannes Doerfert80ef1102014-11-07 08:31:31 +00003414const ScopArrayInfo *
Tobias Grossercc779502016-02-02 13:22:54 +00003415Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003416 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003417 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003418 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003419 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003420 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003421 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003422 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003423 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003424 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003425 // In case of mismatching array sizes, we bail out by setting the run-time
3426 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003427 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003428 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003429 }
Tobias Grosserab671442015-05-23 05:58:27 +00003430 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003431}
3432
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003433const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003434 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003435 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003436 assert(SAI && "No ScopArrayInfo available for this base pointer");
3437 return SAI;
3438}
3439
Tobias Grosser74394f02013-01-14 22:40:23 +00003440std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003441
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003442std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003443 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003444 return stringFromIslObj(AssumedContext);
3445}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003446
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003447std::string Scop::getInvalidContextStr() const {
3448 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003449}
Tobias Grosser75805372011-04-29 06:27:02 +00003450
3451std::string Scop::getNameStr() const {
3452 std::string ExitName, EntryName;
3453 raw_string_ostream ExitStr(ExitName);
3454 raw_string_ostream EntryStr(EntryName);
3455
Tobias Grosserf240b482014-01-09 10:42:15 +00003456 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003457 EntryStr.str();
3458
3459 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003460 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003461 ExitStr.str();
3462 } else
3463 ExitName = "FunctionExit";
3464
3465 return EntryName + "---" + ExitName;
3466}
3467
Tobias Grosser74394f02013-01-14 22:40:23 +00003468__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003469__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003470 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003471}
3472
Tobias Grossere86109f2013-10-29 21:05:49 +00003473__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003474 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003475 return isl_set_copy(AssumedContext);
3476}
3477
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003478bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003479 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003480 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003481 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3482 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3483 isl_set_is_subset(PositiveContext, NegativeContext));
3484 isl_set_free(PositiveContext);
3485 if (!IsFeasible) {
3486 isl_set_free(NegativeContext);
3487 return false;
3488 }
3489
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003490 auto *DomainContext = isl_union_set_params(getDomains());
3491 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003492 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003493 isl_set_free(NegativeContext);
3494 isl_set_free(DomainContext);
3495
Johannes Doerfert43788c52015-08-20 05:58:56 +00003496 return IsFeasible;
3497}
3498
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003499static std::string toString(AssumptionKind Kind) {
3500 switch (Kind) {
3501 case ALIASING:
3502 return "No-aliasing";
3503 case INBOUNDS:
3504 return "Inbounds";
3505 case WRAPPING:
3506 return "No-overflows";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003507 case COMPLEXITY:
3508 return "Low complexity";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003509 case ERRORBLOCK:
3510 return "No-error";
3511 case INFINITELOOP:
3512 return "Finite loop";
3513 case INVARIANTLOAD:
3514 return "Invariant load";
3515 case DELINEARIZATION:
3516 return "Delinearization";
3517 }
3518 llvm_unreachable("Unknown AssumptionKind!");
3519}
3520
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003521bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3522 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert2f705842016-04-12 16:09:44 +00003523 if (PollyRemarksMinimal) {
3524 if (Sign == AS_ASSUMPTION) {
3525 if (isl_set_is_subset(Context, Set))
3526 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003527
Johannes Doerfert2f705842016-04-12 16:09:44 +00003528 if (isl_set_is_subset(AssumedContext, Set))
3529 return false;
3530 } else {
3531 if (isl_set_is_disjoint(Set, Context))
3532 return false;
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003533
Johannes Doerfert2f705842016-04-12 16:09:44 +00003534 if (isl_set_is_subset(Set, InvalidContext))
3535 return false;
3536 }
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003537 }
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003538
3539 auto &F = *getRegion().getEntry()->getParent();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003540 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3541 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003542 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003543 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003544}
3545
3546void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003547 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003548 // Simplify the assumptions/restrictions first.
3549 Set = isl_set_gist_params(Set, getContext());
3550
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003551 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3552 isl_set_free(Set);
3553 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003554 }
3555
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003556 if (Sign == AS_ASSUMPTION) {
3557 AssumedContext = isl_set_intersect(AssumedContext, Set);
3558 AssumedContext = isl_set_coalesce(AssumedContext);
3559 } else {
3560 InvalidContext = isl_set_union(InvalidContext, Set);
3561 InvalidContext = isl_set_coalesce(InvalidContext);
3562 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003563}
3564
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003565void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003566 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
3567 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003568}
3569
3570void Scop::addRecordedAssumptions() {
3571 while (!RecordedAssumptions.empty()) {
3572 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003573
3574 isl_set *S = AS.Set;
3575 // If a basic block was given use its domain to simplify the assumption.
3576 if (AS.BB)
3577 S = isl_set_params(isl_set_intersect(S, getDomainConditions(AS.BB)));
3578
3579 addAssumption(AS.Kind, S, AS.Loc, AS.Sign);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003580 }
3581}
3582
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003583void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003584 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003585}
3586
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003587__isl_give isl_set *Scop::getInvalidContext() const {
3588 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003589}
3590
Tobias Grosser75805372011-04-29 06:27:02 +00003591void Scop::printContext(raw_ostream &OS) const {
3592 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003593 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003594
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003595 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003596 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003597
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003598 OS.indent(4) << "Invalid Context:\n";
3599 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003600
Tobias Grosser083d3d32014-06-28 08:59:45 +00003601 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003602 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003603 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3604 }
Tobias Grosser75805372011-04-29 06:27:02 +00003605}
3606
Johannes Doerfertb164c792014-09-18 11:17:17 +00003607void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003608 int noOfGroups = 0;
3609 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003610 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003611 noOfGroups += 1;
3612 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003613 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003614 }
3615
Tobias Grosserbb853c22015-07-25 12:31:03 +00003616 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003617 if (MinMaxAliasGroups.empty()) {
3618 OS.indent(8) << "n/a\n";
3619 return;
3620 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003621
Tobias Grosserbb853c22015-07-25 12:31:03 +00003622 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003623
3624 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003625 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003626 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003627 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003628 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3629 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003630 }
3631 OS << " ]]\n";
3632 }
3633
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003634 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003635 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003636 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003637 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003638 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3639 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003640 }
3641 OS << " ]]\n";
3642 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003643 }
3644}
3645
Tobias Grosser75805372011-04-29 06:27:02 +00003646void Scop::printStatements(raw_ostream &OS) const {
3647 OS << "Statements {\n";
3648
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003649 for (const ScopStmt &Stmt : *this)
3650 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003651
3652 OS.indent(4) << "}\n";
3653}
3654
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003655void Scop::printArrayInfo(raw_ostream &OS) const {
3656 OS << "Arrays {\n";
3657
Tobias Grosserab671442015-05-23 05:58:27 +00003658 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003659 Array.second->print(OS);
3660
3661 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003662
3663 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3664
3665 for (auto &Array : arrays())
3666 Array.second->print(OS, /* SizeAsPwAff */ true);
3667
3668 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003669}
3670
Tobias Grosser75805372011-04-29 06:27:02 +00003671void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003672 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3673 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003674 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003675 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003676 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003677 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003678 const auto &MAs = std::get<1>(IAClass);
3679 if (MAs.empty()) {
3680 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003681 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003682 MAs.front()->print(OS);
3683 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003684 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003685 }
3686 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003687 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003688 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003689 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003690 printStatements(OS.indent(4));
3691}
3692
3693void Scop::dump() const { print(dbgs()); }
3694
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003695isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003696
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003697__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003698 // First try to use the SCEVAffinator to generate a piecewise defined
3699 // affine function from @p E in the context of @p BB. If that tasks becomes to
3700 // complex the affinator might return a nullptr. In such a case we invalidate
3701 // the SCoP and return a dummy value. This way we do not need to add error
3702 // handling cdoe to all users of this function.
3703 auto *PWA = Affinator.getPwAff(E, BB);
3704 if (PWA)
3705 return PWA;
3706
3707 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
3708 invalidate(COMPLEXITY, DL);
3709 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003710}
3711
Tobias Grosser808cd692015-07-14 09:33:13 +00003712__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003713 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003714
Tobias Grosser808cd692015-07-14 09:33:13 +00003715 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003716 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003717
3718 return Domain;
3719}
3720
Tobias Grossere5a35142015-11-12 14:07:09 +00003721__isl_give isl_union_map *
3722Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3723 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003724
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003725 for (ScopStmt &Stmt : *this) {
3726 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003727 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003728 continue;
3729
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003730 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003731 isl_map *AccessDomain = MA->getAccessRelation();
3732 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003733 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003734 }
3735 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003736 return isl_union_map_coalesce(Accesses);
3737}
3738
3739__isl_give isl_union_map *Scop::getMustWrites() {
3740 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003741}
3742
3743__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003744 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003745}
3746
Tobias Grosser37eb4222014-02-20 21:43:54 +00003747__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003748 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003749}
3750
3751__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003752 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003753}
3754
Tobias Grosser2ac23382015-11-12 14:07:13 +00003755__isl_give isl_union_map *Scop::getAccesses() {
3756 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3757}
3758
Tobias Grosser808cd692015-07-14 09:33:13 +00003759__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003760 auto *Tree = getScheduleTree();
3761 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00003762 isl_schedule_free(Tree);
3763 return S;
3764}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003765
Tobias Grosser808cd692015-07-14 09:33:13 +00003766__isl_give isl_schedule *Scop::getScheduleTree() const {
3767 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3768 getDomains());
3769}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003770
Tobias Grosser808cd692015-07-14 09:33:13 +00003771void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3772 auto *S = isl_schedule_from_domain(getDomains());
3773 S = isl_schedule_insert_partial_schedule(
3774 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3775 isl_schedule_free(Schedule);
3776 Schedule = S;
3777}
3778
3779void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3780 isl_schedule_free(Schedule);
3781 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003782}
3783
3784bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3785 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003786 for (ScopStmt &Stmt : *this) {
3787 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003788 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3789 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3790
3791 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3792 isl_union_set_free(StmtDomain);
3793 isl_union_set_free(NewStmtDomain);
3794 continue;
3795 }
3796
3797 Changed = true;
3798
3799 isl_union_set_free(StmtDomain);
3800 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3801
3802 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003803 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003804 isl_union_set_free(NewStmtDomain);
3805 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003806 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003807 }
3808 isl_union_set_free(Domain);
3809 return Changed;
3810}
3811
Tobias Grosser75805372011-04-29 06:27:02 +00003812ScalarEvolution *Scop::getSE() const { return SE; }
3813
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003814bool Scop::isIgnored(RegionNode *RN, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003815 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Kruse6f7721f2016-02-24 22:08:19 +00003816 ScopStmt *Stmt = getStmtFor(RN);
Michael Krusea902ba62015-12-13 19:21:45 +00003817
3818 // If there is no stmt, then it already has been removed.
3819 if (!Stmt)
3820 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00003821
Johannes Doerfertf5673802015-10-01 23:48:18 +00003822 // Check if there are accesses contained.
Michael Krusea902ba62015-12-13 19:21:45 +00003823 if (Stmt->isEmpty())
Johannes Doerfertf5673802015-10-01 23:48:18 +00003824 return true;
3825
3826 // Check for reachability via non-error blocks.
3827 if (!DomainMap.count(BB))
3828 return true;
3829
3830 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003831 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003832 return true;
3833
3834 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003835}
3836
Tobias Grosser808cd692015-07-14 09:33:13 +00003837struct MapToDimensionDataTy {
3838 int N;
3839 isl_union_pw_multi_aff *Res;
3840};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003841
Tobias Grosser808cd692015-07-14 09:33:13 +00003842// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003843// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003844//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003845// @param Set The input set.
3846// @param User->N The dimension to map to.
3847// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003848//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003849// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003850static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3851 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3852 int Dim;
3853 isl_space *Space;
3854 isl_pw_multi_aff *PMA;
3855
3856 Dim = isl_set_dim(Set, isl_dim_set);
3857 Space = isl_set_get_space(Set);
3858 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3859 Dim - Data->N);
3860 if (Data->N > 1)
3861 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3862 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3863
3864 isl_set_free(Set);
3865
3866 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003867}
3868
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003869// @brief Create an isl_multi_union_aff that defines an identity mapping
3870// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003871//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003872// # Example:
3873//
3874// Domain: { A[i,j]; B[i,j,k] }
3875// N: 1
3876//
3877// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
3878//
3879// @param USet A union set describing the elements for which to generate a
3880// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00003881// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003882// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003883static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003884mapToDimension(__isl_take isl_union_set *USet, int N) {
3885 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00003886 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003887 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003888
Tobias Grosser808cd692015-07-14 09:33:13 +00003889 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00003890
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003891 auto *Space = isl_union_set_get_space(USet);
3892 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00003893
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003894 Data = {N, PwAff};
3895
3896 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00003897 (void)Res;
3898
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003899 assert(Res == isl_stat_ok);
3900
3901 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00003902 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3903}
3904
Tobias Grosser316b5b22015-11-11 19:28:14 +00003905void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003906 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003907 Stmts.emplace_back(*this, *BB);
Johannes Doerferta90943d2016-02-21 16:37:25 +00003908 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003909 StmtMap[BB] = Stmt;
3910 } else {
3911 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003912 Stmts.emplace_back(*this, *R);
Johannes Doerferta90943d2016-02-21 16:37:25 +00003913 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003914 for (BasicBlock *BB : R->blocks())
3915 StmtMap[BB] = Stmt;
3916 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003917}
3918
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003919void Scop::buildSchedule(ScopDetection &SD, LoopInfo &LI) {
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003920 Loop *L = getLoopSurroundingRegion(getRegion(), LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003921 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003922 buildSchedule(getRegion().getNode(), LoopStack, SD, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00003923 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
3924 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003925}
3926
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003927/// To generate a schedule for the elements in a Region we traverse the Region
3928/// in reverse-post-order and add the contained RegionNodes in traversal order
3929/// to the schedule of the loop that is currently at the top of the LoopStack.
3930/// For loop-free codes, this results in a correct sequential ordering.
3931///
3932/// Example:
3933/// bb1(0)
3934/// / \.
3935/// bb2(1) bb3(2)
3936/// \ / \.
3937/// bb4(3) bb5(4)
3938/// \ /
3939/// bb6(5)
3940///
3941/// Including loops requires additional processing. Whenever a loop header is
3942/// encountered, the corresponding loop is added to the @p LoopStack. Starting
3943/// from an empty schedule, we first process all RegionNodes that are within
3944/// this loop and complete the sequential schedule at this loop-level before
3945/// processing about any other nodes. To implement this
3946/// loop-nodes-first-processing, the reverse post-order traversal is
3947/// insufficient. Hence, we additionally check if the traversal yields
3948/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
3949/// These region-nodes are then queue and only traverse after the all nodes
3950/// within the current loop have been processed.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003951void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, ScopDetection &SD,
3952 LoopInfo &LI) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003953 Loop *OuterScopLoop = getLoopSurroundingRegion(getRegion(), LI);
3954
3955 ReversePostOrderTraversal<Region *> RTraversal(R);
3956 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
3957 std::deque<RegionNode *> DelayList;
3958 bool LastRNWaiting = false;
3959
3960 // Iterate over the region @p R in reverse post-order but queue
3961 // sub-regions/blocks iff they are not part of the last encountered but not
3962 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
3963 // that we queued the last sub-region/block from the reverse post-order
3964 // iterator. If it is set we have to explore the next sub-region/block from
3965 // the iterator (if any) to guarantee progress. If it is not set we first try
3966 // the next queued sub-region/blocks.
3967 while (!WorkList.empty() || !DelayList.empty()) {
3968 RegionNode *RN;
3969
3970 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
3971 RN = WorkList.front();
3972 WorkList.pop_front();
3973 LastRNWaiting = false;
3974 } else {
3975 RN = DelayList.front();
3976 DelayList.pop_front();
3977 }
3978
3979 Loop *L = getRegionNodeLoop(RN, LI);
3980 if (!getRegion().contains(L))
3981 L = OuterScopLoop;
3982
Tobias Grosser151ae322016-04-03 19:36:52 +00003983 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003984 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00003985 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003986 LastRNWaiting = true;
3987 DelayList.push_back(RN);
3988 continue;
3989 }
3990 LoopStack.push_back({L, nullptr, 0});
3991 }
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003992 buildSchedule(RN, LoopStack, SD, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003993 }
3994
3995 return;
3996}
3997
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003998void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003999 ScopDetection &SD, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004000
Tobias Grosser8362c262016-01-06 15:30:06 +00004001 if (RN->isSubRegion()) {
4002 auto *LocalRegion = RN->getNodeAs<Region>();
4003 if (!SD.isNonAffineSubRegion(LocalRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004004 buildSchedule(LocalRegion, LoopStack, SD, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004005 return;
4006 }
4007 }
Michael Kruse046dde42015-08-10 13:01:57 +00004008
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004009 auto &LoopData = LoopStack.back();
4010 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004011
Michael Kruse6f7721f2016-02-24 22:08:19 +00004012 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004013 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4014 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004015 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004016 }
4017
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004018 // Check if we just processed the last node in this loop. If we did, finalize
4019 // the loop by:
4020 //
4021 // - adding new schedule dimensions
4022 // - folding the resulting schedule into the parent loop schedule
4023 // - dropping the loop schedule from the LoopStack.
4024 //
4025 // Then continue to check surrounding loops, which might also have been
4026 // completed by this node.
4027 while (LoopData.L &&
4028 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004029 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004030 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004031
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004032 LoopStack.pop_back();
4033 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004034
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004035 if (Schedule) {
4036 auto *Domain = isl_schedule_get_domain(Schedule);
4037 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4038 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4039 NextLoopData.Schedule =
4040 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004041 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004042
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004043 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4044 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004045 }
Tobias Grosser75805372011-04-29 06:27:02 +00004046}
4047
Michael Kruse6f7721f2016-02-24 22:08:19 +00004048ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004049 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004050 if (StmtMapIt == StmtMap.end())
4051 return nullptr;
4052 return StmtMapIt->second;
4053}
4054
Michael Kruse6f7721f2016-02-24 22:08:19 +00004055ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4056 if (RN->isSubRegion())
4057 return getStmtFor(RN->getNodeAs<Region>());
4058 return getStmtFor(RN->getNodeAs<BasicBlock>());
4059}
4060
4061ScopStmt *Scop::getStmtFor(Region *R) const {
4062 ScopStmt *Stmt = getStmtFor(R->getEntry());
4063 assert(!Stmt || Stmt->getRegion() == R);
4064 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004065}
4066
Johannes Doerfert96425c22015-08-30 21:13:53 +00004067int Scop::getRelativeLoopDepth(const Loop *L) const {
4068 Loop *OuterLoop =
4069 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4070 if (!OuterLoop)
4071 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004072 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4073}
4074
Michael Krused868b5d2015-09-10 15:25:24 +00004075void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00004076 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00004077
4078 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
4079 // true, are not modeled as ordinary PHI nodes as they are not part of the
4080 // region. However, we model the operands in the predecessor blocks that are
4081 // part of the region as regular scalar accesses.
4082
4083 // If we can synthesize a PHI we can skip it, however only if it is in
4084 // the region. If it is not it can only be in the exit block of the region.
4085 // In this case we model the operands but not the PHI itself.
Michael Krusec7e0d9c2016-03-01 21:44:06 +00004086 auto *Scope = LI->getLoopFor(PHI->getParent());
4087 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R, Scope))
Michael Kruse7bf39442015-09-10 12:46:52 +00004088 return;
4089
4090 // PHI nodes are modeled as if they had been demoted prior to the SCoP
4091 // detection. Hence, the PHI is a load of a new memory location in which the
4092 // incoming value was written at the end of the incoming basic block.
4093 bool OnlyNonAffineSubRegionOperands = true;
4094 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
4095 Value *Op = PHI->getIncomingValue(u);
4096 BasicBlock *OpBB = PHI->getIncomingBlock(u);
4097
4098 // Do not build scalar dependences inside a non-affine subregion.
4099 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
4100 continue;
4101
4102 OnlyNonAffineSubRegionOperands = false;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004103 ensurePHIWrite(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00004104 }
4105
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004106 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
4107 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00004108 }
4109}
4110
Michael Kruse2e02d562016-02-06 09:19:40 +00004111void ScopInfo::buildScalarDependences(Instruction *Inst) {
4112 assert(!isa<PHINode>(Inst));
Michael Kruse7bf39442015-09-10 12:46:52 +00004113
Michael Kruse2e02d562016-02-06 09:19:40 +00004114 // Pull-in required operands.
4115 for (Use &Op : Inst->operands())
4116 ensureValueRead(Op.get(), Inst->getParent());
4117}
Michael Kruse7bf39442015-09-10 12:46:52 +00004118
Michael Kruse2e02d562016-02-06 09:19:40 +00004119void ScopInfo::buildEscapingDependences(Instruction *Inst) {
4120 Region *R = &scop->getRegion();
Michael Kruse7bf39442015-09-10 12:46:52 +00004121
Michael Kruse2e02d562016-02-06 09:19:40 +00004122 // Check for uses of this instruction outside the scop. Because we do not
4123 // iterate over such instructions and therefore did not "ensure" the existence
4124 // of a write, we must determine such use here.
4125 for (Use &U : Inst->uses()) {
4126 Instruction *UI = dyn_cast<Instruction>(U.getUser());
4127 if (!UI)
Michael Kruse7bf39442015-09-10 12:46:52 +00004128 continue;
4129
Michael Kruse2e02d562016-02-06 09:19:40 +00004130 BasicBlock *UseParent = getUseBlock(U);
4131 BasicBlock *UserParent = UI->getParent();
Michael Kruse7bf39442015-09-10 12:46:52 +00004132
Michael Kruse2e02d562016-02-06 09:19:40 +00004133 // An escaping value is either used by an instruction not within the scop,
4134 // or (when the scop region's exit needs to be simplified) by a PHI in the
4135 // scop's exit block. This is because region simplification before code
4136 // generation inserts new basic blocks before the PHI such that its incoming
4137 // blocks are not in the scop anymore.
4138 if (!R->contains(UseParent) ||
4139 (isa<PHINode>(UI) && UserParent == R->getExit() &&
4140 R->getExitingBlock())) {
4141 // At least one escaping use found.
4142 ensureValueWrite(Inst);
4143 break;
Michael Kruse7bf39442015-09-10 12:46:52 +00004144 }
4145 }
Michael Kruse7bf39442015-09-10 12:46:52 +00004146}
4147
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004148bool ScopInfo::buildAccessMultiDimFixed(
Michael Kruse70131d32016-01-27 17:09:17 +00004149 MemAccInst Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00004150 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4151 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse70131d32016-01-27 17:09:17 +00004152 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004153 Type *ElementType = Val->getType();
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004154 Value *Address = Inst.getPointerOperand();
Tobias Grosser5fd8c092015-09-17 17:28:15 +00004155 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00004156 const SCEVUnknown *BasePointer =
4157 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004158 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004159 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00004160
Michael Kruse37d136e2016-02-26 16:08:24 +00004161 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
4162 auto *Src = BitCast->getOperand(0);
4163 auto *SrcTy = Src->getType();
4164 auto *DstTy = BitCast->getType();
Johannes Doerfert41725a12016-04-08 19:20:03 +00004165 // Do not try to delinearize non-sized (opaque) pointers.
4166 if ((SrcTy->isPointerTy() && !SrcTy->getPointerElementType()->isSized()) ||
4167 (DstTy->isPointerTy() && !DstTy->getPointerElementType()->isSized())) {
4168 return false;
4169 }
Michael Kruse436c9062016-04-08 16:20:08 +00004170 if (SrcTy->isPointerTy() && DstTy->isPointerTy() &&
4171 DL->getTypeAllocSize(SrcTy->getPointerElementType()) ==
4172 DL->getTypeAllocSize(DstTy->getPointerElementType()))
Michael Kruse37d136e2016-02-26 16:08:24 +00004173 Address = Src;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00004174 }
Michael Kruse37d136e2016-02-26 16:08:24 +00004175
4176 auto *GEP = dyn_cast<GetElementPtrInst>(Address);
4177 if (!GEP)
4178 return false;
4179
4180 std::vector<const SCEV *> Subscripts;
4181 std::vector<int> Sizes;
4182 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
4183 auto *BasePtr = GEP->getOperand(0);
4184
Tobias Grosser535afd82016-04-05 06:23:45 +00004185 if (auto *BasePtrCast = dyn_cast<BitCastInst>(BasePtr))
4186 BasePtr = BasePtrCast->getOperand(0);
4187
4188 // Check for identical base pointers to ensure that we do not miss index
4189 // offsets that have been added before this GEP is applied.
4190 if (BasePtr != BasePointer->getValue())
4191 return false;
4192
Michael Kruse37d136e2016-02-26 16:08:24 +00004193 std::vector<const SCEV *> SizesSCEV;
4194
4195 for (auto *Subscript : Subscripts) {
4196 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +00004197 if (!isAffineExpr(R, L, Subscript, *SE, nullptr, &AccessILS))
Michael Kruse37d136e2016-02-26 16:08:24 +00004198 return false;
4199
4200 for (LoadInst *LInst : AccessILS)
4201 if (!ScopRIL.count(LInst))
4202 return false;
4203 }
4204
4205 if (Sizes.empty())
4206 return false;
4207
4208 for (auto V : Sizes)
4209 SizesSCEV.push_back(SE->getSCEV(
4210 ConstantInt::get(IntegerType::getInt64Ty(BasePtr->getContext()), V)));
4211
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004212 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, true,
Michael Kruse37d136e2016-02-26 16:08:24 +00004213 Subscripts, SizesSCEV, Val);
4214 return true;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004215}
4216
4217bool ScopInfo::buildAccessMultiDimParam(
4218 MemAccInst Inst, Loop *L, Region *R,
4219 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00004220 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Michael Kruse37d136e2016-02-26 16:08:24 +00004221 if (!PollyDelinearize)
4222 return false;
4223
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004224 Value *Address = Inst.getPointerOperand();
4225 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004226 Type *ElementType = Val->getType();
4227 unsigned ElementSize = DL->getTypeAllocSize(ElementType);
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004228 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004229 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004230
4231 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
4232 const SCEVUnknown *BasePointer =
4233 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
4234
4235 assert(BasePointer && "Could not find base pointer");
4236 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00004237
Michael Kruse7bf39442015-09-10 12:46:52 +00004238 auto AccItr = InsnToMemAcc.find(Inst);
Michael Kruse37d136e2016-02-26 16:08:24 +00004239 if (AccItr == InsnToMemAcc.end())
4240 return false;
Tobias Grosser5d51afe2016-02-02 16:46:45 +00004241
Michael Kruse37d136e2016-02-26 16:08:24 +00004242 std::vector<const SCEV *> Sizes(
4243 AccItr->second.Shape->DelinearizedSizes.begin(),
4244 AccItr->second.Shape->DelinearizedSizes.end());
4245 // Remove the element size. This information is already provided by the
4246 // ElementSize parameter. In case the element size of this access and the
4247 // element size used for delinearization differs the delinearization is
4248 // incorrect. Hence, we invalidate the scop.
4249 //
4250 // TODO: Handle delinearization with differing element sizes.
4251 auto DelinearizedSize =
4252 cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue();
4253 Sizes.pop_back();
4254 if (ElementSize != DelinearizedSize)
4255 scop->invalidate(DELINEARIZATION, Inst->getDebugLoc());
4256
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004257 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, true,
Michael Kruse37d136e2016-02-26 16:08:24 +00004258 AccItr->second.DelinearizedSubscripts, Sizes, Val);
4259 return true;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004260}
4261
Johannes Doerfertcea61932016-02-21 19:13:19 +00004262bool ScopInfo::buildAccessMemIntrinsic(
4263 MemAccInst Inst, Loop *L, Region *R,
4264 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4265 const InvariantLoadsSetTy &ScopRIL) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004266 auto *MemIntr = dyn_cast_or_null<MemIntrinsic>(Inst);
4267
4268 if (MemIntr == nullptr)
Johannes Doerfertcea61932016-02-21 19:13:19 +00004269 return false;
4270
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004271 auto *LengthVal = SE->getSCEVAtScope(MemIntr->getLength(), L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00004272 assert(LengthVal);
4273
Johannes Doerferta7920982016-02-25 14:08:48 +00004274 // Check if the length val is actually affine or if we overapproximate it
4275 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +00004276 bool LengthIsAffine = isAffineExpr(R, L, LengthVal, *SE, nullptr, &AccessILS);
Johannes Doerferta7920982016-02-25 14:08:48 +00004277 for (LoadInst *LInst : AccessILS)
4278 if (!ScopRIL.count(LInst))
4279 LengthIsAffine = false;
4280 if (!LengthIsAffine)
4281 LengthVal = nullptr;
4282
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004283 auto *DestPtrVal = MemIntr->getDest();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004284 assert(DestPtrVal);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004285
Johannes Doerfertcea61932016-02-21 19:13:19 +00004286 auto *DestAccFunc = SE->getSCEVAtScope(DestPtrVal, L);
4287 assert(DestAccFunc);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004288 // Ignore accesses to "NULL".
4289 // TODO: We could use this to optimize the region further, e.g., intersect
4290 // the context with
4291 // isl_set_complement(isl_set_params(getDomain()))
4292 // as we know it would be undefined to execute this instruction anyway.
4293 if (DestAccFunc->isZero())
4294 return true;
4295
Johannes Doerfertcea61932016-02-21 19:13:19 +00004296 auto *DestPtrSCEV = dyn_cast<SCEVUnknown>(SE->getPointerBase(DestAccFunc));
4297 assert(DestPtrSCEV);
4298 DestAccFunc = SE->getMinusSCEV(DestAccFunc, DestPtrSCEV);
4299 addArrayAccess(Inst, MemoryAccess::MUST_WRITE, DestPtrSCEV->getValue(),
4300 IntegerType::getInt8Ty(DestPtrVal->getContext()), false,
4301 {DestAccFunc, LengthVal}, {}, Inst.getValueOperand());
4302
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004303 auto *MemTrans = dyn_cast<MemTransferInst>(MemIntr);
4304 if (!MemTrans)
Johannes Doerfertcea61932016-02-21 19:13:19 +00004305 return true;
4306
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004307 auto *SrcPtrVal = MemTrans->getSource();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004308 assert(SrcPtrVal);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004309
Johannes Doerfertcea61932016-02-21 19:13:19 +00004310 auto *SrcAccFunc = SE->getSCEVAtScope(SrcPtrVal, L);
4311 assert(SrcAccFunc);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004312 // Ignore accesses to "NULL".
4313 // TODO: See above TODO
4314 if (SrcAccFunc->isZero())
4315 return true;
4316
Johannes Doerfertcea61932016-02-21 19:13:19 +00004317 auto *SrcPtrSCEV = dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccFunc));
4318 assert(SrcPtrSCEV);
4319 SrcAccFunc = SE->getMinusSCEV(SrcAccFunc, SrcPtrSCEV);
4320 addArrayAccess(Inst, MemoryAccess::READ, SrcPtrSCEV->getValue(),
4321 IntegerType::getInt8Ty(SrcPtrVal->getContext()), false,
4322 {SrcAccFunc, LengthVal}, {}, Inst.getValueOperand());
4323
4324 return true;
4325}
4326
Johannes Doerferta7920982016-02-25 14:08:48 +00004327bool ScopInfo::buildAccessCallInst(
4328 MemAccInst Inst, Loop *L, Region *R,
4329 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4330 const InvariantLoadsSetTy &ScopRIL) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004331 auto *CI = dyn_cast_or_null<CallInst>(Inst);
4332
4333 if (CI == nullptr)
Johannes Doerferta7920982016-02-25 14:08:48 +00004334 return false;
4335
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004336 if (CI->doesNotAccessMemory() || isIgnoredIntrinsic(CI))
Johannes Doerferta7920982016-02-25 14:08:48 +00004337 return true;
4338
4339 bool ReadOnly = false;
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004340 auto *AF = SE->getConstant(IntegerType::getInt64Ty(CI->getContext()), 0);
4341 auto *CalledFunction = CI->getCalledFunction();
Johannes Doerferta7920982016-02-25 14:08:48 +00004342 switch (AA->getModRefBehavior(CalledFunction)) {
4343 case llvm::FMRB_UnknownModRefBehavior:
4344 llvm_unreachable("Unknown mod ref behaviour cannot be represented.");
4345 case llvm::FMRB_DoesNotAccessMemory:
4346 return true;
4347 case llvm::FMRB_OnlyReadsMemory:
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004348 GlobalReads.push_back(CI);
Johannes Doerferta7920982016-02-25 14:08:48 +00004349 return true;
4350 case llvm::FMRB_OnlyReadsArgumentPointees:
4351 ReadOnly = true;
4352 // Fall through
4353 case llvm::FMRB_OnlyAccessesArgumentPointees:
4354 auto AccType = ReadOnly ? MemoryAccess::READ : MemoryAccess::MAY_WRITE;
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004355 for (const auto &Arg : CI->arg_operands()) {
Johannes Doerferta7920982016-02-25 14:08:48 +00004356 if (!Arg->getType()->isPointerTy())
4357 continue;
4358
4359 auto *ArgSCEV = SE->getSCEVAtScope(Arg, L);
4360 if (ArgSCEV->isZero())
4361 continue;
4362
4363 auto *ArgBasePtr = cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
4364 addArrayAccess(Inst, AccType, ArgBasePtr->getValue(),
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004365 ArgBasePtr->getType(), false, {AF}, {}, CI);
Johannes Doerferta7920982016-02-25 14:08:48 +00004366 }
4367 return true;
4368 }
4369
4370 return true;
4371}
4372
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004373void ScopInfo::buildAccessSingleDim(
4374 MemAccInst Inst, Loop *L, Region *R,
4375 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4376 const InvariantLoadsSetTy &ScopRIL) {
4377 Value *Address = Inst.getPointerOperand();
4378 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004379 Type *ElementType = Val->getType();
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004380 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004381 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004382
4383 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
4384 const SCEVUnknown *BasePointer =
4385 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
4386
4387 assert(BasePointer && "Could not find base pointer");
4388 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Michael Kruse7bf39442015-09-10 12:46:52 +00004389
4390 // Check if the access depends on a loop contained in a non-affine subregion.
4391 bool isVariantInNonAffineLoop = false;
4392 if (BoxedLoops) {
4393 SetVector<const Loop *> Loops;
4394 findLoops(AccessFunction, Loops);
4395 for (const Loop *L : Loops)
4396 if (BoxedLoops->count(L))
4397 isVariantInNonAffineLoop = true;
4398 }
4399
Johannes Doerfert09e36972015-10-07 20:17:36 +00004400 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +00004401 bool IsAffine = !isVariantInNonAffineLoop &&
4402 isAffineExpr(R, L, AccessFunction, *SE,
4403 BasePointer->getValue(), &AccessILS);
Johannes Doerfert09e36972015-10-07 20:17:36 +00004404
4405 for (LoadInst *LInst : AccessILS)
4406 if (!ScopRIL.count(LInst))
4407 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00004408
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004409 if (!IsAffine && AccType == MemoryAccess::MUST_WRITE)
4410 AccType = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00004411
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004412 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, IsAffine,
Tobias Grosser5d51afe2016-02-02 16:46:45 +00004413 {AccessFunction}, {}, Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00004414}
4415
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004416void ScopInfo::buildMemoryAccess(
4417 MemAccInst Inst, Loop *L, Region *R,
4418 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00004419 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004420
Johannes Doerfertcea61932016-02-21 19:13:19 +00004421 if (buildAccessMemIntrinsic(Inst, L, R, BoxedLoops, ScopRIL))
4422 return;
4423
Johannes Doerferta7920982016-02-25 14:08:48 +00004424 if (buildAccessCallInst(Inst, L, R, BoxedLoops, ScopRIL))
4425 return;
4426
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004427 if (buildAccessMultiDimFixed(Inst, L, R, BoxedLoops, ScopRIL))
4428 return;
4429
Hongbin Zheng22623202016-02-15 00:20:58 +00004430 if (buildAccessMultiDimParam(Inst, L, R, BoxedLoops, ScopRIL, InsnToMemAcc))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004431 return;
4432
4433 buildAccessSingleDim(Inst, L, R, BoxedLoops, ScopRIL);
4434}
4435
Hongbin Zheng22623202016-02-15 00:20:58 +00004436void ScopInfo::buildAccessFunctions(Region &R, Region &SR,
4437 const MapInsnToMemAcc &InsnToMemAcc) {
Michael Kruse7bf39442015-09-10 12:46:52 +00004438
4439 if (SD->isNonAffineSubRegion(&SR, &R)) {
4440 for (BasicBlock *BB : SR.blocks())
Hongbin Zheng22623202016-02-15 00:20:58 +00004441 buildAccessFunctions(R, *BB, InsnToMemAcc, &SR);
Michael Kruse7bf39442015-09-10 12:46:52 +00004442 return;
4443 }
4444
4445 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4446 if (I->isSubRegion())
Hongbin Zheng22623202016-02-15 00:20:58 +00004447 buildAccessFunctions(R, *I->getNodeAs<Region>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004448 else
Hongbin Zheng22623202016-02-15 00:20:58 +00004449 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004450}
4451
Johannes Doerferta8781032016-02-02 14:14:40 +00004452void ScopInfo::buildStmts(Region &R, Region &SR) {
Michael Krusecac948e2015-10-02 13:53:07 +00004453
Johannes Doerferta8781032016-02-02 14:14:40 +00004454 if (SD->isNonAffineSubRegion(&SR, &R)) {
Michael Krusecac948e2015-10-02 13:53:07 +00004455 scop->addScopStmt(nullptr, &SR);
4456 return;
4457 }
4458
4459 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4460 if (I->isSubRegion())
Johannes Doerferta8781032016-02-02 14:14:40 +00004461 buildStmts(R, *I->getNodeAs<Region>());
Michael Krusecac948e2015-10-02 13:53:07 +00004462 else
4463 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
4464}
4465
Michael Krused868b5d2015-09-10 15:25:24 +00004466void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
Hongbin Zheng22623202016-02-15 00:20:58 +00004467 const MapInsnToMemAcc &InsnToMemAcc,
Michael Krused868b5d2015-09-10 15:25:24 +00004468 Region *NonAffineSubRegion,
4469 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00004470 // We do not build access functions for error blocks, as they may contain
4471 // instructions we can not model.
Johannes Doerfertc36d39b2016-02-02 14:14:20 +00004472 if (isErrorBlock(BB, R, *LI, *DT) && !IsExitBlock)
Tobias Grosser910cf262015-11-11 20:15:49 +00004473 return;
4474
Michael Kruse7bf39442015-09-10 12:46:52 +00004475 Loop *L = LI->getLoopFor(&BB);
4476
4477 // The set of loops contained in non-affine subregions that are part of R.
4478 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
4479
Johannes Doerfert09e36972015-10-07 20:17:36 +00004480 // The set of loads that are required to be invariant.
4481 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
4482
Michael Kruse2e02d562016-02-06 09:19:40 +00004483 for (Instruction &Inst : BB) {
4484 PHINode *PHI = dyn_cast<PHINode>(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004485 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00004486 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00004487
4488 // For the exit block we stop modeling after the last PHI node.
4489 if (!PHI && IsExitBlock)
4490 break;
4491
Johannes Doerfert09e36972015-10-07 20:17:36 +00004492 // TODO: At this point we only know that elements of ScopRIL have to be
4493 // invariant and will be hoisted for the SCoP to be processed. Though,
4494 // there might be other invariant accesses that will be hoisted and
4495 // that would allow to make a non-affine access affine.
Michael Kruse70131d32016-01-27 17:09:17 +00004496 if (auto MemInst = MemAccInst::dyn_cast(Inst))
Hongbin Zheng22623202016-02-15 00:20:58 +00004497 buildMemoryAccess(MemInst, L, &R, BoxedLoops, ScopRIL, InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004498
Michael Kruse2e02d562016-02-06 09:19:40 +00004499 if (isIgnoredIntrinsic(&Inst))
Michael Kruse7bf39442015-09-10 12:46:52 +00004500 continue;
4501
Tobias Grosser0904c692016-03-16 23:33:54 +00004502 // PHI nodes have already been modeled above and TerminatorInsts that are
4503 // not part of a non-affine subregion are fully modeled and regenerated
4504 // from the polyhedral domains. Hence, they do not need to be modeled as
4505 // explicit data dependences.
4506 if (!PHI && (!isa<TerminatorInst>(&Inst) || NonAffineSubRegion))
Michael Kruse2e02d562016-02-06 09:19:40 +00004507 buildScalarDependences(&Inst);
Tobias Grosser0904c692016-03-16 23:33:54 +00004508
Michael Kruse2e02d562016-02-06 09:19:40 +00004509 if (!IsExitBlock)
4510 buildEscapingDependences(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004511 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00004512}
Michael Kruse7bf39442015-09-10 12:46:52 +00004513
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004514MemoryAccess *ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004515 MemoryAccess::AccessType AccType,
4516 Value *BaseAddress, Type *ElementType,
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004517 bool Affine, Value *AccessValue,
4518 ArrayRef<const SCEV *> Subscripts,
4519 ArrayRef<const SCEV *> Sizes,
4520 ScopArrayInfo::MemoryKind Kind) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004521 ScopStmt *Stmt = scop->getStmtFor(BB);
Michael Krusecac948e2015-10-02 13:53:07 +00004522
4523 // Do not create a memory access for anything not in the SCoP. It would be
4524 // ignored anyway.
4525 if (!Stmt)
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004526 return nullptr;
Michael Krusecac948e2015-10-02 13:53:07 +00004527
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00004528 AccFuncSetType &AccList = scop->getOrCreateAccessFunctions(BB);
Michael Krusee2bccbb2015-09-18 19:59:43 +00004529 Value *BaseAddr = BaseAddress;
4530 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
4531
Tobias Grosserf4f68702015-12-14 15:05:37 +00004532 bool isKnownMustAccess = false;
4533
4534 // Accesses in single-basic block statements are always excuted.
4535 if (Stmt->isBlockStmt())
4536 isKnownMustAccess = true;
4537
4538 if (Stmt->isRegionStmt()) {
4539 // Accesses that dominate the exit block of a non-affine region are always
4540 // executed. In non-affine regions there may exist MK_Values that do not
4541 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs
4542 // only if there is at most one PHI_WRITE in the non-affine region.
4543 if (DT->dominates(BB, Stmt->getRegion()->getExit()))
4544 isKnownMustAccess = true;
4545 }
4546
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004547 // Non-affine PHI writes do not "happen" at a particular instruction, but
4548 // after exiting the statement. Therefore they are guaranteed execute and
4549 // overwrite the old value.
4550 if (Kind == ScopArrayInfo::MK_PHI || Kind == ScopArrayInfo::MK_ExitPHI)
4551 isKnownMustAccess = true;
4552
Johannes Doerfertcea61932016-02-21 19:13:19 +00004553 if (!isKnownMustAccess && AccType == MemoryAccess::MUST_WRITE)
4554 AccType = MemoryAccess::MAY_WRITE;
Michael Krusecac948e2015-10-02 13:53:07 +00004555
Johannes Doerfertcea61932016-02-21 19:13:19 +00004556 AccList.emplace_back(Stmt, Inst, AccType, BaseAddress, ElementType, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00004557 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00004558 Stmt->addAccess(&AccList.back());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004559 return &AccList.back();
Michael Kruse7bf39442015-09-10 12:46:52 +00004560}
4561
Michael Kruse70131d32016-01-27 17:09:17 +00004562void ScopInfo::addArrayAccess(MemAccInst MemAccInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004563 MemoryAccess::AccessType AccType,
4564 Value *BaseAddress, Type *ElementType,
4565 bool IsAffine, ArrayRef<const SCEV *> Subscripts,
Tobias Grossera535dff2015-12-13 19:59:01 +00004566 ArrayRef<const SCEV *> Sizes,
4567 Value *AccessValue) {
Johannes Doerferta7920982016-02-25 14:08:48 +00004568 ArrayBasePointers.insert(BaseAddress);
Hongbin Zhengf3d66122016-02-26 09:47:11 +00004569 addMemoryAccess(MemAccInst->getParent(), MemAccInst, AccType, BaseAddress,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004570 ElementType, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00004571 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004572}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004573
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004574void ScopInfo::ensureValueWrite(Instruction *Inst) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004575 ScopStmt *Stmt = scop->getStmtFor(Inst);
Michael Kruse436db622016-01-26 13:33:10 +00004576
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004577 // Inst not defined within this SCoP.
Michael Kruse436db622016-01-26 13:33:10 +00004578 if (!Stmt)
4579 return;
4580
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004581 // Do not process further if the instruction is already written.
4582 if (Stmt->lookupValueWriteOf(Inst))
Michael Kruse436db622016-01-26 13:33:10 +00004583 return;
4584
Johannes Doerfertcea61932016-02-21 19:13:19 +00004585 addMemoryAccess(Inst->getParent(), Inst, MemoryAccess::MUST_WRITE, Inst,
4586 Inst->getType(), true, Inst, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004587 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004588}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004589
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004590void ScopInfo::ensureValueRead(Value *V, BasicBlock *UserBB) {
Michael Krusefd463082016-01-27 22:51:56 +00004591
Michael Kruse2e02d562016-02-06 09:19:40 +00004592 // There cannot be an "access" for literal constants. BasicBlock references
4593 // (jump destinations) also never change.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004594 if ((isa<Constant>(V) && !isa<GlobalVariable>(V)) || isa<BasicBlock>(V))
Michael Kruse2e02d562016-02-06 09:19:40 +00004595 return;
4596
Michael Krusefd463082016-01-27 22:51:56 +00004597 // If the instruction can be synthesized and the user is in the region we do
4598 // not need to add a value dependences.
4599 Region &ScopRegion = scop->getRegion();
Michael Krusec7e0d9c2016-03-01 21:44:06 +00004600 auto *Scope = LI->getLoopFor(UserBB);
4601 if (canSynthesize(V, LI, SE, &ScopRegion, Scope))
Michael Krusefd463082016-01-27 22:51:56 +00004602 return;
4603
Michael Kruse2e02d562016-02-06 09:19:40 +00004604 // Do not build scalar dependences for required invariant loads as we will
4605 // hoist them later on anyway or drop the SCoP if we cannot.
Johannes Doerferta90943d2016-02-21 16:37:25 +00004606 auto *ScopRIL = SD->getRequiredInvariantLoads(&ScopRegion);
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004607 if (ScopRIL->count(dyn_cast<LoadInst>(V)))
Michael Kruse2e02d562016-02-06 09:19:40 +00004608 return;
4609
4610 // Determine the ScopStmt containing the value's definition and use. There is
4611 // no defining ScopStmt if the value is a function argument, a global value,
4612 // or defined outside the SCoP.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004613 Instruction *ValueInst = dyn_cast<Instruction>(V);
Michael Kruse6f7721f2016-02-24 22:08:19 +00004614 ScopStmt *ValueStmt = ValueInst ? scop->getStmtFor(ValueInst) : nullptr;
Michael Kruse2e02d562016-02-06 09:19:40 +00004615
Michael Kruse6f7721f2016-02-24 22:08:19 +00004616 ScopStmt *UserStmt = scop->getStmtFor(UserBB);
Michael Krusead28e5a2016-01-26 13:33:15 +00004617
4618 // We do not model uses outside the scop.
4619 if (!UserStmt)
4620 return;
4621
Michael Kruse2e02d562016-02-06 09:19:40 +00004622 // Add MemoryAccess for invariant values only if requested.
4623 if (!ModelReadOnlyScalars && !ValueStmt)
4624 return;
4625
4626 // Ignore use-def chains within the same ScopStmt.
4627 if (ValueStmt == UserStmt)
4628 return;
4629
Michael Krusead28e5a2016-01-26 13:33:15 +00004630 // Do not create another MemoryAccess for reloading the value if one already
4631 // exists.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004632 if (UserStmt->lookupValueReadOf(V))
Michael Krusead28e5a2016-01-26 13:33:15 +00004633 return;
4634
Johannes Doerfert2075b5d2016-04-03 11:16:00 +00004635 // For exit PHIs use the MK_ExitPHI MemoryKind not MK_Value.
4636 ScopArrayInfo::MemoryKind Kind = ScopArrayInfo::MK_Value;
4637 if (!ValueStmt && isa<PHINode>(V))
4638 Kind = ScopArrayInfo::MK_ExitPHI;
4639
Johannes Doerfertcea61932016-02-21 19:13:19 +00004640 addMemoryAccess(UserBB, nullptr, MemoryAccess::READ, V, V->getType(), true, V,
Johannes Doerfert2075b5d2016-04-03 11:16:00 +00004641 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(), Kind);
Michael Kruse2e02d562016-02-06 09:19:40 +00004642 if (ValueInst)
4643 ensureValueWrite(ValueInst);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004644}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004645
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004646void ScopInfo::ensurePHIWrite(PHINode *PHI, BasicBlock *IncomingBlock,
4647 Value *IncomingValue, bool IsExitBlock) {
Johannes Doerfert57c5f0b2016-04-05 13:44:21 +00004648 // As the incoming block might turn out to be an error statement ensure we
4649 // will create an exit PHI SAI object. It is needed during code generation
4650 // and would be created later anyway.
4651 if (IsExitBlock)
4652 scop->getOrCreateScopArrayInfo(PHI, PHI->getType(), {},
4653 ScopArrayInfo::MK_ExitPHI);
4654
Michael Kruse6f7721f2016-02-24 22:08:19 +00004655 ScopStmt *IncomingStmt = scop->getStmtFor(IncomingBlock);
Michael Kruse2e02d562016-02-06 09:19:40 +00004656 if (!IncomingStmt)
4657 return;
4658
4659 // Take care for the incoming value being available in the incoming block.
4660 // This must be done before the check for multiple PHI writes because multiple
4661 // exiting edges from subregion each can be the effective written value of the
4662 // subregion. As such, all of them must be made available in the subregion
4663 // statement.
4664 ensureValueRead(IncomingValue, IncomingBlock);
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004665
4666 // Do not add more than one MemoryAccess per PHINode and ScopStmt.
4667 if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) {
4668 assert(Acc->getAccessInstruction() == PHI);
4669 Acc->addIncoming(IncomingBlock, IncomingValue);
4670 return;
4671 }
4672
4673 MemoryAccess *Acc = addMemoryAccess(
Michael Kruse375cb5f2016-02-24 22:08:24 +00004674 IncomingStmt->getEntryBlock(), PHI, MemoryAccess::MUST_WRITE, PHI,
4675 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4676 ArrayRef<const SCEV *>(),
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004677 IsExitBlock ? ScopArrayInfo::MK_ExitPHI : ScopArrayInfo::MK_PHI);
4678 assert(Acc);
4679 Acc->addIncoming(IncomingBlock, IncomingValue);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004680}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004681
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004682void ScopInfo::addPHIReadAccess(PHINode *PHI) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00004683 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI,
4684 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4685 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004686}
4687
Michael Krusedaf66942015-12-13 22:10:37 +00004688void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00004689 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Michael Kruse09eb4452016-03-03 22:10:47 +00004690 scop.reset(new Scop(R, *SE, *LI, MaxLoopDepth));
Michael Kruse7bf39442015-09-10 12:46:52 +00004691
Johannes Doerferta8781032016-02-02 14:14:40 +00004692 buildStmts(R, R);
Hongbin Zheng22623202016-02-15 00:20:58 +00004693 buildAccessFunctions(R, R, *SD->getInsnToMemAccMap(&R));
Michael Kruse7bf39442015-09-10 12:46:52 +00004694
4695 // In case the region does not have an exiting block we will later (during
4696 // code generation) split the exit block. This will move potential PHI nodes
4697 // from the current exit block into the new region exiting block. Hence, PHI
4698 // nodes that are at this point not part of the region will be.
4699 // To handle these PHI nodes later we will now model their operands as scalar
4700 // accesses. Note that we do not model anything in the exit block if we have
4701 // an exiting block in the region, as there will not be any splitting later.
4702 if (!R.getExitingBlock())
Hongbin Zheng22623202016-02-15 00:20:58 +00004703 buildAccessFunctions(R, *R.getExit(), *SD->getInsnToMemAccMap(&R), nullptr,
4704 /* IsExitBlock */ true);
Michael Kruse7bf39442015-09-10 12:46:52 +00004705
Johannes Doerferta7920982016-02-25 14:08:48 +00004706 // Create memory accesses for global reads since all arrays are now known.
4707 auto *AF = SE->getConstant(IntegerType::getInt64Ty(SE->getContext()), 0);
4708 for (auto *GlobalRead : GlobalReads)
4709 for (auto *BP : ArrayBasePointers)
4710 addArrayAccess(MemAccInst(GlobalRead), MemoryAccess::READ, BP,
4711 BP->getType(), false, {AF}, {}, GlobalRead);
4712
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004713 scop->init(*AA, AC, *SD, *DT, *LI);
Michael Kruse7bf39442015-09-10 12:46:52 +00004714}
4715
Michael Krused868b5d2015-09-10 15:25:24 +00004716void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00004717 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00004718 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00004719 return;
4720 }
4721
Michael Kruse9d080092015-09-11 21:41:48 +00004722 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00004723}
4724
Hongbin Zhengfec32802016-02-13 15:13:02 +00004725void ScopInfo::clear() { scop.reset(); }
Michael Kruse7bf39442015-09-10 12:46:52 +00004726
4727//===----------------------------------------------------------------------===//
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004728ScopInfo::ScopInfo() : RegionPass(ID) {}
Tobias Grosserb76f38532011-08-20 11:11:25 +00004729
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004730ScopInfo::~ScopInfo() { clear(); }
Tobias Grosserb76f38532011-08-20 11:11:25 +00004731
Tobias Grosser75805372011-04-29 06:27:02 +00004732void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00004733 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00004734 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00004735 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00004736 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4737 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004738 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004739 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00004740 AU.setPreservesAll();
4741}
4742
4743bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004744 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004745
Michael Krused868b5d2015-09-10 15:25:24 +00004746 if (!SD->isMaxRegionInScop(*R))
4747 return false;
4748
4749 Function *F = R->getEntry()->getParent();
4750 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4751 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4752 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Johannes Doerferta1f291e2016-02-02 14:15:13 +00004753 DL = &F->getParent()->getDataLayout();
Michael Krusedaf66942015-12-13 22:10:37 +00004754 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004755 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004756
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004757 DebugLoc Beg, End;
4758 getDebugLocations(R, Beg, End);
4759 std::string Msg = "SCoP begins here.";
4760 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4761
Michael Krusedaf66942015-12-13 22:10:37 +00004762 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004763
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004764 DEBUG(scop->print(dbgs()));
4765
Michael Kruseafe06702015-10-02 16:33:27 +00004766 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004767 Msg = "SCoP ends here but was dismissed.";
Hongbin Zhengfec32802016-02-13 15:13:02 +00004768 scop.reset();
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004769 } else {
4770 Msg = "SCoP ends here.";
4771 ++ScopFound;
4772 if (scop->getMaxLoopDepth() > 0)
4773 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004774 }
4775
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004776 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4777
Tobias Grosser75805372011-04-29 06:27:02 +00004778 return false;
4779}
4780
4781char ScopInfo::ID = 0;
4782
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004783Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4784
Tobias Grosser73600b82011-10-08 00:30:40 +00004785INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4786 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004787 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004788INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004789INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004790INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004791INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004792INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004793INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004794INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004795INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4796 "Polly - Create polyhedral description of Scops", false,
4797 false)