blob: 3cb53299ed7dadcfc621af2b620ae0f3b451b998 [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 Grosser75805372011-04-29 06:27:02 +000020#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000021#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000022#include "polly/ScopInfo.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 Grosserf4c24b22015-04-05 13:11:54 +000026#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000027#include "llvm/ADT/PostOrderIterator.h"
28#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000029#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000030#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000031#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000032#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000033#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000034#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000035#include "llvm/Analysis/RegionIterator.h"
36#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000037#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000038#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000039#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000040#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000041#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000042#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000043#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000044#include "isl/schedule.h"
45#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/set.h"
47#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000048#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000049#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000050#include <sstream>
51#include <string>
52#include <vector>
53
54using namespace llvm;
55using namespace polly;
56
Chandler Carruth95fef942014-04-22 03:30:19 +000057#define DEBUG_TYPE "polly-scops"
58
Tobias Grosser74394f02013-01-14 22:40:23 +000059STATISTIC(ScopFound, "Number of valid Scops");
60STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000061
Michael Kruse7bf39442015-09-10 12:46:52 +000062static cl::opt<bool> ModelReadOnlyScalars(
63 "polly-analyze-read-only-scalars",
64 cl::desc("Model read-only scalar values in the scop description"),
65 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
66
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000067// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000068// operations can overflow easily. Additive reductions and bit operations
69// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000070static cl::opt<bool> DisableMultiplicativeReductions(
71 "polly-disable-multiplicative-reductions",
72 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
73 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000074
Johannes Doerfert9143d672014-09-27 11:02:39 +000075static cl::opt<unsigned> RunTimeChecksMaxParameters(
76 "polly-rtc-max-parameters",
77 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
78 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
79
Tobias Grosser71500722015-03-28 15:11:14 +000080static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
81 "polly-rtc-max-arrays-per-group",
82 cl::desc("The maximal number of arrays to compare in each alias group."),
83 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000084static cl::opt<std::string> UserContextStr(
85 "polly-context", cl::value_desc("isl parameter set"),
86 cl::desc("Provide additional constraints on the context parameters"),
87 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000088
Tobias Grosserd83b8a82015-08-20 19:08:11 +000089static cl::opt<bool> DetectReductions("polly-detect-reductions",
90 cl::desc("Detect and exploit reductions"),
91 cl::Hidden, cl::ZeroOrMore,
92 cl::init(true), cl::cat(PollyCategory));
93
Michael Kruse7bf39442015-09-10 12:46:52 +000094//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +000095
Michael Kruse046dde42015-08-10 13:01:57 +000096// Create a sequence of two schedules. Either argument may be null and is
97// interpreted as the empty schedule. Can also return null if both schedules are
98// empty.
99static __isl_give isl_schedule *
100combineInSequence(__isl_take isl_schedule *Prev,
101 __isl_take isl_schedule *Succ) {
102 if (!Prev)
103 return Succ;
104 if (!Succ)
105 return Prev;
106
107 return isl_schedule_sequence(Prev, Succ);
108}
109
Johannes Doerferte7044942015-02-24 11:58:30 +0000110static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
111 const ConstantRange &Range,
112 int dim,
113 enum isl_dim_type type) {
114 isl_val *V;
115 isl_ctx *ctx = isl_set_get_ctx(S);
116
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000117 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
118 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000119 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000120 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
121
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000122 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000123 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000124 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000125 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000126 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
127
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000128 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000129 return isl_set_union(SLB, SUB);
130 else
131 return isl_set_intersect(SLB, SUB);
132}
133
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000134static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
135 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
136 if (!BasePtrLI)
137 return nullptr;
138
139 if (!S->getRegion().contains(BasePtrLI))
140 return nullptr;
141
142 ScalarEvolution &SE = *S->getSE();
143
144 auto *OriginBaseSCEV =
145 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
146 if (!OriginBaseSCEV)
147 return nullptr;
148
149 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
150 if (!OriginBaseSCEVUnknown)
151 return nullptr;
152
153 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue());
154}
155
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000156ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000157 ArrayRef<const SCEV *> Sizes, bool IsPHI, Scop *S)
158 : BasePtr(BasePtr), ElementType(ElementType), IsPHI(IsPHI), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000159 std::string BasePtrName =
160 getIslCompatibleName("MemRef_", BasePtr, IsPHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000161 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000162
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000163 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000164 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
165 if (BasePtrOriginSAI)
166 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000167}
168
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000169__isl_give isl_space *ScopArrayInfo::getSpace() const {
170 auto Space =
171 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
172 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
173 return Space;
174}
175
Tobias Grosser8286b832015-11-02 11:29:32 +0000176bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000177 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
178 int ExtraDimsNew = NewSizes.size() - SharedDims;
179 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000180 for (int i = 0; i < SharedDims; i++)
181 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
182 return false;
183
184 if (DimensionSizes.size() >= NewSizes.size())
185 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000186
187 DimensionSizes.clear();
188 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
189 NewSizes.end());
190 for (isl_pw_aff *Size : DimensionSizesPw)
191 isl_pw_aff_free(Size);
192 DimensionSizesPw.clear();
193 for (const SCEV *Expr : DimensionSizes) {
194 isl_pw_aff *Size = S.getPwAff(Expr);
195 DimensionSizesPw.push_back(Size);
196 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000197 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000198}
199
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000200ScopArrayInfo::~ScopArrayInfo() {
201 isl_id_free(Id);
202 for (isl_pw_aff *Size : DimensionSizesPw)
203 isl_pw_aff_free(Size);
204}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000205
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000206std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
207
208int ScopArrayInfo::getElemSizeInBytes() const {
209 return ElementType->getPrimitiveSizeInBits() / 8;
210}
211
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000212isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
213
214void ScopArrayInfo::dump() const { print(errs()); }
215
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000216void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000217 OS.indent(8) << *getElementType() << " " << getName() << "[*]";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000218 for (unsigned u = 0; u < getNumberOfDimensions(); u++) {
219 OS << "[";
220
221 if (SizeAsPwAff)
222 OS << " " << DimensionSizesPw[u] << " ";
223 else
224 OS << *DimensionSizes[u];
225
226 OS << "]";
227 }
228
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000229 if (BasePtrOriginSAI)
230 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
231
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000232 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000233}
234
235const ScopArrayInfo *
236ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
237 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
238 assert(Id && "Output dimension didn't have an ID");
239 return getFromId(Id);
240}
241
242const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
243 void *User = isl_id_get_user(Id);
244 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
245 isl_id_free(Id);
246 return SAI;
247}
248
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000249void MemoryAccess::updateDimensionality() {
250 auto ArraySpace = getScopArrayInfo()->getSpace();
251 auto AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
252
253 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
254 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
255 auto DimsMissing = DimsArray - DimsAccess;
256
257 auto Map = isl_map_from_domain_and_range(isl_set_universe(AccessSpace),
258 isl_set_universe(ArraySpace));
259
260 for (unsigned i = 0; i < DimsMissing; i++)
261 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
262
263 for (unsigned i = DimsMissing; i < DimsArray; i++)
264 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
265
266 AccessRelation = isl_map_apply_range(AccessRelation, Map);
267}
268
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000269const std::string
270MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
271 switch (RT) {
272 case MemoryAccess::RT_NONE:
273 llvm_unreachable("Requested a reduction operator string for a memory "
274 "access which isn't a reduction");
275 case MemoryAccess::RT_ADD:
276 return "+";
277 case MemoryAccess::RT_MUL:
278 return "*";
279 case MemoryAccess::RT_BOR:
280 return "|";
281 case MemoryAccess::RT_BXOR:
282 return "^";
283 case MemoryAccess::RT_BAND:
284 return "&";
285 }
286 llvm_unreachable("Unknown reduction type");
287 return "";
288}
289
Johannes Doerfertf6183392014-07-01 20:52:51 +0000290/// @brief Return the reduction type for a given binary operator
291static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
292 const Instruction *Load) {
293 if (!BinOp)
294 return MemoryAccess::RT_NONE;
295 switch (BinOp->getOpcode()) {
296 case Instruction::FAdd:
297 if (!BinOp->hasUnsafeAlgebra())
298 return MemoryAccess::RT_NONE;
299 // Fall through
300 case Instruction::Add:
301 return MemoryAccess::RT_ADD;
302 case Instruction::Or:
303 return MemoryAccess::RT_BOR;
304 case Instruction::Xor:
305 return MemoryAccess::RT_BXOR;
306 case Instruction::And:
307 return MemoryAccess::RT_BAND;
308 case Instruction::FMul:
309 if (!BinOp->hasUnsafeAlgebra())
310 return MemoryAccess::RT_NONE;
311 // Fall through
312 case Instruction::Mul:
313 if (DisableMultiplicativeReductions)
314 return MemoryAccess::RT_NONE;
315 return MemoryAccess::RT_MUL;
316 default:
317 return MemoryAccess::RT_NONE;
318 }
319}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000320
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000321/// @brief Derive the individual index expressions from a GEP instruction
322///
323/// This function optimistically assumes the GEP references into a fixed size
324/// array. If this is actually true, this function returns a list of array
325/// subscript expressions as SCEV as well as a list of integers describing
326/// the size of the individual array dimensions. Both lists have either equal
327/// length of the size list is one element shorter in case there is no known
328/// size available for the outermost array dimension.
329///
330/// @param GEP The GetElementPtr instruction to analyze.
331///
332/// @return A tuple with the subscript expressions and the dimension sizes.
333static std::tuple<std::vector<const SCEV *>, std::vector<int>>
334getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
335 std::vector<const SCEV *> Subscripts;
336 std::vector<int> Sizes;
337
338 Type *Ty = GEP->getPointerOperandType();
339
340 bool DroppedFirstDim = false;
341
Michael Kruse26ed65e2015-09-24 17:32:49 +0000342 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000343
344 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
345
346 if (i == 1) {
347 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
348 Ty = PtrTy->getElementType();
349 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
350 Ty = ArrayTy->getElementType();
351 } else {
352 Subscripts.clear();
353 Sizes.clear();
354 break;
355 }
356 if (auto Const = dyn_cast<SCEVConstant>(Expr))
357 if (Const->getValue()->isZero()) {
358 DroppedFirstDim = true;
359 continue;
360 }
361 Subscripts.push_back(Expr);
362 continue;
363 }
364
365 auto ArrayTy = dyn_cast<ArrayType>(Ty);
366 if (!ArrayTy) {
367 Subscripts.clear();
368 Sizes.clear();
369 break;
370 }
371
372 Subscripts.push_back(Expr);
373 if (!(DroppedFirstDim && i == 2))
374 Sizes.push_back(ArrayTy->getNumElements());
375
376 Ty = ArrayTy->getElementType();
377 }
378
379 return std::make_tuple(Subscripts, Sizes);
380}
381
Tobias Grosser75805372011-04-29 06:27:02 +0000382MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000383 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000384 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000385 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000386}
387
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000388const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
389 isl_id *ArrayId = getArrayId();
390 void *User = isl_id_get_user(ArrayId);
391 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
392 isl_id_free(ArrayId);
393 return SAI;
394}
395
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000396__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000397 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
398}
399
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000400__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
401 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000402 isl_map *Schedule, *ScheduledAccRel;
403 isl_union_set *UDomain;
404
405 UDomain = isl_union_set_from_set(getStatement()->getDomain());
406 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
407 Schedule = isl_map_from_union_map(USchedule);
408 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
409 return isl_pw_multi_aff_from_map(ScheduledAccRel);
410}
411
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000412__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000413 return isl_map_copy(AccessRelation);
414}
415
Johannes Doerferta99130f2014-10-13 12:58:03 +0000416std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000417 return stringFromIslObj(AccessRelation);
418}
419
Johannes Doerferta99130f2014-10-13 12:58:03 +0000420__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000421 return isl_map_get_space(AccessRelation);
422}
423
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000424__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000425 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000426}
427
Tobias Grosser6f730082015-09-05 07:46:47 +0000428std::string MemoryAccess::getNewAccessRelationStr() const {
429 return stringFromIslObj(NewAccessRelation);
430}
431
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000432__isl_give isl_basic_map *
433MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000434 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000435 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000436
Tobias Grosser084d8f72012-05-29 09:29:44 +0000437 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000438 isl_basic_set_universe(Statement->getDomainSpace()),
439 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000440}
441
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000442// Formalize no out-of-bound access assumption
443//
444// When delinearizing array accesses we optimistically assume that the
445// delinearized accesses do not access out of bound locations (the subscript
446// expression of each array evaluates for each statement instance that is
447// executed to a value that is larger than zero and strictly smaller than the
448// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000449// dimension for which we do not need to assume any upper bound. At this point
450// we formalize this assumption to ensure that at code generation time the
451// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000452//
453// To find the set of constraints necessary to avoid out of bound accesses, we
454// first build the set of data locations that are not within array bounds. We
455// then apply the reverse access relation to obtain the set of iterations that
456// may contain invalid accesses and reduce this set of iterations to the ones
457// that are actually executed by intersecting them with the domain of the
458// statement. If we now project out all loop dimensions, we obtain a set of
459// parameters that may cause statement instances to be executed that may
460// possibly yield out of bound memory accesses. The complement of these
461// constraints is the set of constraints that needs to be assumed to ensure such
462// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000463void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000464 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000465 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Michael Krusee2bccbb2015-09-18 19:59:43 +0000466 for (int i = 1, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000467 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
468 isl_pw_aff *Var =
469 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
470 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
471
472 isl_set *DimOutside;
473
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000474 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Michael Krusee2bccbb2015-09-18 19:59:43 +0000475 isl_pw_aff *SizeE = Statement->getPwAff(Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000476
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000477 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
478 Statement->getNumIterators());
479 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
480 isl_space_dim(Space, isl_dim_set));
481 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
482 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000483
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000484 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000485
486 Outside = isl_set_union(Outside, DimOutside);
487 }
488
489 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
490 Outside = isl_set_intersect(Outside, Statement->getDomain());
491 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000492
493 // Remove divs to avoid the construction of overly complicated assumptions.
494 // Doing so increases the set of parameter combinations that are assumed to
495 // not appear. This is always save, but may make the resulting run-time check
496 // bail out more often than strictly necessary.
497 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000498 Outside = isl_set_complement(Outside);
499 Statement->getParent()->addAssumption(Outside);
500 isl_space_free(Space);
501}
502
Johannes Doerferte7044942015-02-24 11:58:30 +0000503void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
504 ScalarEvolution *SE = Statement->getParent()->getSE();
505
506 Value *Ptr = getPointerOperand(*getAccessInstruction());
507 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
508 return;
509
510 auto *PtrSCEV = SE->getSCEV(Ptr);
511 if (isa<SCEVCouldNotCompute>(PtrSCEV))
512 return;
513
514 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
515 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
516 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
517
518 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
519 if (Range.isFullSet())
520 return;
521
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000522 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000523 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000524 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
525 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
526
527 auto Min = LB.sdiv(APInt(BW, ElementSize));
528 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000529
530 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
531 AccessRange =
532 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
533 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
534}
535
Michael Krusee2bccbb2015-09-18 19:59:43 +0000536__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000537 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000538 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000539
540 for (int i = Size - 2; i >= 0; --i) {
541 isl_space *Space;
542 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000543 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000544
545 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
546 isl_pw_aff_free(DimSize);
547 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
548
549 Space = isl_map_get_space(AccessRelation);
550 Space = isl_space_map_from_set(isl_space_range(Space));
551 Space = isl_space_align_params(Space, SpaceSize);
552
553 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
554 isl_id_free(ParamId);
555
556 MapOne = isl_map_universe(isl_space_copy(Space));
557 for (int j = 0; j < Size; ++j)
558 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
559 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
560
561 MapTwo = isl_map_universe(isl_space_copy(Space));
562 for (int j = 0; j < Size; ++j)
563 if (j < i || j > i + 1)
564 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
565
566 isl_local_space *LS = isl_local_space_from_space(Space);
567 isl_constraint *C;
568 C = isl_equality_alloc(isl_local_space_copy(LS));
569 C = isl_constraint_set_constant_si(C, -1);
570 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
571 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
572 MapTwo = isl_map_add_constraint(MapTwo, C);
573 C = isl_equality_alloc(LS);
574 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
575 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
576 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
577 MapTwo = isl_map_add_constraint(MapTwo, C);
578 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
579
580 MapOne = isl_map_union(MapOne, MapTwo);
581 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
582 }
583 return AccessRelation;
584}
585
Michael Krusee2bccbb2015-09-18 19:59:43 +0000586void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
587 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000588
Michael Krusee2bccbb2015-09-18 19:59:43 +0000589 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000590 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000591
Michael Krusee2bccbb2015-09-18 19:59:43 +0000592 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000593 // We overapproximate non-affine accesses with a possible access to the
594 // whole array. For read accesses it does not make a difference, if an
595 // access must or may happen. However, for write accesses it is important to
596 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000597 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000598 AccessRelation =
599 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000600
Michael Krusee2bccbb2015-09-18 19:59:43 +0000601 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000602 return;
603 }
604
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000605 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000606 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000607
Michael Krusee2bccbb2015-09-18 19:59:43 +0000608 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
609 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000610
Sebastian Pop422e33f2014-06-03 18:16:31 +0000611 if (Size == 1) {
612 // For the non delinearized arrays, divide the access function of the last
613 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000614 //
615 // A stride one array access in C expressed as A[i] is expressed in
616 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
617 // two subsequent values of 'i' index two values that are stored next to
618 // each other in memory. By this division we make this characteristic
619 // obvious again.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000620 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000621 Affine = isl_pw_aff_scale_down_val(Affine, v);
622 }
623
624 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
625
Tobias Grosser79baa212014-04-10 08:38:02 +0000626 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000627 }
628
Michael Krusee2bccbb2015-09-18 19:59:43 +0000629 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
630 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000631
Tobias Grosser79baa212014-04-10 08:38:02 +0000632 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000633 AccessRelation = isl_map_set_tuple_id(
634 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000635 AccessRelation =
636 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
637
Michael Krusee2bccbb2015-09-18 19:59:43 +0000638 assumeNoOutOfBound();
Tobias Grosseraa660a92015-03-30 00:07:50 +0000639 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000640 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000641}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000642
Michael Krusecac948e2015-10-02 13:53:07 +0000643MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
644 __isl_take isl_id *Id, AccessType Type,
645 Value *BaseAddress, unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000646 ArrayRef<const SCEV *> Subscripts,
647 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Michael Kruse8d0b7342015-09-25 21:21:00 +0000648 AccessOrigin Origin, StringRef BaseName)
Michael Krusecac948e2015-10-02 13:53:07 +0000649 : Id(Id), Origin(Origin), AccType(Type), RedType(RT_NONE), Statement(Stmt),
650 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
651 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
652 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000653 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
654 NewAccessRelation(nullptr) {}
655
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000656void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000657 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000658 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000659}
660
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000661const std::string MemoryAccess::getReductionOperatorStr() const {
662 return MemoryAccess::getReductionOperatorStr(getReductionType());
663}
664
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000665__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
666
Johannes Doerfertf6183392014-07-01 20:52:51 +0000667raw_ostream &polly::operator<<(raw_ostream &OS,
668 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000669 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000670 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000671 else
672 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000673 return OS;
674}
675
Tobias Grosser75805372011-04-29 06:27:02 +0000676void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000677 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000678 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000679 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000680 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000681 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000682 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000683 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000684 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000685 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000686 break;
687 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000688 OS << "[Reduction Type: " << getReductionType() << "] ";
Michael Kruse8d0b7342015-09-25 21:21:00 +0000689 OS << "[Scalar: " << isImplicit() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000690 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000691 if (hasNewAccessRelation())
692 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000693}
694
Tobias Grosser74394f02013-01-14 22:40:23 +0000695void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000696
697// Create a map in the size of the provided set domain, that maps from the
698// one element of the provided set domain to another element of the provided
699// set domain.
700// The mapping is limited to all points that are equal in all but the last
701// dimension and for which the last dimension of the input is strict smaller
702// than the last dimension of the output.
703//
704// getEqualAndLarger(set[i0, i1, ..., iX]):
705//
706// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
707// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
708//
Tobias Grosserf5338802011-10-06 00:03:35 +0000709static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000710 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000711 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000712 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000713
714 // Set all but the last dimension to be equal for the input and output
715 //
716 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
717 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000718 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000719 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000720
721 // Set the last dimension of the input to be strict smaller than the
722 // last dimension of the output.
723 //
724 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000725 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
726 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000727 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000728}
729
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000730__isl_give isl_set *
731MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000732 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000733 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000734 isl_space *Space = isl_space_range(isl_map_get_space(S));
735 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000736
Sebastian Popa00a0292012-12-18 07:46:06 +0000737 S = isl_map_reverse(S);
738 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000739
Sebastian Popa00a0292012-12-18 07:46:06 +0000740 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
741 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
742 NextScatt = isl_map_apply_domain(NextScatt, S);
743 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000744
Sebastian Popa00a0292012-12-18 07:46:06 +0000745 isl_set *Deltas = isl_map_deltas(NextScatt);
746 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000747}
748
Sebastian Popa00a0292012-12-18 07:46:06 +0000749bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000750 int StrideWidth) const {
751 isl_set *Stride, *StrideX;
752 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000753
Sebastian Popa00a0292012-12-18 07:46:06 +0000754 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000755 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000756 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
757 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
758 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
759 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000760 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000761
Tobias Grosser28dd4862012-01-24 16:42:16 +0000762 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000763 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000764
Tobias Grosser28dd4862012-01-24 16:42:16 +0000765 return IsStrideX;
766}
767
Sebastian Popa00a0292012-12-18 07:46:06 +0000768bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
769 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000770}
771
Sebastian Popa00a0292012-12-18 07:46:06 +0000772bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
773 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000774}
775
Tobias Grosser166c4222015-09-05 07:46:40 +0000776void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
777 isl_map_free(NewAccessRelation);
778 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000779}
Tobias Grosser75805372011-04-29 06:27:02 +0000780
781//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000782
Tobias Grosser808cd692015-07-14 09:33:13 +0000783isl_map *ScopStmt::getSchedule() const {
784 isl_set *Domain = getDomain();
785 if (isl_set_is_empty(Domain)) {
786 isl_set_free(Domain);
787 return isl_map_from_aff(
788 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
789 }
790 auto *Schedule = getParent()->getSchedule();
791 Schedule = isl_union_map_intersect_domain(
792 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
793 if (isl_union_map_is_empty(Schedule)) {
794 isl_set_free(Domain);
795 isl_union_map_free(Schedule);
796 return isl_map_from_aff(
797 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
798 }
799 auto *M = isl_map_from_union_map(Schedule);
800 M = isl_map_coalesce(M);
801 M = isl_map_gist_domain(M, Domain);
802 M = isl_map_coalesce(M);
803 return M;
804}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000805
Johannes Doerfert574182d2015-08-12 10:19:50 +0000806__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000807 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
808 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000809}
810
Tobias Grosser37eb4222014-02-20 21:43:54 +0000811void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
812 assert(isl_set_is_subset(NewDomain, Domain) &&
813 "New domain is not a subset of old domain!");
814 isl_set_free(Domain);
815 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000816}
817
Michael Krusecac948e2015-10-02 13:53:07 +0000818void ScopStmt::buildAccessRelations() {
819 for (MemoryAccess *Access : MemAccs) {
820 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000821
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000822 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Michael Krusecac948e2015-10-02 13:53:07 +0000823 Access->getBaseAddr(), ElementType, Access->Sizes, Access->isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000824
Michael Krusecac948e2015-10-02 13:53:07 +0000825 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000826 }
827}
828
Michael Krusecac948e2015-10-02 13:53:07 +0000829void ScopStmt::addAccess(MemoryAccess *Access) {
830 Instruction *AccessInst = Access->getAccessInstruction();
831
832 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
833 if (!MAL)
834 MAL = new MemoryAccessList();
835 MAL->emplace_front(Access);
836 MemAccs.push_back(MAL->front());
837}
838
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000839void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000840 for (MemoryAccess *MA : *this)
841 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000842
843 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000844}
845
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000846/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
847static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
848 void *User) {
849 isl_set **BoundedParts = static_cast<isl_set **>(User);
850 if (isl_basic_set_is_bounded(BSet))
851 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
852 else
853 isl_basic_set_free(BSet);
854 return isl_stat_ok;
855}
856
857/// @brief Return the bounded parts of @p S.
858static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
859 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
860 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
861 isl_set_free(S);
862 return BoundedParts;
863}
864
865/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
866///
867/// @returns A separation of @p S into first an unbounded then a bounded subset,
868/// both with regards to the dimension @p Dim.
869static std::pair<__isl_give isl_set *, __isl_give isl_set *>
870partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
871
872 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000873 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000874
875 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000876 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000877
878 // Remove dimensions that are greater than Dim as they are not interesting.
879 assert(NumDimsS >= Dim + 1);
880 OnlyDimS =
881 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
882
883 // Create artificial parametric upper bounds for dimensions smaller than Dim
884 // as we are not interested in them.
885 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
886 for (unsigned u = 0; u < Dim; u++) {
887 isl_constraint *C = isl_inequality_alloc(
888 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
889 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
890 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
891 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
892 }
893
894 // Collect all bounded parts of OnlyDimS.
895 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
896
897 // Create the dimensions greater than Dim again.
898 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
899 NumDimsS - Dim - 1);
900
901 // Remove the artificial upper bound parameters again.
902 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
903
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000904 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000905 return std::make_pair(UnboundedParts, BoundedParts);
906}
907
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000908/// @brief Set the dimension Ids from @p From in @p To.
909static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
910 __isl_take isl_set *To) {
911 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
912 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
913 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
914 }
915 return To;
916}
917
918/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000919static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000920 __isl_take isl_pw_aff *L,
921 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +0000922 switch (Pred) {
923 case ICmpInst::ICMP_EQ:
924 return isl_pw_aff_eq_set(L, R);
925 case ICmpInst::ICMP_NE:
926 return isl_pw_aff_ne_set(L, R);
927 case ICmpInst::ICMP_SLT:
928 return isl_pw_aff_lt_set(L, R);
929 case ICmpInst::ICMP_SLE:
930 return isl_pw_aff_le_set(L, R);
931 case ICmpInst::ICMP_SGT:
932 return isl_pw_aff_gt_set(L, R);
933 case ICmpInst::ICMP_SGE:
934 return isl_pw_aff_ge_set(L, R);
935 case ICmpInst::ICMP_ULT:
936 return isl_pw_aff_lt_set(L, R);
937 case ICmpInst::ICMP_UGT:
938 return isl_pw_aff_gt_set(L, R);
939 case ICmpInst::ICMP_ULE:
940 return isl_pw_aff_le_set(L, R);
941 case ICmpInst::ICMP_UGE:
942 return isl_pw_aff_ge_set(L, R);
943 default:
944 llvm_unreachable("Non integer predicate not supported");
945 }
946}
947
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000948/// @brief Create the conditions under which @p L @p Pred @p R is true.
949///
950/// Helper function that will make sure the dimensions of the result have the
951/// same isl_id's as the @p Domain.
952static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
953 __isl_take isl_pw_aff *L,
954 __isl_take isl_pw_aff *R,
955 __isl_keep isl_set *Domain) {
956 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
957 return setDimensionIds(Domain, ConsequenceCondSet);
958}
959
960/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000961///
962/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000963/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
964/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000965static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000966buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +0000967 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
968
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000969 Value *Condition = getConditionFromTerminator(SI);
970 assert(Condition && "No condition for switch");
971
972 ScalarEvolution &SE = *S.getSE();
973 BasicBlock *BB = SI->getParent();
974 isl_pw_aff *LHS, *RHS;
975 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
976
977 unsigned NumSuccessors = SI->getNumSuccessors();
978 ConditionSets.resize(NumSuccessors);
979 for (auto &Case : SI->cases()) {
980 unsigned Idx = Case.getSuccessorIndex();
981 ConstantInt *CaseValue = Case.getCaseValue();
982
983 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
984 isl_set *CaseConditionSet =
985 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
986 ConditionSets[Idx] = isl_set_coalesce(
987 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
988 }
989
990 assert(ConditionSets[0] == nullptr && "Default condition set was set");
991 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
992 for (unsigned u = 2; u < NumSuccessors; u++)
993 ConditionSetUnion =
994 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
995 ConditionSets[0] = setDimensionIds(
996 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
997
998 S.markAsOptimized();
999 isl_pw_aff_free(LHS);
1000}
1001
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001002/// @brief Build the conditions sets for the branch condition @p Condition in
1003/// the @p Domain.
1004///
1005/// This will fill @p ConditionSets with the conditions under which control
1006/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1007/// have as many elements as @p TI has successors.
1008static void
1009buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1010 __isl_keep isl_set *Domain,
1011 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1012
1013 isl_set *ConsequenceCondSet = nullptr;
1014 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1015 if (CCond->isZero())
1016 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1017 else
1018 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1019 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1020 auto Opcode = BinOp->getOpcode();
1021 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1022
1023 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1024 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1025
1026 isl_set_free(ConditionSets.pop_back_val());
1027 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1028 isl_set_free(ConditionSets.pop_back_val());
1029 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1030
1031 if (Opcode == Instruction::And)
1032 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1033 else
1034 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1035 } else {
1036 auto *ICond = dyn_cast<ICmpInst>(Condition);
1037 assert(ICond &&
1038 "Condition of exiting branch was neither constant nor ICmp!");
1039
1040 ScalarEvolution &SE = *S.getSE();
1041 BasicBlock *BB = TI->getParent();
1042 isl_pw_aff *LHS, *RHS;
1043 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1044 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1045 ConsequenceCondSet =
1046 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1047 }
1048
1049 assert(ConsequenceCondSet);
1050 isl_set *AlternativeCondSet =
1051 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1052
1053 ConditionSets.push_back(isl_set_coalesce(
1054 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1055 ConditionSets.push_back(isl_set_coalesce(
1056 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1057}
1058
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001059/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1060///
1061/// This will fill @p ConditionSets with the conditions under which control
1062/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1063/// have as many elements as @p TI has successors.
1064static void
1065buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1066 __isl_keep isl_set *Domain,
1067 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1068
1069 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1070 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1071
1072 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1073
1074 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001075 ConditionSets.push_back(isl_set_copy(Domain));
1076 return;
1077 }
1078
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001079 Value *Condition = getConditionFromTerminator(TI);
1080 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001081
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001082 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001083}
1084
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001085void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001086 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001087
Tobias Grosser084d8f72012-05-29 09:29:44 +00001088 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1089
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001090 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001091 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001092}
1093
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001094void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001095 isl_ctx *Ctx = Parent.getIslCtx();
1096 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1097 Type *Ty = GEP->getPointerOperandType();
1098 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001099 ScopDetection &SD = Parent.getSD();
1100
1101 // The set of loads that are required to be invariant.
1102 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001103
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001104 std::vector<const SCEV *> Subscripts;
1105 std::vector<int> Sizes;
1106
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001107 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001108
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001109 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001110 Ty = PtrTy->getElementType();
1111 }
1112
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001113 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001114
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001115 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001116
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001117 for (size_t i = 0; i < Sizes.size(); i++) {
1118 auto Expr = Subscripts[i + IndexOffset];
1119 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001120
Johannes Doerfert09e36972015-10-07 20:17:36 +00001121 InvariantLoadsSetTy AccessILS;
1122 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1123 continue;
1124
1125 bool NonAffine = false;
1126 for (LoadInst *LInst : AccessILS)
1127 if (!ScopRIL.count(LInst))
1128 NonAffine = true;
1129
1130 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001131 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001132
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001133 isl_pw_aff *AccessOffset = getPwAff(Expr);
1134 AccessOffset =
1135 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001136
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001137 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1138 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001139
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001140 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1141 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1142 OutOfBound = isl_set_params(OutOfBound);
1143 isl_set *InBound = isl_set_complement(OutOfBound);
1144 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001145
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001146 // A => B == !A or B
1147 isl_set *InBoundIfExecuted =
1148 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001149
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001150 Parent.addAssumption(InBoundIfExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001151 }
1152
1153 isl_local_space_free(LSpace);
1154}
1155
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001156void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1157 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001158 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1159 deriveAssumptionsFromGEP(GEP);
1160}
1161
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001162void ScopStmt::collectSurroundingLoops() {
1163 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1164 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1165 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1166 isl_id_free(DimId);
1167 }
1168}
1169
Michael Kruse9d080092015-09-11 21:41:48 +00001170ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001171 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001172
Tobias Grosser16c44032015-07-09 07:31:45 +00001173 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001174}
1175
Michael Kruse9d080092015-09-11 21:41:48 +00001176ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001177 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001178
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001179 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001180}
1181
1182void ScopStmt::init() {
1183 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001184
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001185 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001186 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001187 buildAccessRelations();
1188
1189 if (BB) {
1190 deriveAssumptions(BB);
1191 } else {
1192 for (BasicBlock *Block : R->blocks()) {
1193 deriveAssumptions(Block);
1194 }
1195 }
1196
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001197 if (DetectReductions)
1198 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001199}
1200
Johannes Doerferte58a0122014-06-27 20:31:28 +00001201/// @brief Collect loads which might form a reduction chain with @p StoreMA
1202///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001203/// Check if the stored value for @p StoreMA is a binary operator with one or
1204/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001205/// used only once (by @p StoreMA) and its load operands are also used only
1206/// once, we have found a possible reduction chain. It starts at an operand
1207/// load and includes the binary operator and @p StoreMA.
1208///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001209/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001210/// escape this block or into any other store except @p StoreMA.
1211void ScopStmt::collectCandiateReductionLoads(
1212 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1213 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1214 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001215 return;
1216
1217 // Skip if there is not one binary operator between the load and the store
1218 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001219 if (!BinOp)
1220 return;
1221
1222 // Skip if the binary operators has multiple uses
1223 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001224 return;
1225
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001226 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001227 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1228 return;
1229
Johannes Doerfert9890a052014-07-01 00:32:29 +00001230 // Skip if the binary operator is outside the current SCoP
1231 if (BinOp->getParent() != Store->getParent())
1232 return;
1233
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001234 // Skip if it is a multiplicative reduction and we disabled them
1235 if (DisableMultiplicativeReductions &&
1236 (BinOp->getOpcode() == Instruction::Mul ||
1237 BinOp->getOpcode() == Instruction::FMul))
1238 return;
1239
Johannes Doerferte58a0122014-06-27 20:31:28 +00001240 // Check the binary operator operands for a candidate load
1241 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1242 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1243 if (!PossibleLoad0 && !PossibleLoad1)
1244 return;
1245
1246 // A load is only a candidate if it cannot escape (thus has only this use)
1247 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001248 if (PossibleLoad0->getParent() == Store->getParent())
1249 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001250 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001251 if (PossibleLoad1->getParent() == Store->getParent())
1252 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001253}
1254
1255/// @brief Check for reductions in this ScopStmt
1256///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001257/// Iterate over all store memory accesses and check for valid binary reduction
1258/// like chains. For all candidates we check if they have the same base address
1259/// and there are no other accesses which overlap with them. The base address
1260/// check rules out impossible reductions candidates early. The overlap check,
1261/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001262/// guarantees that none of the intermediate results will escape during
1263/// execution of the loop nest. We basically check here that no other memory
1264/// access can access the same memory as the potential reduction.
1265void ScopStmt::checkForReductions() {
1266 SmallVector<MemoryAccess *, 2> Loads;
1267 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1268
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001269 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001270 // stores and collecting possible reduction loads.
1271 for (MemoryAccess *StoreMA : MemAccs) {
1272 if (StoreMA->isRead())
1273 continue;
1274
1275 Loads.clear();
1276 collectCandiateReductionLoads(StoreMA, Loads);
1277 for (MemoryAccess *LoadMA : Loads)
1278 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1279 }
1280
1281 // Then check each possible candidate pair.
1282 for (const auto &CandidatePair : Candidates) {
1283 bool Valid = true;
1284 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1285 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1286
1287 // Skip those with obviously unequal base addresses.
1288 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1289 isl_map_free(LoadAccs);
1290 isl_map_free(StoreAccs);
1291 continue;
1292 }
1293
1294 // And check if the remaining for overlap with other memory accesses.
1295 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1296 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1297 isl_set *AllAccs = isl_map_range(AllAccsRel);
1298
1299 for (MemoryAccess *MA : MemAccs) {
1300 if (MA == CandidatePair.first || MA == CandidatePair.second)
1301 continue;
1302
1303 isl_map *AccRel =
1304 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1305 isl_set *Accs = isl_map_range(AccRel);
1306
1307 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1308 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1309 Valid = Valid && isl_set_is_empty(OverlapAccs);
1310 isl_set_free(OverlapAccs);
1311 }
1312 }
1313
1314 isl_set_free(AllAccs);
1315 if (!Valid)
1316 continue;
1317
Johannes Doerfertf6183392014-07-01 20:52:51 +00001318 const LoadInst *Load =
1319 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1320 MemoryAccess::ReductionType RT =
1321 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1322
Johannes Doerferte58a0122014-06-27 20:31:28 +00001323 // If no overlapping access was found we mark the load and store as
1324 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001325 CandidatePair.first->markAsReductionLike(RT);
1326 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001327 }
Tobias Grosser75805372011-04-29 06:27:02 +00001328}
1329
Tobias Grosser74394f02013-01-14 22:40:23 +00001330std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001331
Tobias Grosser54839312015-04-21 11:37:25 +00001332std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001333 auto *S = getSchedule();
1334 auto Str = stringFromIslObj(S);
1335 isl_map_free(S);
1336 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001337}
1338
Tobias Grosser74394f02013-01-14 22:40:23 +00001339unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001340
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001341unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001342
Tobias Grosser75805372011-04-29 06:27:02 +00001343const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1344
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001345const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001346 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001347}
1348
Tobias Grosser74394f02013-01-14 22:40:23 +00001349isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001350
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001351__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001352
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001353__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001354 return isl_set_get_space(Domain);
1355}
1356
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001357__isl_give isl_id *ScopStmt::getDomainId() const {
1358 return isl_set_get_tuple_id(Domain);
1359}
Tobias Grossercd95b772012-08-30 11:49:38 +00001360
Tobias Grosser75805372011-04-29 06:27:02 +00001361ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001362 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001363 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001364}
1365
1366void ScopStmt::print(raw_ostream &OS) const {
1367 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001368 OS.indent(12) << "Domain :=\n";
1369
1370 if (Domain) {
1371 OS.indent(16) << getDomainStr() << ";\n";
1372 } else
1373 OS.indent(16) << "n/a\n";
1374
Tobias Grosser54839312015-04-21 11:37:25 +00001375 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001376
1377 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001378 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001379 } else
1380 OS.indent(16) << "n/a\n";
1381
Tobias Grosser083d3d32014-06-28 08:59:45 +00001382 for (MemoryAccess *Access : MemAccs)
1383 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001384}
1385
1386void ScopStmt::dump() const { print(dbgs()); }
1387
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001388void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001389
1390 // Remove all memory accesses in @p InvMAs from this statement together
1391 // with all scalar accesses that were caused by them. The tricky iteration
1392 // order uses is needed because the MemAccs is a vector and the order in
1393 // which the accesses of each memory access list (MAL) are stored in this
1394 // vector is reversed.
1395 for (MemoryAccess *MA : InvMAs) {
1396 auto &MAL = *lookupAccessesFor(MA->getAccessInstruction());
1397 MAL.reverse();
1398
1399 auto MALIt = MAL.begin();
1400 auto MALEnd = MAL.end();
1401 auto MemAccsIt = MemAccs.begin();
1402 while (MALIt != MALEnd) {
1403 while (*MemAccsIt != *MALIt)
1404 MemAccsIt++;
1405
1406 MALIt++;
1407 MemAccs.erase(MemAccsIt);
1408 }
1409
1410 InstructionToAccess.erase(MA->getAccessInstruction());
1411 delete &MAL;
1412 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001413}
1414
Tobias Grosser75805372011-04-29 06:27:02 +00001415//===----------------------------------------------------------------------===//
1416/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001417
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001418void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001419 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1420 isl_set_free(Context);
1421 Context = NewContext;
1422}
1423
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001424/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1425struct SCEVSensitiveParameterRewriter
1426 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1427 ValueToValueMap &VMap;
1428 ScalarEvolution &SE;
1429
1430public:
1431 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1432 : VMap(VMap), SE(SE) {}
1433
1434 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1435 ValueToValueMap &VMap) {
1436 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1437 return SSPR.visit(E);
1438 }
1439
1440 const SCEV *visit(const SCEV *E) {
1441 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1442 }
1443
1444 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1445
1446 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1447 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1448 }
1449
1450 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1451 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1452 }
1453
1454 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1455 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1456 }
1457
1458 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1459 SmallVector<const SCEV *, 4> Operands;
1460 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1461 Operands.push_back(visit(E->getOperand(i)));
1462 return SE.getAddExpr(Operands);
1463 }
1464
1465 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1466 SmallVector<const SCEV *, 4> Operands;
1467 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1468 Operands.push_back(visit(E->getOperand(i)));
1469 return SE.getMulExpr(Operands);
1470 }
1471
1472 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1473 SmallVector<const SCEV *, 4> Operands;
1474 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1475 Operands.push_back(visit(E->getOperand(i)));
1476 return SE.getSMaxExpr(Operands);
1477 }
1478
1479 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1480 SmallVector<const SCEV *, 4> Operands;
1481 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1482 Operands.push_back(visit(E->getOperand(i)));
1483 return SE.getUMaxExpr(Operands);
1484 }
1485
1486 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1487 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1488 }
1489
1490 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1491 auto *Start = visit(E->getStart());
1492 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1493 visit(E->getStepRecurrence(SE)),
1494 E->getLoop(), SCEV::FlagAnyWrap);
1495 return SE.getAddExpr(Start, AddRec);
1496 }
1497
1498 const SCEV *visitUnknown(const SCEVUnknown *E) {
1499 if (auto *NewValue = VMap.lookup(E->getValue()))
1500 return SE.getUnknown(NewValue);
1501 return E;
1502 }
1503};
1504
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001505const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001506 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001507}
1508
Tobias Grosserabfbe632013-02-05 12:09:06 +00001509void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001510 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001511 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001512
1513 // Normalize the SCEV to get the representing element for an invariant load.
1514 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1515
Tobias Grosser60b54f12011-11-08 15:41:28 +00001516 if (ParameterIds.find(Parameter) != ParameterIds.end())
1517 continue;
1518
1519 int dimension = Parameters.size();
1520
1521 Parameters.push_back(Parameter);
1522 ParameterIds[Parameter] = dimension;
1523 }
1524}
1525
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001526__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001527 // Normalize the SCEV to get the representing element for an invariant load.
1528 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1529
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001530 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001531
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001532 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001533 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001534
Tobias Grosser8f99c162011-11-15 11:38:55 +00001535 std::string ParameterName;
1536
1537 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1538 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001539 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001540 }
1541
1542 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001543 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001544
Tobias Grosser20532b82014-04-11 17:56:49 +00001545 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1546 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001547}
Tobias Grosser75805372011-04-29 06:27:02 +00001548
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001549isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1550 isl_set *DomainContext = isl_union_set_params(getDomains());
1551 return isl_set_intersect_params(C, DomainContext);
1552}
1553
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001554void Scop::buildBoundaryContext() {
1555 BoundaryContext = Affinator.getWrappingContext();
1556 BoundaryContext = isl_set_complement(BoundaryContext);
1557 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
1558}
1559
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001560void Scop::addUserContext() {
1561 if (UserContextStr.empty())
1562 return;
1563
1564 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1565 isl_space *Space = getParamSpace();
1566 if (isl_space_dim(Space, isl_dim_param) !=
1567 isl_set_dim(UserContext, isl_dim_param)) {
1568 auto SpaceStr = isl_space_to_str(Space);
1569 errs() << "Error: the context provided in -polly-context has not the same "
1570 << "number of dimensions than the computed context. Due to this "
1571 << "mismatch, the -polly-context option is ignored. Please provide "
1572 << "the context in the parameter space: " << SpaceStr << ".\n";
1573 free(SpaceStr);
1574 isl_set_free(UserContext);
1575 isl_space_free(Space);
1576 return;
1577 }
1578
1579 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1580 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1581 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1582
1583 if (strcmp(NameContext, NameUserContext) != 0) {
1584 auto SpaceStr = isl_space_to_str(Space);
1585 errs() << "Error: the name of dimension " << i
1586 << " provided in -polly-context "
1587 << "is '" << NameUserContext << "', but the name in the computed "
1588 << "context is '" << NameContext
1589 << "'. Due to this name mismatch, "
1590 << "the -polly-context option is ignored. Please provide "
1591 << "the context in the parameter space: " << SpaceStr << ".\n";
1592 free(SpaceStr);
1593 isl_set_free(UserContext);
1594 isl_space_free(Space);
1595 return;
1596 }
1597
1598 UserContext =
1599 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1600 isl_space_get_dim_id(Space, isl_dim_param, i));
1601 }
1602
1603 Context = isl_set_intersect(Context, UserContext);
1604 isl_space_free(Space);
1605}
1606
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001607void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001608 DenseMap<const SCEV *, LoadInst *> EquivClasses;
1609
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001610 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001611 for (LoadInst *LInst : RIL) {
1612 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1613
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001614 LoadInst *&ClassRep = EquivClasses[PointerSCEV];
1615 if (!ClassRep)
1616 ClassRep = LInst;
1617 else
1618 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001619 }
1620}
1621
Tobias Grosser6be480c2011-11-08 15:41:13 +00001622void Scop::buildContext() {
1623 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001624 Context = isl_set_universe(isl_space_copy(Space));
1625 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001626}
1627
Tobias Grosser18daaca2012-05-22 10:47:27 +00001628void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001629 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001630 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001631
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001632 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001633
Johannes Doerferte7044942015-02-24 11:58:30 +00001634 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001635 }
1636}
1637
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001638void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001639 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001640 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001641
Tobias Grosser083d3d32014-06-28 08:59:45 +00001642 for (const auto &ParamID : ParameterIds) {
1643 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001644 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001645 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001646 }
1647
1648 // Align the parameters of all data structures to the model.
1649 Context = isl_set_align_params(Context, Space);
1650
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001651 for (ScopStmt &Stmt : *this)
1652 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001653}
1654
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001655static __isl_give isl_set *
1656simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1657 const Scop &S) {
1658 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1659 AssumptionContext = isl_set_gist_params(AssumptionContext, DomainParameters);
1660 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1661 return AssumptionContext;
1662}
1663
1664void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001665 // The parameter constraints of the iteration domains give us a set of
1666 // constraints that need to hold for all cases where at least a single
1667 // statement iteration is executed in the whole scop. We now simplify the
1668 // assumed context under the assumption that such constraints hold and at
1669 // least a single statement iteration is executed. For cases where no
1670 // statement instances are executed, the assumptions we have taken about
1671 // the executed code do not matter and can be changed.
1672 //
1673 // WARNING: This only holds if the assumptions we have taken do not reduce
1674 // the set of statement instances that are executed. Otherwise we
1675 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001676 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001677 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001678 // performed. In such a case, modifying the run-time conditions and
1679 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001680 // to not be executed.
1681 //
1682 // Example:
1683 //
1684 // When delinearizing the following code:
1685 //
1686 // for (long i = 0; i < 100; i++)
1687 // for (long j = 0; j < m; j++)
1688 // A[i+p][j] = 1.0;
1689 //
1690 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001691 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001692 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001693 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1694 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001695}
1696
Johannes Doerfertb164c792014-09-18 11:17:17 +00001697/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001698static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001699 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1700 isl_pw_multi_aff *MinPMA, *MaxPMA;
1701 isl_pw_aff *LastDimAff;
1702 isl_aff *OneAff;
1703 unsigned Pos;
1704
Johannes Doerfert9143d672014-09-27 11:02:39 +00001705 // Restrict the number of parameters involved in the access as the lexmin/
1706 // lexmax computation will take too long if this number is high.
1707 //
1708 // Experiments with a simple test case using an i7 4800MQ:
1709 //
1710 // #Parameters involved | Time (in sec)
1711 // 6 | 0.01
1712 // 7 | 0.04
1713 // 8 | 0.12
1714 // 9 | 0.40
1715 // 10 | 1.54
1716 // 11 | 6.78
1717 // 12 | 30.38
1718 //
1719 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1720 unsigned InvolvedParams = 0;
1721 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1722 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1723 InvolvedParams++;
1724
1725 if (InvolvedParams > RunTimeChecksMaxParameters) {
1726 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001727 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001728 }
1729 }
1730
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001731 Set = isl_set_remove_divs(Set);
1732
Johannes Doerfertb164c792014-09-18 11:17:17 +00001733 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1734 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1735
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001736 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1737 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1738
Johannes Doerfertb164c792014-09-18 11:17:17 +00001739 // Adjust the last dimension of the maximal access by one as we want to
1740 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1741 // we test during code generation might now point after the end of the
1742 // allocated array but we will never dereference it anyway.
1743 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1744 "Assumed at least one output dimension");
1745 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1746 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1747 OneAff = isl_aff_zero_on_domain(
1748 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1749 OneAff = isl_aff_add_constant_si(OneAff, 1);
1750 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1751 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1752
1753 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1754
1755 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001756 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001757}
1758
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001759static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1760 isl_set *Domain = MA->getStatement()->getDomain();
1761 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1762 return isl_set_reset_tuple_id(Domain);
1763}
1764
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001765/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1766static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001767 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001768 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001769
1770 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1771 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001772 Locations = isl_union_set_coalesce(Locations);
1773 Locations = isl_union_set_detect_equalities(Locations);
1774 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001775 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001776 isl_union_set_free(Locations);
1777 return Valid;
1778}
1779
Johannes Doerfert96425c22015-08-30 21:13:53 +00001780/// @brief Helper to treat non-affine regions and basic blocks the same.
1781///
1782///{
1783
1784/// @brief Return the block that is the representing block for @p RN.
1785static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1786 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1787 : RN->getNodeAs<BasicBlock>();
1788}
1789
1790/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001791static inline BasicBlock *
1792getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001793 if (RN->isSubRegion()) {
1794 assert(idx == 0);
1795 return RN->getNodeAs<Region>()->getExit();
1796 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001797 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001798}
1799
1800/// @brief Return the smallest loop surrounding @p RN.
1801static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1802 if (!RN->isSubRegion())
1803 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1804
1805 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1806 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1807 while (L && NonAffineSubRegion->contains(L))
1808 L = L->getParentLoop();
1809 return L;
1810}
1811
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001812static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1813 if (!RN->isSubRegion())
1814 return 1;
1815
1816 unsigned NumBlocks = 0;
1817 Region *R = RN->getNodeAs<Region>();
1818 for (auto BB : R->blocks()) {
1819 (void)BB;
1820 NumBlocks++;
1821 }
1822 return NumBlocks;
1823}
1824
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001825static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1826 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001827 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001828 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001829 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001830 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001831 return true;
1832 return false;
1833}
1834
Johannes Doerfert96425c22015-08-30 21:13:53 +00001835///}
1836
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001837static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1838 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001839 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001840 isl_id *DimId =
1841 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1842 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1843}
1844
Johannes Doerfert96425c22015-08-30 21:13:53 +00001845isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1846 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1847 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001848 return getDomainConditions(BB);
1849}
1850
1851isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1852 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001853 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001854}
1855
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001856void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001857
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001858 auto *EntryBB = R->getEntry();
1859 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1860 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001861
1862 Loop *L = LI.getLoopFor(EntryBB);
1863 while (LD-- >= 0) {
1864 S = addDomainDimId(S, LD + 1, L);
1865 L = L->getParentLoop();
1866 }
1867
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001868 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001869
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001870 if (SD.isNonAffineSubRegion(R, R))
1871 return;
1872
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001873 buildDomainsWithBranchConstraints(R);
1874 propagateDomainConstraints(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001875}
1876
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001877void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001878 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001879
1880 // To create the domain for each block in R we iterate over all blocks and
1881 // subregions in R and propagate the conditions under which the current region
1882 // element is executed. To this end we iterate in reverse post order over R as
1883 // it ensures that we first visit all predecessors of a region node (either a
1884 // basic block or a subregion) before we visit the region node itself.
1885 // Initially, only the domain for the SCoP region entry block is set and from
1886 // there we propagate the current domain to all successors, however we add the
1887 // condition that the successor is actually executed next.
1888 // As we are only interested in non-loop carried constraints here we can
1889 // simply skip loop back edges.
1890
1891 ReversePostOrderTraversal<Region *> RTraversal(R);
1892 for (auto *RN : RTraversal) {
1893
1894 // Recurse for affine subregions but go on for basic blocks and non-affine
1895 // subregions.
1896 if (RN->isSubRegion()) {
1897 Region *SubRegion = RN->getNodeAs<Region>();
1898 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001899 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001900 continue;
1901 }
1902 }
1903
Johannes Doerfertf5673802015-10-01 23:48:18 +00001904 // Error blocks are assumed not to be executed. Therefor they are not
1905 // checked properly in the ScopDetection. Any attempt to generate control
1906 // conditions from them might result in a crash. However, this is only true
1907 // for the first step of the domain generation (this function) where we
1908 // push the control conditions of a block to the successors. In the second
1909 // step (propagateDomainConstraints) we only receive domain constraints from
1910 // the predecessors and can therefor look at the domain of a error block.
1911 // That allows us to generate the assumptions needed for them not to be
1912 // executed at runtime.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001913 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001914 continue;
1915
Johannes Doerfert96425c22015-08-30 21:13:53 +00001916 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001917 TerminatorInst *TI = BB->getTerminator();
1918
Johannes Doerfertf5673802015-10-01 23:48:18 +00001919 isl_set *Domain = DomainMap.lookup(BB);
1920 if (!Domain) {
1921 DEBUG(dbgs() << "\tSkip: " << BB->getName()
1922 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001923 continue;
1924 }
1925
Johannes Doerfert96425c22015-08-30 21:13:53 +00001926 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001927
1928 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1929 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1930
1931 // Build the condition sets for the successor nodes of the current region
1932 // node. If it is a non-affine subregion we will always execute the single
1933 // exit node, hence the single entry node domain is the condition set. For
1934 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001935 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001936 if (RN->isSubRegion())
1937 ConditionSets.push_back(isl_set_copy(Domain));
1938 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001939 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001940
1941 // Now iterate over the successors and set their initial domain based on
1942 // their condition set. We skip back edges here and have to be careful when
1943 // we leave a loop not to keep constraints over a dimension that doesn't
1944 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001945 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00001946 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001947 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001948 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001949
1950 // Skip back edges.
1951 if (DT.dominates(SuccBB, BB)) {
1952 isl_set_free(CondSet);
1953 continue;
1954 }
1955
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001956 // Do not adjust the number of dimensions if we enter a boxed loop or are
1957 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001958 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001959 Region *SuccRegion = RI.getRegionFor(SuccBB);
Johannes Doerfert634909c2015-10-04 14:57:41 +00001960 if (SD.isNonAffineSubRegion(SuccRegion, &getRegion()))
1961 while (SuccBBLoop && SuccRegion->contains(SuccBBLoop))
1962 SuccBBLoop = SuccBBLoop->getParentLoop();
1963
1964 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001965
1966 // Check if the edge to SuccBB is a loop entry or exit edge. If so
1967 // adjust the dimensionality accordingly. Lastly, if we leave a loop
1968 // and enter a new one we need to drop the old constraints.
1969 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001970 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001971 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001972 CondSet = isl_set_project_out(CondSet, isl_dim_set,
1973 isl_set_n_dim(CondSet) - LoopDepthDiff,
1974 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001975 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001976 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001977 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001978 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001979 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001980 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001981 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
1982 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001983 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001984 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00001985 }
1986
1987 // Set the domain for the successor or merge it with an existing domain in
1988 // case there are multiple paths (without loop back edges) to the
1989 // successor block.
1990 isl_set *&SuccDomain = DomainMap[SuccBB];
1991 if (!SuccDomain)
1992 SuccDomain = CondSet;
1993 else
1994 SuccDomain = isl_set_union(SuccDomain, CondSet);
1995
1996 SuccDomain = isl_set_coalesce(SuccDomain);
Johannes Doerfert634909c2015-10-04 14:57:41 +00001997 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
1998 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001999 }
2000 }
2001}
2002
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002003/// @brief Return the domain for @p BB wrt @p DomainMap.
2004///
2005/// This helper function will lookup @p BB in @p DomainMap but also handle the
2006/// case where @p BB is contained in a non-affine subregion using the region
2007/// tree obtained by @p RI.
2008static __isl_give isl_set *
2009getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2010 RegionInfo &RI) {
2011 auto DIt = DomainMap.find(BB);
2012 if (DIt != DomainMap.end())
2013 return isl_set_copy(DIt->getSecond());
2014
2015 Region *R = RI.getRegionFor(BB);
2016 while (R->getEntry() == BB)
2017 R = R->getParent();
2018 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2019}
2020
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002021void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002022 // Iterate over the region R and propagate the domain constrains from the
2023 // predecessors to the current node. In contrast to the
2024 // buildDomainsWithBranchConstraints function, this one will pull the domain
2025 // information from the predecessors instead of pushing it to the successors.
2026 // Additionally, we assume the domains to be already present in the domain
2027 // map here. However, we iterate again in reverse post order so we know all
2028 // predecessors have been visited before a block or non-affine subregion is
2029 // visited.
2030
2031 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2032 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2033
2034 ReversePostOrderTraversal<Region *> RTraversal(R);
2035 for (auto *RN : RTraversal) {
2036
2037 // Recurse for affine subregions but go on for basic blocks and non-affine
2038 // subregions.
2039 if (RN->isSubRegion()) {
2040 Region *SubRegion = RN->getNodeAs<Region>();
2041 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002042 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002043 continue;
2044 }
2045 }
2046
Johannes Doerfertf5673802015-10-01 23:48:18 +00002047 // Get the domain for the current block and check if it was initialized or
2048 // not. The only way it was not is if this block is only reachable via error
2049 // blocks, thus will not be executed under the assumptions we make. Such
2050 // blocks have to be skipped as their predecessors might not have domains
2051 // either. It would not benefit us to compute the domain anyway, only the
2052 // domains of the error blocks that are reachable from non-error blocks
2053 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002054 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002055 isl_set *&Domain = DomainMap[BB];
2056 if (!Domain) {
2057 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2058 << ", it is only reachable from error blocks.\n");
2059 DomainMap.erase(BB);
2060 continue;
2061 }
2062 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2063
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002064 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2065 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2066
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002067 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2068 for (auto *PredBB : predecessors(BB)) {
2069
2070 // Skip backedges
2071 if (DT.dominates(BB, PredBB))
2072 continue;
2073
2074 isl_set *PredBBDom = nullptr;
2075
2076 // Handle the SCoP entry block with its outside predecessors.
2077 if (!getRegion().contains(PredBB))
2078 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2079
2080 if (!PredBBDom) {
2081 // Determine the loop depth of the predecessor and adjust its domain to
2082 // the domain of the current block. This can mean we have to:
2083 // o) Drop a dimension if this block is the exit of a loop, not the
2084 // header of a new loop and the predecessor was part of the loop.
2085 // o) Add an unconstrainted new dimension if this block is the header
2086 // of a loop and the predecessor is not part of it.
2087 // o) Drop the information about the innermost loop dimension when the
2088 // predecessor and the current block are surrounded by different
2089 // loops in the same depth.
2090 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2091 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2092 while (BoxedLoops.count(PredBBLoop))
2093 PredBBLoop = PredBBLoop->getParentLoop();
2094
2095 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002096 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002097 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002098 PredBBDom = isl_set_project_out(
2099 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2100 LoopDepthDiff);
2101 else if (PredBBLoopDepth < BBLoopDepth) {
2102 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002103 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002104 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2105 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002106 PredBBDom = isl_set_drop_constraints_involving_dims(
2107 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002108 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002109 }
2110
2111 PredDom = isl_set_union(PredDom, PredBBDom);
2112 }
2113
2114 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002115 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002116
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002117 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002118 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002119
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002120 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002121 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002122 IsOptimized = true;
2123 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2124 addAssumption(isl_set_complement(DomPar));
2125 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002126 }
2127}
2128
2129/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2130/// is incremented by one and all other dimensions are equal, e.g.,
2131/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2132/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2133static __isl_give isl_map *
2134createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2135 auto *MapSpace = isl_space_map_from_set(SetSpace);
2136 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2137 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2138 if (u != Dim)
2139 NextIterationMap =
2140 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2141 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2142 C = isl_constraint_set_constant_si(C, 1);
2143 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2144 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2145 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2146 return NextIterationMap;
2147}
2148
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002149void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002150 int LoopDepth = getRelativeLoopDepth(L);
2151 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002152
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002153 BasicBlock *HeaderBB = L->getHeader();
2154 assert(DomainMap.count(HeaderBB));
2155 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002156
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002157 isl_map *NextIterationMap =
2158 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002159
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002160 isl_set *UnionBackedgeCondition =
2161 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002162
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002163 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2164 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002165
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002166 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002167
2168 // If the latch is only reachable via error statements we skip it.
2169 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2170 if (!LatchBBDom)
2171 continue;
2172
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002173 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002174
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002175 TerminatorInst *TI = LatchBB->getTerminator();
2176 BranchInst *BI = dyn_cast<BranchInst>(TI);
2177 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002178 BackedgeCondition = isl_set_copy(LatchBBDom);
2179 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002180 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002181 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002182 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002183
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002184 // Free the non back edge condition set as we do not need it.
2185 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002186
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002187 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002188 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002189
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002190 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2191 assert(LatchLoopDepth >= LoopDepth);
2192 BackedgeCondition =
2193 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2194 LatchLoopDepth - LoopDepth);
2195 UnionBackedgeCondition =
2196 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002197 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002198
2199 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2200 for (int i = 0; i < LoopDepth; i++)
2201 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2202
2203 isl_set *UnionBackedgeConditionComplement =
2204 isl_set_complement(UnionBackedgeCondition);
2205 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2206 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2207 UnionBackedgeConditionComplement =
2208 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2209 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2210 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2211
2212 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2213 HeaderBBDom = Parts.second;
2214
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002215 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2216 // the bounded assumptions to the context as they are already implied by the
2217 // <nsw> tag.
2218 if (Affinator.hasNSWAddRecForLoop(L)) {
2219 isl_set_free(Parts.first);
2220 return;
2221 }
2222
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002223 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2224 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfert707a4062015-09-20 16:38:19 +00002225 addAssumption(BoundedCtx);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002226}
2227
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002228void Scop::buildAliasChecks(AliasAnalysis &AA) {
2229 if (!PollyUseRuntimeAliasChecks)
2230 return;
2231
2232 if (buildAliasGroups(AA))
2233 return;
2234
2235 // If a problem occurs while building the alias groups we need to delete
2236 // this SCoP and pretend it wasn't valid in the first place. To this end
2237 // we make the assumed context infeasible.
2238 addAssumption(isl_set_empty(getParamSpace()));
2239
2240 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2241 << " could not be created as the number of parameters involved "
2242 "is too high. The SCoP will be "
2243 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2244 "the maximal number of parameters but be advised that the "
2245 "compile time might increase exponentially.\n\n");
2246}
2247
Johannes Doerfert9143d672014-09-27 11:02:39 +00002248bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002249 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002250 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002251 // for all memory accesses inside the SCoP.
2252 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002253 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002254 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002255 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002256 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002257 // if their access domains intersect, otherwise they are in different
2258 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002259 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002260 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002261 // and maximal accesses to each array of a group in read only and non
2262 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002263 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2264
2265 AliasSetTracker AST(AA);
2266
2267 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002268 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002269 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002270
2271 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002272 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002273 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2274 isl_set_free(StmtDomain);
2275 if (StmtDomainEmpty)
2276 continue;
2277
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002278 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00002279 if (MA->isImplicit())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002280 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002281 if (!MA->isRead())
2282 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002283 Instruction *Acc = MA->getAccessInstruction();
2284 PtrToAcc[getPointerOperand(*Acc)] = MA;
2285 AST.add(Acc);
2286 }
2287 }
2288
2289 SmallVector<AliasGroupTy, 4> AliasGroups;
2290 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002291 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002292 continue;
2293 AliasGroupTy AG;
2294 for (auto PR : AS)
2295 AG.push_back(PtrToAcc[PR.getValue()]);
2296 assert(AG.size() > 1 &&
2297 "Alias groups should contain at least two accesses");
2298 AliasGroups.push_back(std::move(AG));
2299 }
2300
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002301 // Split the alias groups based on their domain.
2302 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2303 AliasGroupTy NewAG;
2304 AliasGroupTy &AG = AliasGroups[u];
2305 AliasGroupTy::iterator AGI = AG.begin();
2306 isl_set *AGDomain = getAccessDomain(*AGI);
2307 while (AGI != AG.end()) {
2308 MemoryAccess *MA = *AGI;
2309 isl_set *MADomain = getAccessDomain(MA);
2310 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2311 NewAG.push_back(MA);
2312 AGI = AG.erase(AGI);
2313 isl_set_free(MADomain);
2314 } else {
2315 AGDomain = isl_set_union(AGDomain, MADomain);
2316 AGI++;
2317 }
2318 }
2319 if (NewAG.size() > 1)
2320 AliasGroups.push_back(std::move(NewAG));
2321 isl_set_free(AGDomain);
2322 }
2323
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002324 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002325 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2326 for (AliasGroupTy &AG : AliasGroups) {
2327 NonReadOnlyBaseValues.clear();
2328 ReadOnlyPairs.clear();
2329
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002330 if (AG.size() < 2) {
2331 AG.clear();
2332 continue;
2333 }
2334
Johannes Doerfert13771732014-10-01 12:40:46 +00002335 for (auto II = AG.begin(); II != AG.end();) {
2336 Value *BaseAddr = (*II)->getBaseAddr();
2337 if (HasWriteAccess.count(BaseAddr)) {
2338 NonReadOnlyBaseValues.insert(BaseAddr);
2339 II++;
2340 } else {
2341 ReadOnlyPairs[BaseAddr].insert(*II);
2342 II = AG.erase(II);
2343 }
2344 }
2345
2346 // If we don't have read only pointers check if there are at least two
2347 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002348 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002349 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002350 continue;
2351 }
2352
2353 // If we don't have non read only pointers clear the alias group.
2354 if (NonReadOnlyBaseValues.empty()) {
2355 AG.clear();
2356 continue;
2357 }
2358
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002359 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002360 MinMaxAliasGroups.emplace_back();
2361 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2362 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2363 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2364 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002365
2366 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002367
2368 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002369 for (MemoryAccess *MA : AG)
2370 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002371
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002372 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2373 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002374
2375 // Bail out if the number of values we need to compare is too large.
2376 // This is important as the number of comparisions grows quadratically with
2377 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002378 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2379 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002380 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002381
2382 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002383 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002384 Accesses = isl_union_map_empty(getParamSpace());
2385
2386 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2387 for (MemoryAccess *MA : ReadOnlyPair.second)
2388 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2389
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002390 Valid =
2391 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002392
2393 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002394 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002395 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002396
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002397 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002398}
2399
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002400static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2401 Loop *L = LI.getLoopFor(R.getEntry());
2402 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2403}
2404
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002405static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2406 ScopDetection &SD) {
2407
2408 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2409
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002410 unsigned MinLD = INT_MAX, MaxLD = 0;
2411 for (BasicBlock *BB : R.blocks()) {
2412 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002413 if (!R.contains(L))
2414 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002415 if (BoxedLoops && BoxedLoops->count(L))
2416 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002417 unsigned LD = L->getLoopDepth();
2418 MinLD = std::min(MinLD, LD);
2419 MaxLD = std::max(MaxLD, LD);
2420 }
2421 }
2422
2423 // Handle the case that there is no loop in the SCoP first.
2424 if (MaxLD == 0)
2425 return 1;
2426
2427 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2428 assert(MaxLD >= MinLD &&
2429 "Maximal loop depth was smaller than mininaml loop depth?");
2430 return MaxLD - MinLD + 1;
2431}
2432
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002433Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002434 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002435 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002436 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2437 AccFuncMap(AccFuncMap), IsOptimized(false),
2438 HasSingleExitEdge(R.getExitingBlock()), MaxLoopDepth(MaxLoopDepth),
2439 IslCtx(Context), Context(nullptr), Affinator(this),
2440 AssumedContext(nullptr), BoundaryContext(nullptr), Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002441
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002442void Scop::init(AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002443 buildContext();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002444 buildInvariantEquivalenceClasses();
2445
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002446 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002447
Michael Krusecac948e2015-10-02 13:53:07 +00002448 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002449 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002450 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002451 if (Stmts.empty())
2452 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002453
Michael Krusecac948e2015-10-02 13:53:07 +00002454 // The ScopStmts now have enough information to initialize themselves.
2455 for (ScopStmt &Stmt : Stmts)
2456 Stmt.init();
2457
2458 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002459 Loop *L = getLoopSurroundingRegion(R, LI);
2460 LoopSchedules[L];
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002461 buildSchedule(&R, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002462 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002463
Tobias Grosser8286b832015-11-02 11:29:32 +00002464 if (isl_set_is_empty(AssumedContext))
2465 return;
2466
2467 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002468 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002469 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002470 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002471 buildBoundaryContext();
2472 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002473 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002474
2475 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002476 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002477}
2478
2479Scop::~Scop() {
2480 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002481 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002482 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002483 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002484
Johannes Doerfert96425c22015-08-30 21:13:53 +00002485 for (auto It : DomainMap)
2486 isl_set_free(It.second);
2487
Johannes Doerfertb164c792014-09-18 11:17:17 +00002488 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002489 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002490 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002491 isl_pw_multi_aff_free(MMA.first);
2492 isl_pw_multi_aff_free(MMA.second);
2493 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002494 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002495 isl_pw_multi_aff_free(MMA.first);
2496 isl_pw_multi_aff_free(MMA.second);
2497 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002498 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002499
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002500 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002501 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002502}
2503
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002504void Scop::updateAccessDimensionality() {
2505 for (auto &Stmt : *this)
2506 for (auto &Access : Stmt)
2507 Access->updateDimensionality();
2508}
2509
Michael Krusecac948e2015-10-02 13:53:07 +00002510void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002511 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2512 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002513 RegionNode *RN = Stmt.isRegionStmt()
2514 ? Stmt.getRegion()->getNode()
2515 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002516
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002517 if (StmtIt->isEmpty() ||
2518 isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]) ||
2519 (RemoveIgnoredStmts && isIgnored(RN))) {
2520
Michael Krusecac948e2015-10-02 13:53:07 +00002521 // Remove the statement because it is unnecessary.
2522 if (Stmt.isRegionStmt())
2523 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2524 StmtMap.erase(BB);
2525 else
2526 StmtMap.erase(Stmt.getBasicBlock());
2527
2528 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002529 continue;
2530 }
2531
Michael Krusecac948e2015-10-02 13:53:07 +00002532 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002533 }
2534}
2535
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002536const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2537 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2538 if (!LInst)
2539 return nullptr;
2540
2541 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2542 LInst = cast<LoadInst>(Rep);
2543
2544 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2545 for (auto &IAClass : InvariantEquivClasses)
2546 if (PointerSCEV == std::get<0>(IAClass))
2547 return &IAClass;
2548
2549 return nullptr;
2550}
2551
2552void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2553
2554 // Get the context under which the statement is executed.
2555 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2556 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2557 DomainCtx = isl_set_detect_equalities(DomainCtx);
2558 DomainCtx = isl_set_coalesce(DomainCtx);
2559
2560 // Project out all parameters that relate to loads in the statement. Otherwise
2561 // we could have cyclic dependences on the constraints under which the
2562 // hoisted loads are executed and we could not determine an order in which to
2563 // pre-load them. This happens because not only lower bounds are part of the
2564 // domain but also upper bounds.
2565 for (MemoryAccess *MA : InvMAs) {
2566 Instruction *AccInst = MA->getAccessInstruction();
2567 if (SE->isSCEVable(AccInst->getType())) {
2568 isl_id *ParamId = getIdForParam(SE->getSCEV(AccInst));
2569 if (ParamId) {
2570 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2571 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2572 }
2573 isl_id_free(ParamId);
2574 }
2575 }
2576
2577 for (MemoryAccess *MA : InvMAs) {
2578 // Check for another invariant access that accesses the same location as
2579 // MA and if found consolidate them. Otherwise create a new equivalence
2580 // class at the end of InvariantEquivClasses.
2581 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2582 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2583
2584 bool Consolidated = false;
2585 for (auto &IAClass : InvariantEquivClasses) {
2586 if (PointerSCEV != std::get<0>(IAClass))
2587 continue;
2588
2589 Consolidated = true;
2590
2591 // Add MA to the list of accesses that are in this class.
2592 auto &MAs = std::get<1>(IAClass);
2593 MAs.push_front(MA);
2594
2595 // Unify the execution context of the class and this statement.
2596 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
2597 IAClassDomainCtx = isl_set_coalesce(
2598 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2599 break;
2600 }
2601
2602 if (Consolidated)
2603 continue;
2604
2605 // If we did not consolidate MA, thus did not find an equivalence class
2606 // for it, we create a new one.
2607 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2608 isl_set_copy(DomainCtx));
2609 }
2610
2611 isl_set_free(DomainCtx);
2612}
2613
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002614void Scop::hoistInvariantLoads() {
2615 isl_union_map *Writes = getWrites();
2616 for (ScopStmt &Stmt : *this) {
2617
2618 // TODO: Loads that are not loop carried, hence are in a statement with
2619 // zero iterators, are by construction invariant, though we
Johannes Doerfert09e36972015-10-07 20:17:36 +00002620 // currently "hoist" them anyway. This is necessary because we allow
2621 // them to be treated as parameters (e.g., in conditions) and our code
2622 // generation would otherwise use the old value.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002623
Johannes Doerfert8930f482015-10-02 14:51:00 +00002624 BasicBlock *BB = Stmt.isBlockStmt() ? Stmt.getBasicBlock()
2625 : Stmt.getRegion()->getEntry();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002626 isl_set *Domain = Stmt.getDomain();
2627 MemoryAccessList InvMAs;
2628
2629 for (MemoryAccess *MA : Stmt) {
2630 if (MA->isImplicit() || MA->isWrite() || !MA->isAffine())
2631 continue;
2632
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002633 // Skip accesses that have an invariant base pointer which is defined but
2634 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2635 // returns a pointer that is used as a base address. However, as we want
2636 // to hoist indirect pointers, we allow the base pointer to be defined in
Johannes Doerfert654c3282015-10-21 22:14:57 +00002637 // the region if it is also a memory access. Each ScopArrayInfo object
2638 // that has a base pointer origin has a base pointer that is loaded and
2639 // that it is invariant, thus it will be hoisted too. However, if there is
Tobias Grosser27e19a02015-10-25 12:05:14 +00002640 // no base pointer origin we check that the base pointer is defined
Johannes Doerfert654c3282015-10-21 22:14:57 +00002641 // outside the region.
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002642 const ScopArrayInfo *SAI = MA->getScopArrayInfo();
Johannes Doerfert654c3282015-10-21 22:14:57 +00002643 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2644 SAI = BasePtrOriginSAI;
2645
2646 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2647 if (R.contains(BasePtrInst))
2648 continue;
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002649
Johannes Doerfert8930f482015-10-02 14:51:00 +00002650 // Skip accesses in non-affine subregions as they might not be executed
2651 // under the same condition as the entry of the non-affine subregion.
2652 if (BB != MA->getAccessInstruction()->getParent())
2653 continue;
2654
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002655 isl_map *AccessRelation = MA->getAccessRelation();
Johannes Doerfertb864c2c2015-10-18 19:50:18 +00002656
2657 // Skip accesses that have an empty access relation. These can be caused
2658 // by multiple offsets with a type cast in-between that cause the overall
2659 // byte offset to be not divisible by the new types sizes.
2660 if (isl_map_is_empty(AccessRelation)) {
2661 isl_map_free(AccessRelation);
2662 continue;
2663 }
2664
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002665 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2666 Stmt.getNumIterators())) {
2667 isl_map_free(AccessRelation);
2668 continue;
2669 }
2670
2671 AccessRelation =
2672 isl_map_intersect_domain(AccessRelation, isl_set_copy(Domain));
2673 isl_set *AccessRange = isl_map_range(AccessRelation);
2674
2675 isl_union_map *Written = isl_union_map_intersect_range(
2676 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2677 bool IsWritten = !isl_union_map_is_empty(Written);
2678 isl_union_map_free(Written);
2679
2680 if (IsWritten)
2681 continue;
2682
2683 InvMAs.push_front(MA);
2684 }
2685
2686 // We inserted invariant accesses always in the front but need them to be
2687 // sorted in a "natural order". The statements are already sorted in reverse
2688 // post order and that suffices for the accesses too. The reason we require
2689 // an order in the first place is the dependences between invariant loads
2690 // that can be caused by indirect loads.
2691 InvMAs.reverse();
2692
2693 // Transfer the memory access from the statement to the SCoP.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002694 Stmt.removeMemoryAccesses(InvMAs);
2695 addInvariantLoads(Stmt, InvMAs);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002696
2697 isl_set_free(Domain);
2698 }
2699 isl_union_map_free(Writes);
2700
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002701 if (!InvariantEquivClasses.empty())
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002702 IsOptimized = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00002703
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002704 auto &ScopRIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002705 // Check required invariant loads that were tagged during SCoP detection.
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002706 for (LoadInst *LI : ScopRIL) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00002707 assert(LI && getRegion().contains(LI));
2708 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
2709 if (Stmt && Stmt->lookupAccessesFor(LI) != nullptr) {
2710 DEBUG(dbgs() << "\n\nWARNING: Load (" << *LI
2711 << ") is required to be invariant but was not marked as "
2712 "such. SCoP for "
2713 << getRegion() << " will be dropped\n\n");
2714 addAssumption(isl_set_empty(getParamSpace()));
2715 return;
2716 }
2717 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002718}
2719
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002720const ScopArrayInfo *
2721Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Michael Kruse28468772015-09-14 15:45:33 +00002722 ArrayRef<const SCEV *> Sizes, bool IsPHI) {
Tobias Grosser92245222015-07-28 14:53:44 +00002723 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002724 if (!SAI) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002725 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
2726 this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002727 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002728 // In case of mismatching array sizes, we bail out by setting the run-time
2729 // context to false.
2730 if (!SAI->updateSizes(Sizes))
2731 addAssumption(isl_set_empty(getParamSpace()));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002732 }
Tobias Grosserab671442015-05-23 05:58:27 +00002733 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002734}
2735
Tobias Grosser92245222015-07-28 14:53:44 +00002736const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
2737 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002738 assert(SAI && "No ScopArrayInfo available for this base pointer");
2739 return SAI;
2740}
2741
Tobias Grosser74394f02013-01-14 22:40:23 +00002742std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002743std::string Scop::getAssumedContextStr() const {
2744 return stringFromIslObj(AssumedContext);
2745}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002746std::string Scop::getBoundaryContextStr() const {
2747 return stringFromIslObj(BoundaryContext);
2748}
Tobias Grosser75805372011-04-29 06:27:02 +00002749
2750std::string Scop::getNameStr() const {
2751 std::string ExitName, EntryName;
2752 raw_string_ostream ExitStr(ExitName);
2753 raw_string_ostream EntryStr(EntryName);
2754
Tobias Grosserf240b482014-01-09 10:42:15 +00002755 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002756 EntryStr.str();
2757
2758 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002759 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002760 ExitStr.str();
2761 } else
2762 ExitName = "FunctionExit";
2763
2764 return EntryName + "---" + ExitName;
2765}
2766
Tobias Grosser74394f02013-01-14 22:40:23 +00002767__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002768__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002769 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002770}
2771
Tobias Grossere86109f2013-10-29 21:05:49 +00002772__isl_give isl_set *Scop::getAssumedContext() const {
2773 return isl_set_copy(AssumedContext);
2774}
2775
Johannes Doerfert43788c52015-08-20 05:58:56 +00002776__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2777 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002778 RuntimeCheckContext =
2779 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2780 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002781 return RuntimeCheckContext;
2782}
2783
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002784bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002785 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002786 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002787 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2788 isl_set_free(RuntimeCheckContext);
2789 return IsFeasible;
2790}
2791
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002792void Scop::addAssumption(__isl_take isl_set *Set) {
2793 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002794 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002795}
2796
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002797__isl_give isl_set *Scop::getBoundaryContext() const {
2798 return isl_set_copy(BoundaryContext);
2799}
2800
Tobias Grosser75805372011-04-29 06:27:02 +00002801void Scop::printContext(raw_ostream &OS) const {
2802 OS << "Context:\n";
2803
2804 if (!Context) {
2805 OS.indent(4) << "n/a\n\n";
2806 return;
2807 }
2808
2809 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002810
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002811 OS.indent(4) << "Assumed Context:\n";
2812 if (!AssumedContext) {
2813 OS.indent(4) << "n/a\n\n";
2814 return;
2815 }
2816
2817 OS.indent(4) << getAssumedContextStr() << "\n";
2818
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002819 OS.indent(4) << "Boundary Context:\n";
2820 if (!BoundaryContext) {
2821 OS.indent(4) << "n/a\n\n";
2822 return;
2823 }
2824
2825 OS.indent(4) << getBoundaryContextStr() << "\n";
2826
Tobias Grosser083d3d32014-06-28 08:59:45 +00002827 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002828 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002829 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2830 }
Tobias Grosser75805372011-04-29 06:27:02 +00002831}
2832
Johannes Doerfertb164c792014-09-18 11:17:17 +00002833void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002834 int noOfGroups = 0;
2835 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002836 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002837 noOfGroups += 1;
2838 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002839 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002840 }
2841
Tobias Grosserbb853c22015-07-25 12:31:03 +00002842 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002843 if (MinMaxAliasGroups.empty()) {
2844 OS.indent(8) << "n/a\n";
2845 return;
2846 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002847
Tobias Grosserbb853c22015-07-25 12:31:03 +00002848 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002849
2850 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002851 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002852 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002853 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002854 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2855 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002856 }
2857 OS << " ]]\n";
2858 }
2859
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002860 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002861 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002862 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002863 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002864 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2865 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002866 }
2867 OS << " ]]\n";
2868 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002869 }
2870}
2871
Tobias Grosser75805372011-04-29 06:27:02 +00002872void Scop::printStatements(raw_ostream &OS) const {
2873 OS << "Statements {\n";
2874
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002875 for (const ScopStmt &Stmt : *this)
2876 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002877
2878 OS.indent(4) << "}\n";
2879}
2880
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002881void Scop::printArrayInfo(raw_ostream &OS) const {
2882 OS << "Arrays {\n";
2883
Tobias Grosserab671442015-05-23 05:58:27 +00002884 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002885 Array.second->print(OS);
2886
2887 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002888
2889 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2890
2891 for (auto &Array : arrays())
2892 Array.second->print(OS, /* SizeAsPwAff */ true);
2893
2894 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002895}
2896
Tobias Grosser75805372011-04-29 06:27:02 +00002897void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002898 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2899 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002900 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002901 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002902 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002903 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002904 const auto &MAs = std::get<1>(IAClass);
2905 if (MAs.empty()) {
2906 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002907 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002908 MAs.front()->print(OS);
2909 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002910 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002911 }
2912 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002913 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002914 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002915 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002916 printStatements(OS.indent(4));
2917}
2918
2919void Scop::dump() const { print(dbgs()); }
2920
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002921isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002922
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002923__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
2924 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002925}
2926
Tobias Grosser808cd692015-07-14 09:33:13 +00002927__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002928 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002929
Tobias Grosser808cd692015-07-14 09:33:13 +00002930 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002931 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002932
2933 return Domain;
2934}
2935
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002936__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002937 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002938
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002939 for (ScopStmt &Stmt : *this) {
2940 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002941 if (!MA->isMustWrite())
2942 continue;
2943
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002944 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002945 isl_map *AccessDomain = MA->getAccessRelation();
2946 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2947 Write = isl_union_map_add_map(Write, AccessDomain);
2948 }
2949 }
2950 return isl_union_map_coalesce(Write);
2951}
2952
2953__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002954 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002955
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002956 for (ScopStmt &Stmt : *this) {
2957 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002958 if (!MA->isMayWrite())
2959 continue;
2960
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002961 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002962 isl_map *AccessDomain = MA->getAccessRelation();
2963 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2964 Write = isl_union_map_add_map(Write, AccessDomain);
2965 }
2966 }
2967 return isl_union_map_coalesce(Write);
2968}
2969
Tobias Grosser37eb4222014-02-20 21:43:54 +00002970__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002971 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002972
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002973 for (ScopStmt &Stmt : *this) {
2974 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002975 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002976 continue;
2977
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002978 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002979 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002980 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2981 Write = isl_union_map_add_map(Write, AccessDomain);
2982 }
2983 }
2984 return isl_union_map_coalesce(Write);
2985}
2986
2987__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002988 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002989
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002990 for (ScopStmt &Stmt : *this) {
2991 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002992 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002993 continue;
2994
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002995 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002996 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002997
2998 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2999 Read = isl_union_map_add_map(Read, AccessDomain);
3000 }
3001 }
3002 return isl_union_map_coalesce(Read);
3003}
3004
Tobias Grosser808cd692015-07-14 09:33:13 +00003005__isl_give isl_union_map *Scop::getSchedule() const {
3006 auto Tree = getScheduleTree();
3007 auto S = isl_schedule_get_map(Tree);
3008 isl_schedule_free(Tree);
3009 return S;
3010}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003011
Tobias Grosser808cd692015-07-14 09:33:13 +00003012__isl_give isl_schedule *Scop::getScheduleTree() const {
3013 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3014 getDomains());
3015}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003016
Tobias Grosser808cd692015-07-14 09:33:13 +00003017void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3018 auto *S = isl_schedule_from_domain(getDomains());
3019 S = isl_schedule_insert_partial_schedule(
3020 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3021 isl_schedule_free(Schedule);
3022 Schedule = S;
3023}
3024
3025void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3026 isl_schedule_free(Schedule);
3027 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003028}
3029
3030bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3031 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003032 for (ScopStmt &Stmt : *this) {
3033 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003034 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3035 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3036
3037 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3038 isl_union_set_free(StmtDomain);
3039 isl_union_set_free(NewStmtDomain);
3040 continue;
3041 }
3042
3043 Changed = true;
3044
3045 isl_union_set_free(StmtDomain);
3046 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3047
3048 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003049 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003050 isl_union_set_free(NewStmtDomain);
3051 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003052 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003053 }
3054 isl_union_set_free(Domain);
3055 return Changed;
3056}
3057
Tobias Grosser75805372011-04-29 06:27:02 +00003058ScalarEvolution *Scop::getSE() const { return SE; }
3059
Johannes Doerfertf5673802015-10-01 23:48:18 +00003060bool Scop::isIgnored(RegionNode *RN) {
3061 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser75805372011-04-29 06:27:02 +00003062
Johannes Doerfertf5673802015-10-01 23:48:18 +00003063 // Check if there are accesses contained.
3064 bool ContainsAccesses = false;
3065 if (!RN->isSubRegion())
3066 ContainsAccesses = getAccessFunctions(BB);
3067 else
3068 for (BasicBlock *RBB : RN->getNodeAs<Region>()->blocks())
3069 ContainsAccesses |= (getAccessFunctions(RBB) != nullptr);
3070 if (!ContainsAccesses)
3071 return true;
3072
3073 // Check for reachability via non-error blocks.
3074 if (!DomainMap.count(BB))
3075 return true;
3076
3077 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003078 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003079 return true;
3080
3081 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003082}
3083
Tobias Grosser808cd692015-07-14 09:33:13 +00003084struct MapToDimensionDataTy {
3085 int N;
3086 isl_union_pw_multi_aff *Res;
3087};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003088
Tobias Grosser808cd692015-07-14 09:33:13 +00003089// @brief Create a function that maps the elements of 'Set' to its N-th
3090// dimension.
3091//
3092// The result is added to 'User->Res'.
3093//
3094// @param Set The input set.
3095// @param N The dimension to map to.
3096//
3097// @returns Zero if no error occurred, non-zero otherwise.
3098static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3099 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3100 int Dim;
3101 isl_space *Space;
3102 isl_pw_multi_aff *PMA;
3103
3104 Dim = isl_set_dim(Set, isl_dim_set);
3105 Space = isl_set_get_space(Set);
3106 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3107 Dim - Data->N);
3108 if (Data->N > 1)
3109 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3110 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3111
3112 isl_set_free(Set);
3113
3114 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003115}
3116
Tobias Grosser808cd692015-07-14 09:33:13 +00003117// @brief Create a function that maps the elements of Domain to their Nth
3118// dimension.
3119//
3120// @param Domain The set of elements to map.
3121// @param N The dimension to map to.
3122static __isl_give isl_multi_union_pw_aff *
3123mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003124 if (N <= 0 || isl_union_set_is_empty(Domain)) {
3125 isl_union_set_free(Domain);
3126 return nullptr;
3127 }
3128
Tobias Grosser808cd692015-07-14 09:33:13 +00003129 struct MapToDimensionDataTy Data;
3130 isl_space *Space;
3131
3132 Space = isl_union_set_get_space(Domain);
3133 Data.N = N;
3134 Data.Res = isl_union_pw_multi_aff_empty(Space);
3135 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
3136 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
3137
3138 isl_union_set_free(Domain);
3139 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3140}
3141
Michael Kruse9d080092015-09-11 21:41:48 +00003142ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003143 ScopStmt *Stmt;
3144 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003145 Stmts.emplace_back(*this, *BB);
Tobias Grosser808cd692015-07-14 09:33:13 +00003146 Stmt = &Stmts.back();
3147 StmtMap[BB] = Stmt;
3148 } else {
3149 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003150 Stmts.emplace_back(*this, *R);
Tobias Grosser808cd692015-07-14 09:33:13 +00003151 Stmt = &Stmts.back();
3152 for (BasicBlock *BB : R->blocks())
3153 StmtMap[BB] = Stmt;
3154 }
3155 return Stmt;
3156}
3157
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003158void Scop::buildSchedule(
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003159 Region *R,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003160 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003161
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003162 if (SD.isNonAffineSubRegion(R, &getRegion())) {
Johannes Doerfertc6987c12015-09-26 13:41:43 +00003163 Loop *L = getLoopSurroundingRegion(*R, LI);
3164 auto &LSchedulePair = LoopSchedules[L];
Michael Krusecac948e2015-10-02 13:53:07 +00003165 ScopStmt *Stmt = getStmtForBasicBlock(R->getEntry());
Michael Kruseafe06702015-10-02 16:33:27 +00003166 isl_set *Domain = Stmt->getDomain();
Michael Krusecac948e2015-10-02 13:53:07 +00003167 auto *UDomain = isl_union_set_from_set(Domain);
3168 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003169 LSchedulePair.first = StmtSchedule;
3170 return;
3171 }
3172
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003173 ReversePostOrderTraversal<Region *> RTraversal(R);
3174 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00003175
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003176 if (RN->isSubRegion()) {
3177 Region *SubRegion = RN->getNodeAs<Region>();
3178 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003179 buildSchedule(SubRegion, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003180 continue;
3181 }
Tobias Grosser75805372011-04-29 06:27:02 +00003182 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003183
3184 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert30c22652015-10-18 21:17:11 +00003185 if (!getRegion().contains(L))
3186 L = getLoopSurroundingRegion(getRegion(), LI);
3187
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003188 int LD = getRelativeLoopDepth(L);
3189 auto &LSchedulePair = LoopSchedules[L];
3190 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3191
Michael Krusecac948e2015-10-02 13:53:07 +00003192 BasicBlock *BB = getRegionNodeBasicBlock(RN);
3193 ScopStmt *Stmt = getStmtForBasicBlock(BB);
3194 if (Stmt) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003195 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3196 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3197 LSchedulePair.first =
3198 combineInSequence(LSchedulePair.first, StmtSchedule);
3199 }
3200
3201 unsigned NumVisited = LSchedulePair.second;
3202 while (L && NumVisited == L->getNumBlocks()) {
3203 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
3204 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
3205 LSchedulePair.first =
3206 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
3207
3208 auto *PL = L->getParentLoop();
Johannes Doerfertdca28372015-11-03 00:28:07 +00003209
3210 // Either we have a proper loop and we also build a schedule for the
3211 // parent loop or we have a infinite loop that does not have a proper
3212 // parent loop. In the former case this conditional will be skipped, in
3213 // the latter case however we will break here as we do not build a domain
3214 // nor a schedule for a infinite loop.
3215 assert(LoopSchedules.count(PL) || LSchedulePair.first == nullptr);
3216 if (!LoopSchedules.count(PL))
3217 break;
3218
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003219 auto &PSchedulePair = LoopSchedules[PL];
3220 PSchedulePair.first =
3221 combineInSequence(PSchedulePair.first, LSchedulePair.first);
3222 PSchedulePair.second += NumVisited;
3223
3224 L = PL;
3225 NumVisited = PSchedulePair.second;
3226 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003227 }
Tobias Grosser75805372011-04-29 06:27:02 +00003228}
3229
Johannes Doerfert7c494212014-10-31 23:13:39 +00003230ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003231 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003232 if (StmtMapIt == StmtMap.end())
3233 return nullptr;
3234 return StmtMapIt->second;
3235}
3236
Johannes Doerfert96425c22015-08-30 21:13:53 +00003237int Scop::getRelativeLoopDepth(const Loop *L) const {
3238 Loop *OuterLoop =
3239 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3240 if (!OuterLoop)
3241 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003242 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3243}
3244
Michael Krused868b5d2015-09-10 15:25:24 +00003245void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003246 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003247
3248 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3249 // true, are not modeled as ordinary PHI nodes as they are not part of the
3250 // region. However, we model the operands in the predecessor blocks that are
3251 // part of the region as regular scalar accesses.
3252
3253 // If we can synthesize a PHI we can skip it, however only if it is in
3254 // the region. If it is not it can only be in the exit block of the region.
3255 // In this case we model the operands but not the PHI itself.
3256 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3257 return;
3258
3259 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3260 // detection. Hence, the PHI is a load of a new memory location in which the
3261 // incoming value was written at the end of the incoming basic block.
3262 bool OnlyNonAffineSubRegionOperands = true;
3263 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3264 Value *Op = PHI->getIncomingValue(u);
3265 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3266
3267 // Do not build scalar dependences inside a non-affine subregion.
3268 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3269 continue;
3270
3271 OnlyNonAffineSubRegionOperands = false;
3272
3273 if (!R.contains(OpBB))
3274 continue;
3275
3276 Instruction *OpI = dyn_cast<Instruction>(Op);
3277 if (OpI) {
3278 BasicBlock *OpIBB = OpI->getParent();
3279 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3280 // we have to insert a scalar dependence from the definition of OpI to
3281 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003282 if (scop->getStmtForBasicBlock(OpIBB) !=
3283 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003284 addScalarReadAccess(OpI, PHI, OpBB);
3285 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003286 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003287 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003288 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003289 }
3290
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003291 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003292 }
3293
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003294 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3295 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003296 }
3297}
3298
Michael Krused868b5d2015-09-10 15:25:24 +00003299bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3300 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003301 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3302 if (isIgnoredIntrinsic(Inst))
3303 return false;
3304
3305 bool AnyCrossStmtUse = false;
3306 BasicBlock *ParentBB = Inst->getParent();
3307
3308 for (User *U : Inst->users()) {
3309 Instruction *UI = dyn_cast<Instruction>(U);
3310
3311 // Ignore the strange user
3312 if (UI == 0)
3313 continue;
3314
3315 BasicBlock *UseParent = UI->getParent();
3316
Tobias Grosserbaffa092015-10-24 20:55:27 +00003317 // Ignore basic block local uses. A value that is defined in a scop, but
3318 // used in a PHI node in the same basic block does not count as basic block
3319 // local, as for such cases a control flow edge is passed between definition
3320 // and use.
3321 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003322 continue;
3323
3324 // Do not build scalar dependences inside a non-affine subregion.
3325 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3326 continue;
3327
Michael Kruse01cb3792015-10-17 21:07:08 +00003328 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003329 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003330 //
3331 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003332 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3333 // the control flow a different value will be assigned to the PHI node. In
3334 // case this is the case, there is no need to create an additional normal
3335 // scalar dependence. Hence, bail out before we register an "out-of-region"
3336 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003337 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3338 !R->getExitingBlock())
3339 continue;
3340
Michael Kruse7bf39442015-09-10 12:46:52 +00003341 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003342 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003343 AnyCrossStmtUse = true;
3344 continue;
3345 }
3346
Tobias Grosserbaffa092015-10-24 20:55:27 +00003347 // Uses by PHI nodes in the entry node count as external uses in case the
3348 // use is through an incoming block that is itself not contained in the
3349 // region.
3350 if (R->getEntry() == UseParent) {
3351 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3352 bool ExternalUse = false;
3353 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3354 if (PHI->getIncomingValue(i) == Inst &&
3355 !R->contains(PHI->getIncomingBlock(i))) {
3356 ExternalUse = true;
3357 break;
3358 }
3359 }
3360
3361 if (ExternalUse) {
3362 AnyCrossStmtUse = true;
3363 continue;
3364 }
3365 }
3366 }
3367
Michael Kruse7bf39442015-09-10 12:46:52 +00003368 // If the instruction can be synthesized and the user is in the region
3369 // we do not need to add scalar dependences.
3370 if (canSynthesizeInst)
3371 continue;
3372
3373 // No need to translate these scalar dependences into polyhedral form,
3374 // because synthesizable scalars can be generated by the code generator.
3375 if (canSynthesize(UI, LI, SE, R))
3376 continue;
3377
3378 // Skip PHI nodes in the region as they handle their operands on their own.
3379 if (isa<PHINode>(UI))
3380 continue;
3381
3382 // Now U is used in another statement.
3383 AnyCrossStmtUse = true;
3384
3385 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003386 // Use the def instruction as base address of the MemoryAccess, so that it
3387 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003388 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003389 }
3390
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003391 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003392 for (Value *Op : Inst->operands()) {
3393 if (canSynthesize(Op, LI, SE, R))
3394 continue;
3395
3396 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3397 if (R->contains(OpInst))
3398 continue;
3399
3400 if (isa<Constant>(Op))
3401 continue;
3402
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003403 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003404 }
3405 }
3406
3407 return AnyCrossStmtUse;
3408}
3409
3410extern MapInsnToMemAcc InsnToMemAcc;
3411
Michael Krusee2bccbb2015-09-18 19:59:43 +00003412void ScopInfo::buildMemoryAccess(
3413 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003414 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3415 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003416 unsigned Size;
3417 Type *SizeType;
3418 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003419 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003420
3421 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3422 SizeType = Load->getType();
3423 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003424 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003425 Val = Load;
3426 } else {
3427 StoreInst *Store = cast<StoreInst>(Inst);
3428 SizeType = Store->getValueOperand()->getType();
3429 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003430 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003431 Val = Store->getValueOperand();
3432 }
3433
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003434 auto Address = getPointerOperand(*Inst);
3435
3436 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003437 const SCEVUnknown *BasePointer =
3438 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3439
3440 assert(BasePointer && "Could not find base pointer");
3441 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3442
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003443 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3444 auto NewAddress = Address;
3445 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3446 auto Src = BitCast->getOperand(0);
3447 auto SrcTy = Src->getType();
3448 auto DstTy = BitCast->getType();
3449 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3450 NewAddress = Src;
3451 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003452
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003453 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3454 std::vector<const SCEV *> Subscripts;
3455 std::vector<int> Sizes;
3456 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3457 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003458
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003459 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003460
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003461 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003462 for (auto Subscript : Subscripts) {
3463 InvariantLoadsSetTy AccessILS;
3464 AllAffineSubcripts =
3465 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3466
3467 for (LoadInst *LInst : AccessILS)
3468 if (!ScopRIL.count(LInst))
3469 AllAffineSubcripts = false;
3470
3471 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003472 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003473 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003474
3475 if (AllAffineSubcripts && Sizes.size() > 0) {
3476 for (auto V : Sizes)
3477 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3478 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003479 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003480 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003481
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003482 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3483 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003484 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003485 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003486 }
3487 }
3488
Michael Kruse7bf39442015-09-10 12:46:52 +00003489 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003490 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003491 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3492 AccItr->second.DelinearizedSubscripts,
3493 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003494 return;
3495 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003496
3497 // Check if the access depends on a loop contained in a non-affine subregion.
3498 bool isVariantInNonAffineLoop = false;
3499 if (BoxedLoops) {
3500 SetVector<const Loop *> Loops;
3501 findLoops(AccessFunction, Loops);
3502 for (const Loop *L : Loops)
3503 if (BoxedLoops->count(L))
3504 isVariantInNonAffineLoop = true;
3505 }
3506
Johannes Doerfert09e36972015-10-07 20:17:36 +00003507 InvariantLoadsSetTy AccessILS;
3508 bool IsAffine =
3509 !isVariantInNonAffineLoop &&
3510 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3511
3512 for (LoadInst *LInst : AccessILS)
3513 if (!ScopRIL.count(LInst))
3514 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003515
Michael Krusecaac2b62015-09-26 15:51:44 +00003516 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003517 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003518 const SCEV *SizeSCEV =
3519 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003520
Michael Krusee2bccbb2015-09-18 19:59:43 +00003521 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3522 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003523
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003524 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3525 ArrayRef<const SCEV *>(AccessFunction),
3526 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003527}
3528
Michael Krused868b5d2015-09-10 15:25:24 +00003529void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003530
3531 if (SD->isNonAffineSubRegion(&SR, &R)) {
3532 for (BasicBlock *BB : SR.blocks())
3533 buildAccessFunctions(R, *BB, &SR);
3534 return;
3535 }
3536
3537 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3538 if (I->isSubRegion())
3539 buildAccessFunctions(R, *I->getNodeAs<Region>());
3540 else
3541 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3542}
3543
Michael Krusecac948e2015-10-02 13:53:07 +00003544void ScopInfo::buildStmts(Region &SR) {
3545 Region *R = getRegion();
3546
3547 if (SD->isNonAffineSubRegion(&SR, R)) {
3548 scop->addScopStmt(nullptr, &SR);
3549 return;
3550 }
3551
3552 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3553 if (I->isSubRegion())
3554 buildStmts(*I->getNodeAs<Region>());
3555 else
3556 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3557}
3558
Michael Krused868b5d2015-09-10 15:25:24 +00003559void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3560 Region *NonAffineSubRegion,
3561 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003562 Loop *L = LI->getLoopFor(&BB);
3563
3564 // The set of loops contained in non-affine subregions that are part of R.
3565 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3566
Johannes Doerfert09e36972015-10-07 20:17:36 +00003567 // The set of loads that are required to be invariant.
3568 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3569
Michael Kruse7bf39442015-09-10 12:46:52 +00003570 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
3571 Instruction *Inst = I;
3572
3573 PHINode *PHI = dyn_cast<PHINode>(Inst);
3574 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003575 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003576
3577 // For the exit block we stop modeling after the last PHI node.
3578 if (!PHI && IsExitBlock)
3579 break;
3580
Johannes Doerfert09e36972015-10-07 20:17:36 +00003581 // TODO: At this point we only know that elements of ScopRIL have to be
3582 // invariant and will be hoisted for the SCoP to be processed. Though,
3583 // there might be other invariant accesses that will be hoisted and
3584 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003585 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003586 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003587
3588 if (isIgnoredIntrinsic(Inst))
3589 continue;
3590
Johannes Doerfert09e36972015-10-07 20:17:36 +00003591 // Do not build scalar dependences for required invariant loads as we will
3592 // hoist them later on anyway or drop the SCoP if we cannot.
3593 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3594 continue;
3595
Michael Kruse7bf39442015-09-10 12:46:52 +00003596 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003597 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003598 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003599 }
3600 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003601}
Michael Kruse7bf39442015-09-10 12:46:52 +00003602
Michael Kruse2d0ece92015-09-24 11:41:21 +00003603void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3604 MemoryAccess::AccessType Type,
3605 Value *BaseAddress, unsigned ElemBytes,
3606 bool Affine, Value *AccessValue,
3607 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003608 ArrayRef<const SCEV *> Sizes,
3609 MemoryAccess::AccessOrigin Origin) {
Michael Krusecac948e2015-10-02 13:53:07 +00003610 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3611
3612 // Do not create a memory access for anything not in the SCoP. It would be
3613 // ignored anyway.
3614 if (!Stmt)
3615 return;
3616
Michael Krusee2bccbb2015-09-18 19:59:43 +00003617 AccFuncSetType &AccList = AccFuncMap[BB];
3618 size_t Identifier = AccList.size();
Michael Kruse7bf39442015-09-10 12:46:52 +00003619
Michael Krusee2bccbb2015-09-18 19:59:43 +00003620 Value *BaseAddr = BaseAddress;
3621 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3622
3623 std::string IdName = "__polly_array_ref_" + std::to_string(Identifier);
3624 isl_id *Id = isl_id_alloc(ctx, IdName.c_str(), nullptr);
3625
Michael Krusecac948e2015-10-02 13:53:07 +00003626 bool isApproximated =
3627 Stmt->isRegionStmt() && (Stmt->getRegion()->getEntry() != BB);
3628 if (isApproximated && Type == MemoryAccess::MUST_WRITE)
3629 Type = MemoryAccess::MAY_WRITE;
3630
3631 AccList.emplace_back(Stmt, Inst, Id, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003632 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003633 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003634}
3635
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003636void ScopInfo::addExplicitAccess(
3637 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
3638 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
3639 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
3640 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3641 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3642 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003643 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
3644 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003645}
3646void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3647 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3648 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003649 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003650}
3651void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3652 assert(!isa<PHINode>(User));
3653 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3654 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003655 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003656}
3657void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3658 BasicBlock *UserBB) {
3659 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003660 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3661 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003662}
3663void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3664 Value *IncomingValue, bool IsExitBlock) {
3665 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3666 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3667 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003668 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003669}
3670void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3671 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003672 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3673 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003674}
3675
Michael Kruse76e924d2015-09-30 09:16:07 +00003676void ScopInfo::buildScop(Region &R, DominatorTree &DT) {
Michael Kruse9d080092015-09-11 21:41:48 +00003677 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003678 scop = new Scop(R, AccFuncMap, *SD, *SE, DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003679
Michael Krusecac948e2015-10-02 13:53:07 +00003680 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003681 buildAccessFunctions(R, R);
3682
3683 // In case the region does not have an exiting block we will later (during
3684 // code generation) split the exit block. This will move potential PHI nodes
3685 // from the current exit block into the new region exiting block. Hence, PHI
3686 // nodes that are at this point not part of the region will be.
3687 // To handle these PHI nodes later we will now model their operands as scalar
3688 // accesses. Note that we do not model anything in the exit block if we have
3689 // an exiting block in the region, as there will not be any splitting later.
3690 if (!R.getExitingBlock())
3691 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3692
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003693 scop->init(*AA);
Michael Kruse7bf39442015-09-10 12:46:52 +00003694}
3695
Michael Krused868b5d2015-09-10 15:25:24 +00003696void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003697 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003698 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003699 return;
3700 }
3701
Michael Kruse9d080092015-09-11 21:41:48 +00003702 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003703}
3704
Michael Krused868b5d2015-09-10 15:25:24 +00003705void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003706 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003707 if (scop) {
3708 delete scop;
3709 scop = 0;
3710 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003711}
3712
3713//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003714ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003715 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003716 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003717}
3718
3719ScopInfo::~ScopInfo() {
3720 clear();
3721 isl_ctx_free(ctx);
3722}
3723
Tobias Grosser75805372011-04-29 06:27:02 +00003724void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00003725 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003726 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003727 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003728 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3729 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003730 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00003731 AU.setPreservesAll();
3732}
3733
3734bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003735 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003736
Michael Krused868b5d2015-09-10 15:25:24 +00003737 if (!SD->isMaxRegionInScop(*R))
3738 return false;
3739
3740 Function *F = R->getEntry()->getParent();
3741 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3742 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3743 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3744 TD = &F->getParent()->getDataLayout();
3745 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Krused868b5d2015-09-10 15:25:24 +00003746
Michael Kruse76e924d2015-09-30 09:16:07 +00003747 buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00003748
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003749 DEBUG(scop->print(dbgs()));
3750
Michael Kruseafe06702015-10-02 16:33:27 +00003751 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003752 delete scop;
3753 scop = nullptr;
3754 return false;
3755 }
3756
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003757 // Statistics.
3758 ++ScopFound;
3759 if (scop->getMaxLoopDepth() > 0)
3760 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00003761 return false;
3762}
3763
3764char ScopInfo::ID = 0;
3765
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003766Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3767
Tobias Grosser73600b82011-10-08 00:30:40 +00003768INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3769 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003770 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003771INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00003772INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003773INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003774INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003775INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003776INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003777INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3778 "Polly - Create polyhedral description of Scops", false,
3779 false)