blob: 396a11e13aebf094aafaed8b7c20bd145d9a81eb [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();
Johannes Doerferte071f6d2015-11-03 16:49:59 +00001540 if (!Val->hasName())
1541 if (LoadInst *LI = dyn_cast<LoadInst>(Val))
1542 ParameterName =
1543 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001544 }
1545
1546 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001547 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001548
Tobias Grosser20532b82014-04-11 17:56:49 +00001549 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1550 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001551}
Tobias Grosser75805372011-04-29 06:27:02 +00001552
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001553isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1554 isl_set *DomainContext = isl_union_set_params(getDomains());
1555 return isl_set_intersect_params(C, DomainContext);
1556}
1557
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001558void Scop::buildBoundaryContext() {
1559 BoundaryContext = Affinator.getWrappingContext();
1560 BoundaryContext = isl_set_complement(BoundaryContext);
1561 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
1562}
1563
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001564void Scop::addUserContext() {
1565 if (UserContextStr.empty())
1566 return;
1567
1568 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1569 isl_space *Space = getParamSpace();
1570 if (isl_space_dim(Space, isl_dim_param) !=
1571 isl_set_dim(UserContext, isl_dim_param)) {
1572 auto SpaceStr = isl_space_to_str(Space);
1573 errs() << "Error: the context provided in -polly-context has not the same "
1574 << "number of dimensions than the computed context. Due to this "
1575 << "mismatch, the -polly-context option is ignored. Please provide "
1576 << "the context in the parameter space: " << SpaceStr << ".\n";
1577 free(SpaceStr);
1578 isl_set_free(UserContext);
1579 isl_space_free(Space);
1580 return;
1581 }
1582
1583 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1584 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1585 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1586
1587 if (strcmp(NameContext, NameUserContext) != 0) {
1588 auto SpaceStr = isl_space_to_str(Space);
1589 errs() << "Error: the name of dimension " << i
1590 << " provided in -polly-context "
1591 << "is '" << NameUserContext << "', but the name in the computed "
1592 << "context is '" << NameContext
1593 << "'. Due to this name mismatch, "
1594 << "the -polly-context option is ignored. Please provide "
1595 << "the context in the parameter space: " << SpaceStr << ".\n";
1596 free(SpaceStr);
1597 isl_set_free(UserContext);
1598 isl_space_free(Space);
1599 return;
1600 }
1601
1602 UserContext =
1603 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1604 isl_space_get_dim_id(Space, isl_dim_param, i));
1605 }
1606
1607 Context = isl_set_intersect(Context, UserContext);
1608 isl_space_free(Space);
1609}
1610
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001611void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001612 DenseMap<const SCEV *, LoadInst *> EquivClasses;
1613
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001614 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001615 for (LoadInst *LInst : RIL) {
1616 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1617
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001618 LoadInst *&ClassRep = EquivClasses[PointerSCEV];
1619 if (!ClassRep)
1620 ClassRep = LInst;
1621 else
1622 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001623 }
1624}
1625
Tobias Grosser6be480c2011-11-08 15:41:13 +00001626void Scop::buildContext() {
1627 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001628 Context = isl_set_universe(isl_space_copy(Space));
1629 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001630}
1631
Tobias Grosser18daaca2012-05-22 10:47:27 +00001632void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001633 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001634 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001635
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001636 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001637
Johannes Doerferte7044942015-02-24 11:58:30 +00001638 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001639 }
1640}
1641
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001642void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001643 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001644 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001645
Tobias Grosser083d3d32014-06-28 08:59:45 +00001646 for (const auto &ParamID : ParameterIds) {
1647 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001648 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001649 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001650 }
1651
1652 // Align the parameters of all data structures to the model.
1653 Context = isl_set_align_params(Context, Space);
1654
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001655 for (ScopStmt &Stmt : *this)
1656 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001657}
1658
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001659static __isl_give isl_set *
1660simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1661 const Scop &S) {
1662 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1663 AssumptionContext = isl_set_gist_params(AssumptionContext, DomainParameters);
1664 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1665 return AssumptionContext;
1666}
1667
1668void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001669 // The parameter constraints of the iteration domains give us a set of
1670 // constraints that need to hold for all cases where at least a single
1671 // statement iteration is executed in the whole scop. We now simplify the
1672 // assumed context under the assumption that such constraints hold and at
1673 // least a single statement iteration is executed. For cases where no
1674 // statement instances are executed, the assumptions we have taken about
1675 // the executed code do not matter and can be changed.
1676 //
1677 // WARNING: This only holds if the assumptions we have taken do not reduce
1678 // the set of statement instances that are executed. Otherwise we
1679 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001680 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001681 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001682 // performed. In such a case, modifying the run-time conditions and
1683 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001684 // to not be executed.
1685 //
1686 // Example:
1687 //
1688 // When delinearizing the following code:
1689 //
1690 // for (long i = 0; i < 100; i++)
1691 // for (long j = 0; j < m; j++)
1692 // A[i+p][j] = 1.0;
1693 //
1694 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001695 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001696 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001697 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1698 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001699}
1700
Johannes Doerfertb164c792014-09-18 11:17:17 +00001701/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001702static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001703 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1704 isl_pw_multi_aff *MinPMA, *MaxPMA;
1705 isl_pw_aff *LastDimAff;
1706 isl_aff *OneAff;
1707 unsigned Pos;
1708
Johannes Doerfert9143d672014-09-27 11:02:39 +00001709 // Restrict the number of parameters involved in the access as the lexmin/
1710 // lexmax computation will take too long if this number is high.
1711 //
1712 // Experiments with a simple test case using an i7 4800MQ:
1713 //
1714 // #Parameters involved | Time (in sec)
1715 // 6 | 0.01
1716 // 7 | 0.04
1717 // 8 | 0.12
1718 // 9 | 0.40
1719 // 10 | 1.54
1720 // 11 | 6.78
1721 // 12 | 30.38
1722 //
1723 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1724 unsigned InvolvedParams = 0;
1725 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1726 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1727 InvolvedParams++;
1728
1729 if (InvolvedParams > RunTimeChecksMaxParameters) {
1730 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001731 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001732 }
1733 }
1734
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001735 Set = isl_set_remove_divs(Set);
1736
Johannes Doerfertb164c792014-09-18 11:17:17 +00001737 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1738 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1739
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001740 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1741 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1742
Johannes Doerfertb164c792014-09-18 11:17:17 +00001743 // Adjust the last dimension of the maximal access by one as we want to
1744 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1745 // we test during code generation might now point after the end of the
1746 // allocated array but we will never dereference it anyway.
1747 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1748 "Assumed at least one output dimension");
1749 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1750 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1751 OneAff = isl_aff_zero_on_domain(
1752 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1753 OneAff = isl_aff_add_constant_si(OneAff, 1);
1754 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1755 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1756
1757 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1758
1759 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001760 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001761}
1762
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001763static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1764 isl_set *Domain = MA->getStatement()->getDomain();
1765 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1766 return isl_set_reset_tuple_id(Domain);
1767}
1768
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001769/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1770static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001771 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001772 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001773
1774 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1775 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001776 Locations = isl_union_set_coalesce(Locations);
1777 Locations = isl_union_set_detect_equalities(Locations);
1778 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001779 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001780 isl_union_set_free(Locations);
1781 return Valid;
1782}
1783
Johannes Doerfert96425c22015-08-30 21:13:53 +00001784/// @brief Helper to treat non-affine regions and basic blocks the same.
1785///
1786///{
1787
1788/// @brief Return the block that is the representing block for @p RN.
1789static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1790 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1791 : RN->getNodeAs<BasicBlock>();
1792}
1793
1794/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001795static inline BasicBlock *
1796getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001797 if (RN->isSubRegion()) {
1798 assert(idx == 0);
1799 return RN->getNodeAs<Region>()->getExit();
1800 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001801 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001802}
1803
1804/// @brief Return the smallest loop surrounding @p RN.
1805static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1806 if (!RN->isSubRegion())
1807 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1808
1809 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1810 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1811 while (L && NonAffineSubRegion->contains(L))
1812 L = L->getParentLoop();
1813 return L;
1814}
1815
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001816static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1817 if (!RN->isSubRegion())
1818 return 1;
1819
1820 unsigned NumBlocks = 0;
1821 Region *R = RN->getNodeAs<Region>();
1822 for (auto BB : R->blocks()) {
1823 (void)BB;
1824 NumBlocks++;
1825 }
1826 return NumBlocks;
1827}
1828
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001829static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1830 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001831 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001832 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001833 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001834 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001835 return true;
1836 return false;
1837}
1838
Johannes Doerfert96425c22015-08-30 21:13:53 +00001839///}
1840
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001841static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1842 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001843 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001844 isl_id *DimId =
1845 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1846 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1847}
1848
Johannes Doerfert96425c22015-08-30 21:13:53 +00001849isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1850 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1851 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001852 return getDomainConditions(BB);
1853}
1854
1855isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1856 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001857 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001858}
1859
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001860void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001861
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001862 auto *EntryBB = R->getEntry();
1863 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1864 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001865
1866 Loop *L = LI.getLoopFor(EntryBB);
1867 while (LD-- >= 0) {
1868 S = addDomainDimId(S, LD + 1, L);
1869 L = L->getParentLoop();
1870 }
1871
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001872 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001873
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001874 if (SD.isNonAffineSubRegion(R, R))
1875 return;
1876
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001877 buildDomainsWithBranchConstraints(R);
1878 propagateDomainConstraints(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001879}
1880
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001881void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001882 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001883
1884 // To create the domain for each block in R we iterate over all blocks and
1885 // subregions in R and propagate the conditions under which the current region
1886 // element is executed. To this end we iterate in reverse post order over R as
1887 // it ensures that we first visit all predecessors of a region node (either a
1888 // basic block or a subregion) before we visit the region node itself.
1889 // Initially, only the domain for the SCoP region entry block is set and from
1890 // there we propagate the current domain to all successors, however we add the
1891 // condition that the successor is actually executed next.
1892 // As we are only interested in non-loop carried constraints here we can
1893 // simply skip loop back edges.
1894
1895 ReversePostOrderTraversal<Region *> RTraversal(R);
1896 for (auto *RN : RTraversal) {
1897
1898 // Recurse for affine subregions but go on for basic blocks and non-affine
1899 // subregions.
1900 if (RN->isSubRegion()) {
1901 Region *SubRegion = RN->getNodeAs<Region>();
1902 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001903 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001904 continue;
1905 }
1906 }
1907
Johannes Doerfertf5673802015-10-01 23:48:18 +00001908 // Error blocks are assumed not to be executed. Therefor they are not
1909 // checked properly in the ScopDetection. Any attempt to generate control
1910 // conditions from them might result in a crash. However, this is only true
1911 // for the first step of the domain generation (this function) where we
1912 // push the control conditions of a block to the successors. In the second
1913 // step (propagateDomainConstraints) we only receive domain constraints from
1914 // the predecessors and can therefor look at the domain of a error block.
1915 // That allows us to generate the assumptions needed for them not to be
1916 // executed at runtime.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001917 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001918 continue;
1919
Johannes Doerfert96425c22015-08-30 21:13:53 +00001920 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001921 TerminatorInst *TI = BB->getTerminator();
1922
Johannes Doerfertf5673802015-10-01 23:48:18 +00001923 isl_set *Domain = DomainMap.lookup(BB);
1924 if (!Domain) {
1925 DEBUG(dbgs() << "\tSkip: " << BB->getName()
1926 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001927 continue;
1928 }
1929
Johannes Doerfert96425c22015-08-30 21:13:53 +00001930 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001931
1932 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1933 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1934
1935 // Build the condition sets for the successor nodes of the current region
1936 // node. If it is a non-affine subregion we will always execute the single
1937 // exit node, hence the single entry node domain is the condition set. For
1938 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001939 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001940 if (RN->isSubRegion())
1941 ConditionSets.push_back(isl_set_copy(Domain));
1942 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001943 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001944
1945 // Now iterate over the successors and set their initial domain based on
1946 // their condition set. We skip back edges here and have to be careful when
1947 // we leave a loop not to keep constraints over a dimension that doesn't
1948 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001949 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00001950 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001951 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001952 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001953
1954 // Skip back edges.
1955 if (DT.dominates(SuccBB, BB)) {
1956 isl_set_free(CondSet);
1957 continue;
1958 }
1959
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001960 // Do not adjust the number of dimensions if we enter a boxed loop or are
1961 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001962 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001963 Region *SuccRegion = RI.getRegionFor(SuccBB);
Johannes Doerfert634909c2015-10-04 14:57:41 +00001964 if (SD.isNonAffineSubRegion(SuccRegion, &getRegion()))
1965 while (SuccBBLoop && SuccRegion->contains(SuccBBLoop))
1966 SuccBBLoop = SuccBBLoop->getParentLoop();
1967
1968 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001969
1970 // Check if the edge to SuccBB is a loop entry or exit edge. If so
1971 // adjust the dimensionality accordingly. Lastly, if we leave a loop
1972 // and enter a new one we need to drop the old constraints.
1973 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001974 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001975 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001976 CondSet = isl_set_project_out(CondSet, isl_dim_set,
1977 isl_set_n_dim(CondSet) - LoopDepthDiff,
1978 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001979 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001980 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001981 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001982 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001983 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001984 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001985 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
1986 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001987 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001988 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00001989 }
1990
1991 // Set the domain for the successor or merge it with an existing domain in
1992 // case there are multiple paths (without loop back edges) to the
1993 // successor block.
1994 isl_set *&SuccDomain = DomainMap[SuccBB];
1995 if (!SuccDomain)
1996 SuccDomain = CondSet;
1997 else
1998 SuccDomain = isl_set_union(SuccDomain, CondSet);
1999
2000 SuccDomain = isl_set_coalesce(SuccDomain);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002001 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2002 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002003 }
2004 }
2005}
2006
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002007/// @brief Return the domain for @p BB wrt @p DomainMap.
2008///
2009/// This helper function will lookup @p BB in @p DomainMap but also handle the
2010/// case where @p BB is contained in a non-affine subregion using the region
2011/// tree obtained by @p RI.
2012static __isl_give isl_set *
2013getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2014 RegionInfo &RI) {
2015 auto DIt = DomainMap.find(BB);
2016 if (DIt != DomainMap.end())
2017 return isl_set_copy(DIt->getSecond());
2018
2019 Region *R = RI.getRegionFor(BB);
2020 while (R->getEntry() == BB)
2021 R = R->getParent();
2022 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2023}
2024
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002025void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002026 // Iterate over the region R and propagate the domain constrains from the
2027 // predecessors to the current node. In contrast to the
2028 // buildDomainsWithBranchConstraints function, this one will pull the domain
2029 // information from the predecessors instead of pushing it to the successors.
2030 // Additionally, we assume the domains to be already present in the domain
2031 // map here. However, we iterate again in reverse post order so we know all
2032 // predecessors have been visited before a block or non-affine subregion is
2033 // visited.
2034
2035 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2036 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2037
2038 ReversePostOrderTraversal<Region *> RTraversal(R);
2039 for (auto *RN : RTraversal) {
2040
2041 // Recurse for affine subregions but go on for basic blocks and non-affine
2042 // subregions.
2043 if (RN->isSubRegion()) {
2044 Region *SubRegion = RN->getNodeAs<Region>();
2045 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002046 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002047 continue;
2048 }
2049 }
2050
Johannes Doerfertf5673802015-10-01 23:48:18 +00002051 // Get the domain for the current block and check if it was initialized or
2052 // not. The only way it was not is if this block is only reachable via error
2053 // blocks, thus will not be executed under the assumptions we make. Such
2054 // blocks have to be skipped as their predecessors might not have domains
2055 // either. It would not benefit us to compute the domain anyway, only the
2056 // domains of the error blocks that are reachable from non-error blocks
2057 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002058 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002059 isl_set *&Domain = DomainMap[BB];
2060 if (!Domain) {
2061 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2062 << ", it is only reachable from error blocks.\n");
2063 DomainMap.erase(BB);
2064 continue;
2065 }
2066 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2067
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002068 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2069 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2070
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002071 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2072 for (auto *PredBB : predecessors(BB)) {
2073
2074 // Skip backedges
2075 if (DT.dominates(BB, PredBB))
2076 continue;
2077
2078 isl_set *PredBBDom = nullptr;
2079
2080 // Handle the SCoP entry block with its outside predecessors.
2081 if (!getRegion().contains(PredBB))
2082 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2083
2084 if (!PredBBDom) {
2085 // Determine the loop depth of the predecessor and adjust its domain to
2086 // the domain of the current block. This can mean we have to:
2087 // o) Drop a dimension if this block is the exit of a loop, not the
2088 // header of a new loop and the predecessor was part of the loop.
2089 // o) Add an unconstrainted new dimension if this block is the header
2090 // of a loop and the predecessor is not part of it.
2091 // o) Drop the information about the innermost loop dimension when the
2092 // predecessor and the current block are surrounded by different
2093 // loops in the same depth.
2094 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2095 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2096 while (BoxedLoops.count(PredBBLoop))
2097 PredBBLoop = PredBBLoop->getParentLoop();
2098
2099 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002100 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002101 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002102 PredBBDom = isl_set_project_out(
2103 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2104 LoopDepthDiff);
2105 else if (PredBBLoopDepth < BBLoopDepth) {
2106 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002107 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002108 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2109 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002110 PredBBDom = isl_set_drop_constraints_involving_dims(
2111 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002112 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002113 }
2114
2115 PredDom = isl_set_union(PredDom, PredBBDom);
2116 }
2117
2118 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002119 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002120
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002121 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002122 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002123
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002124 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002125 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002126 IsOptimized = true;
2127 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2128 addAssumption(isl_set_complement(DomPar));
2129 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002130 }
2131}
2132
2133/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2134/// is incremented by one and all other dimensions are equal, e.g.,
2135/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2136/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2137static __isl_give isl_map *
2138createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2139 auto *MapSpace = isl_space_map_from_set(SetSpace);
2140 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2141 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2142 if (u != Dim)
2143 NextIterationMap =
2144 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2145 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2146 C = isl_constraint_set_constant_si(C, 1);
2147 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2148 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2149 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2150 return NextIterationMap;
2151}
2152
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002153void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002154 int LoopDepth = getRelativeLoopDepth(L);
2155 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002156
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002157 BasicBlock *HeaderBB = L->getHeader();
2158 assert(DomainMap.count(HeaderBB));
2159 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002160
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002161 isl_map *NextIterationMap =
2162 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002163
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002164 isl_set *UnionBackedgeCondition =
2165 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002166
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002167 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2168 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002169
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002170 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002171
2172 // If the latch is only reachable via error statements we skip it.
2173 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2174 if (!LatchBBDom)
2175 continue;
2176
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002177 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002178
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002179 TerminatorInst *TI = LatchBB->getTerminator();
2180 BranchInst *BI = dyn_cast<BranchInst>(TI);
2181 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002182 BackedgeCondition = isl_set_copy(LatchBBDom);
2183 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002184 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002185 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002186 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002187
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002188 // Free the non back edge condition set as we do not need it.
2189 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002190
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002191 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002192 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002193
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002194 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2195 assert(LatchLoopDepth >= LoopDepth);
2196 BackedgeCondition =
2197 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2198 LatchLoopDepth - LoopDepth);
2199 UnionBackedgeCondition =
2200 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002201 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002202
2203 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2204 for (int i = 0; i < LoopDepth; i++)
2205 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2206
2207 isl_set *UnionBackedgeConditionComplement =
2208 isl_set_complement(UnionBackedgeCondition);
2209 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2210 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2211 UnionBackedgeConditionComplement =
2212 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2213 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2214 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2215
2216 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2217 HeaderBBDom = Parts.second;
2218
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002219 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2220 // the bounded assumptions to the context as they are already implied by the
2221 // <nsw> tag.
2222 if (Affinator.hasNSWAddRecForLoop(L)) {
2223 isl_set_free(Parts.first);
2224 return;
2225 }
2226
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002227 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2228 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfert707a4062015-09-20 16:38:19 +00002229 addAssumption(BoundedCtx);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002230}
2231
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002232void Scop::buildAliasChecks(AliasAnalysis &AA) {
2233 if (!PollyUseRuntimeAliasChecks)
2234 return;
2235
2236 if (buildAliasGroups(AA))
2237 return;
2238
2239 // If a problem occurs while building the alias groups we need to delete
2240 // this SCoP and pretend it wasn't valid in the first place. To this end
2241 // we make the assumed context infeasible.
2242 addAssumption(isl_set_empty(getParamSpace()));
2243
2244 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2245 << " could not be created as the number of parameters involved "
2246 "is too high. The SCoP will be "
2247 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2248 "the maximal number of parameters but be advised that the "
2249 "compile time might increase exponentially.\n\n");
2250}
2251
Johannes Doerfert9143d672014-09-27 11:02:39 +00002252bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002253 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002254 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002255 // for all memory accesses inside the SCoP.
2256 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002257 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002258 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002259 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002260 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002261 // if their access domains intersect, otherwise they are in different
2262 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002263 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002264 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002265 // and maximal accesses to each array of a group in read only and non
2266 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002267 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2268
2269 AliasSetTracker AST(AA);
2270
2271 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002272 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002273 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002274
2275 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002276 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002277 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2278 isl_set_free(StmtDomain);
2279 if (StmtDomainEmpty)
2280 continue;
2281
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002282 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00002283 if (MA->isImplicit())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002284 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002285 if (!MA->isRead())
2286 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002287 Instruction *Acc = MA->getAccessInstruction();
2288 PtrToAcc[getPointerOperand(*Acc)] = MA;
2289 AST.add(Acc);
2290 }
2291 }
2292
2293 SmallVector<AliasGroupTy, 4> AliasGroups;
2294 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002295 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002296 continue;
2297 AliasGroupTy AG;
2298 for (auto PR : AS)
2299 AG.push_back(PtrToAcc[PR.getValue()]);
2300 assert(AG.size() > 1 &&
2301 "Alias groups should contain at least two accesses");
2302 AliasGroups.push_back(std::move(AG));
2303 }
2304
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002305 // Split the alias groups based on their domain.
2306 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2307 AliasGroupTy NewAG;
2308 AliasGroupTy &AG = AliasGroups[u];
2309 AliasGroupTy::iterator AGI = AG.begin();
2310 isl_set *AGDomain = getAccessDomain(*AGI);
2311 while (AGI != AG.end()) {
2312 MemoryAccess *MA = *AGI;
2313 isl_set *MADomain = getAccessDomain(MA);
2314 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2315 NewAG.push_back(MA);
2316 AGI = AG.erase(AGI);
2317 isl_set_free(MADomain);
2318 } else {
2319 AGDomain = isl_set_union(AGDomain, MADomain);
2320 AGI++;
2321 }
2322 }
2323 if (NewAG.size() > 1)
2324 AliasGroups.push_back(std::move(NewAG));
2325 isl_set_free(AGDomain);
2326 }
2327
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002328 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002329 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2330 for (AliasGroupTy &AG : AliasGroups) {
2331 NonReadOnlyBaseValues.clear();
2332 ReadOnlyPairs.clear();
2333
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002334 if (AG.size() < 2) {
2335 AG.clear();
2336 continue;
2337 }
2338
Johannes Doerfert13771732014-10-01 12:40:46 +00002339 for (auto II = AG.begin(); II != AG.end();) {
2340 Value *BaseAddr = (*II)->getBaseAddr();
2341 if (HasWriteAccess.count(BaseAddr)) {
2342 NonReadOnlyBaseValues.insert(BaseAddr);
2343 II++;
2344 } else {
2345 ReadOnlyPairs[BaseAddr].insert(*II);
2346 II = AG.erase(II);
2347 }
2348 }
2349
2350 // If we don't have read only pointers check if there are at least two
2351 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002352 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002353 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002354 continue;
2355 }
2356
2357 // If we don't have non read only pointers clear the alias group.
2358 if (NonReadOnlyBaseValues.empty()) {
2359 AG.clear();
2360 continue;
2361 }
2362
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002363 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002364 MinMaxAliasGroups.emplace_back();
2365 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2366 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2367 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2368 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002369
2370 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002371
2372 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002373 for (MemoryAccess *MA : AG)
2374 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002375
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002376 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2377 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002378
2379 // Bail out if the number of values we need to compare is too large.
2380 // This is important as the number of comparisions grows quadratically with
2381 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002382 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2383 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002384 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002385
2386 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002387 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002388 Accesses = isl_union_map_empty(getParamSpace());
2389
2390 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2391 for (MemoryAccess *MA : ReadOnlyPair.second)
2392 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2393
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002394 Valid =
2395 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002396
2397 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002398 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002399 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002400
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002401 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002402}
2403
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002404static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2405 Loop *L = LI.getLoopFor(R.getEntry());
2406 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2407}
2408
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002409static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2410 ScopDetection &SD) {
2411
2412 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2413
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002414 unsigned MinLD = INT_MAX, MaxLD = 0;
2415 for (BasicBlock *BB : R.blocks()) {
2416 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002417 if (!R.contains(L))
2418 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002419 if (BoxedLoops && BoxedLoops->count(L))
2420 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002421 unsigned LD = L->getLoopDepth();
2422 MinLD = std::min(MinLD, LD);
2423 MaxLD = std::max(MaxLD, LD);
2424 }
2425 }
2426
2427 // Handle the case that there is no loop in the SCoP first.
2428 if (MaxLD == 0)
2429 return 1;
2430
2431 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2432 assert(MaxLD >= MinLD &&
2433 "Maximal loop depth was smaller than mininaml loop depth?");
2434 return MaxLD - MinLD + 1;
2435}
2436
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002437Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002438 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002439 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002440 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2441 AccFuncMap(AccFuncMap), IsOptimized(false),
2442 HasSingleExitEdge(R.getExitingBlock()), MaxLoopDepth(MaxLoopDepth),
2443 IslCtx(Context), Context(nullptr), Affinator(this),
2444 AssumedContext(nullptr), BoundaryContext(nullptr), Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002445
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002446void Scop::init(AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002447 buildContext();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002448 buildInvariantEquivalenceClasses();
2449
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002450 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002451
Michael Krusecac948e2015-10-02 13:53:07 +00002452 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002453 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002454 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002455 if (Stmts.empty())
2456 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002457
Michael Krusecac948e2015-10-02 13:53:07 +00002458 // The ScopStmts now have enough information to initialize themselves.
2459 for (ScopStmt &Stmt : Stmts)
2460 Stmt.init();
2461
2462 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002463 Loop *L = getLoopSurroundingRegion(R, LI);
2464 LoopSchedules[L];
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002465 buildSchedule(&R, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002466 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002467
Tobias Grosser8286b832015-11-02 11:29:32 +00002468 if (isl_set_is_empty(AssumedContext))
2469 return;
2470
2471 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002472 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002473 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002474 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002475 buildBoundaryContext();
2476 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002477 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002478
2479 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002480 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002481}
2482
2483Scop::~Scop() {
2484 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002485 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002486 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002487 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002488
Johannes Doerfert96425c22015-08-30 21:13:53 +00002489 for (auto It : DomainMap)
2490 isl_set_free(It.second);
2491
Johannes Doerfertb164c792014-09-18 11:17:17 +00002492 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002493 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002494 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002495 isl_pw_multi_aff_free(MMA.first);
2496 isl_pw_multi_aff_free(MMA.second);
2497 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002498 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002499 isl_pw_multi_aff_free(MMA.first);
2500 isl_pw_multi_aff_free(MMA.second);
2501 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002502 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002503
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002504 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002505 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002506}
2507
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002508void Scop::updateAccessDimensionality() {
2509 for (auto &Stmt : *this)
2510 for (auto &Access : Stmt)
2511 Access->updateDimensionality();
2512}
2513
Michael Krusecac948e2015-10-02 13:53:07 +00002514void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002515 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2516 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002517 RegionNode *RN = Stmt.isRegionStmt()
2518 ? Stmt.getRegion()->getNode()
2519 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002520
Johannes Doerferteca9e892015-11-03 16:54:49 +00002521 bool RemoveStmt = StmtIt->isEmpty();
2522 if (!RemoveStmt)
2523 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2524 if (!RemoveStmt)
2525 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002526
Johannes Doerferteca9e892015-11-03 16:54:49 +00002527 // Remove read only statements only after invariant loop hoisting.
2528 if (!RemoveStmt && !RemoveIgnoredStmts) {
2529 bool OnlyRead = true;
2530 for (MemoryAccess *MA : Stmt) {
2531 if (MA->isRead())
2532 continue;
2533
2534 OnlyRead = false;
2535 break;
2536 }
2537
2538 RemoveStmt = OnlyRead;
2539 }
2540
2541 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002542 // Remove the statement because it is unnecessary.
2543 if (Stmt.isRegionStmt())
2544 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2545 StmtMap.erase(BB);
2546 else
2547 StmtMap.erase(Stmt.getBasicBlock());
2548
2549 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002550 continue;
2551 }
2552
Michael Krusecac948e2015-10-02 13:53:07 +00002553 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002554 }
2555}
2556
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002557const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2558 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2559 if (!LInst)
2560 return nullptr;
2561
2562 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2563 LInst = cast<LoadInst>(Rep);
2564
2565 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2566 for (auto &IAClass : InvariantEquivClasses)
2567 if (PointerSCEV == std::get<0>(IAClass))
2568 return &IAClass;
2569
2570 return nullptr;
2571}
2572
2573void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2574
2575 // Get the context under which the statement is executed.
2576 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2577 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2578 DomainCtx = isl_set_detect_equalities(DomainCtx);
2579 DomainCtx = isl_set_coalesce(DomainCtx);
2580
2581 // Project out all parameters that relate to loads in the statement. Otherwise
2582 // we could have cyclic dependences on the constraints under which the
2583 // hoisted loads are executed and we could not determine an order in which to
2584 // pre-load them. This happens because not only lower bounds are part of the
2585 // domain but also upper bounds.
2586 for (MemoryAccess *MA : InvMAs) {
2587 Instruction *AccInst = MA->getAccessInstruction();
2588 if (SE->isSCEVable(AccInst->getType())) {
2589 isl_id *ParamId = getIdForParam(SE->getSCEV(AccInst));
2590 if (ParamId) {
2591 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2592 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2593 }
2594 isl_id_free(ParamId);
2595 }
2596 }
2597
2598 for (MemoryAccess *MA : InvMAs) {
2599 // Check for another invariant access that accesses the same location as
2600 // MA and if found consolidate them. Otherwise create a new equivalence
2601 // class at the end of InvariantEquivClasses.
2602 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2603 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2604
2605 bool Consolidated = false;
2606 for (auto &IAClass : InvariantEquivClasses) {
2607 if (PointerSCEV != std::get<0>(IAClass))
2608 continue;
2609
2610 Consolidated = true;
2611
2612 // Add MA to the list of accesses that are in this class.
2613 auto &MAs = std::get<1>(IAClass);
2614 MAs.push_front(MA);
2615
2616 // Unify the execution context of the class and this statement.
2617 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
2618 IAClassDomainCtx = isl_set_coalesce(
2619 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2620 break;
2621 }
2622
2623 if (Consolidated)
2624 continue;
2625
2626 // If we did not consolidate MA, thus did not find an equivalence class
2627 // for it, we create a new one.
2628 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2629 isl_set_copy(DomainCtx));
2630 }
2631
2632 isl_set_free(DomainCtx);
2633}
2634
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002635void Scop::hoistInvariantLoads() {
2636 isl_union_map *Writes = getWrites();
2637 for (ScopStmt &Stmt : *this) {
2638
2639 // TODO: Loads that are not loop carried, hence are in a statement with
2640 // zero iterators, are by construction invariant, though we
Johannes Doerfert09e36972015-10-07 20:17:36 +00002641 // currently "hoist" them anyway. This is necessary because we allow
2642 // them to be treated as parameters (e.g., in conditions) and our code
2643 // generation would otherwise use the old value.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002644
Johannes Doerfert8930f482015-10-02 14:51:00 +00002645 BasicBlock *BB = Stmt.isBlockStmt() ? Stmt.getBasicBlock()
2646 : Stmt.getRegion()->getEntry();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002647 isl_set *Domain = Stmt.getDomain();
2648 MemoryAccessList InvMAs;
2649
2650 for (MemoryAccess *MA : Stmt) {
2651 if (MA->isImplicit() || MA->isWrite() || !MA->isAffine())
2652 continue;
2653
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002654 // Skip accesses that have an invariant base pointer which is defined but
2655 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2656 // returns a pointer that is used as a base address. However, as we want
2657 // to hoist indirect pointers, we allow the base pointer to be defined in
Johannes Doerfert654c3282015-10-21 22:14:57 +00002658 // the region if it is also a memory access. Each ScopArrayInfo object
2659 // that has a base pointer origin has a base pointer that is loaded and
2660 // that it is invariant, thus it will be hoisted too. However, if there is
Tobias Grosser27e19a02015-10-25 12:05:14 +00002661 // no base pointer origin we check that the base pointer is defined
Johannes Doerfert654c3282015-10-21 22:14:57 +00002662 // outside the region.
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002663 const ScopArrayInfo *SAI = MA->getScopArrayInfo();
Johannes Doerfert654c3282015-10-21 22:14:57 +00002664 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2665 SAI = BasePtrOriginSAI;
2666
2667 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2668 if (R.contains(BasePtrInst))
2669 continue;
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002670
Johannes Doerfert8930f482015-10-02 14:51:00 +00002671 // Skip accesses in non-affine subregions as they might not be executed
2672 // under the same condition as the entry of the non-affine subregion.
2673 if (BB != MA->getAccessInstruction()->getParent())
2674 continue;
2675
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002676 isl_map *AccessRelation = MA->getAccessRelation();
Johannes Doerfertb864c2c2015-10-18 19:50:18 +00002677
2678 // Skip accesses that have an empty access relation. These can be caused
2679 // by multiple offsets with a type cast in-between that cause the overall
2680 // byte offset to be not divisible by the new types sizes.
2681 if (isl_map_is_empty(AccessRelation)) {
2682 isl_map_free(AccessRelation);
2683 continue;
2684 }
2685
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002686 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2687 Stmt.getNumIterators())) {
2688 isl_map_free(AccessRelation);
2689 continue;
2690 }
2691
2692 AccessRelation =
2693 isl_map_intersect_domain(AccessRelation, isl_set_copy(Domain));
2694 isl_set *AccessRange = isl_map_range(AccessRelation);
2695
2696 isl_union_map *Written = isl_union_map_intersect_range(
2697 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2698 bool IsWritten = !isl_union_map_is_empty(Written);
2699 isl_union_map_free(Written);
2700
2701 if (IsWritten)
2702 continue;
2703
2704 InvMAs.push_front(MA);
2705 }
2706
2707 // We inserted invariant accesses always in the front but need them to be
2708 // sorted in a "natural order". The statements are already sorted in reverse
2709 // post order and that suffices for the accesses too. The reason we require
2710 // an order in the first place is the dependences between invariant loads
2711 // that can be caused by indirect loads.
2712 InvMAs.reverse();
2713
2714 // Transfer the memory access from the statement to the SCoP.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002715 Stmt.removeMemoryAccesses(InvMAs);
2716 addInvariantLoads(Stmt, InvMAs);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002717
2718 isl_set_free(Domain);
2719 }
2720 isl_union_map_free(Writes);
2721
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002722 if (!InvariantEquivClasses.empty())
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002723 IsOptimized = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00002724
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002725 auto &ScopRIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002726 // Check required invariant loads that were tagged during SCoP detection.
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002727 for (LoadInst *LI : ScopRIL) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00002728 assert(LI && getRegion().contains(LI));
2729 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
2730 if (Stmt && Stmt->lookupAccessesFor(LI) != nullptr) {
2731 DEBUG(dbgs() << "\n\nWARNING: Load (" << *LI
2732 << ") is required to be invariant but was not marked as "
2733 "such. SCoP for "
2734 << getRegion() << " will be dropped\n\n");
2735 addAssumption(isl_set_empty(getParamSpace()));
2736 return;
2737 }
2738 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002739}
2740
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002741const ScopArrayInfo *
2742Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Michael Kruse28468772015-09-14 15:45:33 +00002743 ArrayRef<const SCEV *> Sizes, bool IsPHI) {
Tobias Grosser92245222015-07-28 14:53:44 +00002744 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002745 if (!SAI) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002746 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
2747 this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002748 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002749 // In case of mismatching array sizes, we bail out by setting the run-time
2750 // context to false.
2751 if (!SAI->updateSizes(Sizes))
2752 addAssumption(isl_set_empty(getParamSpace()));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002753 }
Tobias Grosserab671442015-05-23 05:58:27 +00002754 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002755}
2756
Tobias Grosser92245222015-07-28 14:53:44 +00002757const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
2758 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002759 assert(SAI && "No ScopArrayInfo available for this base pointer");
2760 return SAI;
2761}
2762
Tobias Grosser74394f02013-01-14 22:40:23 +00002763std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002764std::string Scop::getAssumedContextStr() const {
2765 return stringFromIslObj(AssumedContext);
2766}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002767std::string Scop::getBoundaryContextStr() const {
2768 return stringFromIslObj(BoundaryContext);
2769}
Tobias Grosser75805372011-04-29 06:27:02 +00002770
2771std::string Scop::getNameStr() const {
2772 std::string ExitName, EntryName;
2773 raw_string_ostream ExitStr(ExitName);
2774 raw_string_ostream EntryStr(EntryName);
2775
Tobias Grosserf240b482014-01-09 10:42:15 +00002776 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002777 EntryStr.str();
2778
2779 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002780 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002781 ExitStr.str();
2782 } else
2783 ExitName = "FunctionExit";
2784
2785 return EntryName + "---" + ExitName;
2786}
2787
Tobias Grosser74394f02013-01-14 22:40:23 +00002788__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002789__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002790 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002791}
2792
Tobias Grossere86109f2013-10-29 21:05:49 +00002793__isl_give isl_set *Scop::getAssumedContext() const {
2794 return isl_set_copy(AssumedContext);
2795}
2796
Johannes Doerfert43788c52015-08-20 05:58:56 +00002797__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2798 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002799 RuntimeCheckContext =
2800 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2801 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002802 return RuntimeCheckContext;
2803}
2804
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002805bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002806 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002807 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002808 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2809 isl_set_free(RuntimeCheckContext);
2810 return IsFeasible;
2811}
2812
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002813void Scop::addAssumption(__isl_take isl_set *Set) {
2814 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002815 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002816}
2817
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002818__isl_give isl_set *Scop::getBoundaryContext() const {
2819 return isl_set_copy(BoundaryContext);
2820}
2821
Tobias Grosser75805372011-04-29 06:27:02 +00002822void Scop::printContext(raw_ostream &OS) const {
2823 OS << "Context:\n";
2824
2825 if (!Context) {
2826 OS.indent(4) << "n/a\n\n";
2827 return;
2828 }
2829
2830 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002831
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002832 OS.indent(4) << "Assumed Context:\n";
2833 if (!AssumedContext) {
2834 OS.indent(4) << "n/a\n\n";
2835 return;
2836 }
2837
2838 OS.indent(4) << getAssumedContextStr() << "\n";
2839
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002840 OS.indent(4) << "Boundary Context:\n";
2841 if (!BoundaryContext) {
2842 OS.indent(4) << "n/a\n\n";
2843 return;
2844 }
2845
2846 OS.indent(4) << getBoundaryContextStr() << "\n";
2847
Tobias Grosser083d3d32014-06-28 08:59:45 +00002848 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002849 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002850 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2851 }
Tobias Grosser75805372011-04-29 06:27:02 +00002852}
2853
Johannes Doerfertb164c792014-09-18 11:17:17 +00002854void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002855 int noOfGroups = 0;
2856 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002857 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002858 noOfGroups += 1;
2859 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002860 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002861 }
2862
Tobias Grosserbb853c22015-07-25 12:31:03 +00002863 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002864 if (MinMaxAliasGroups.empty()) {
2865 OS.indent(8) << "n/a\n";
2866 return;
2867 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002868
Tobias Grosserbb853c22015-07-25 12:31:03 +00002869 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002870
2871 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002872 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002873 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002874 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002875 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2876 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002877 }
2878 OS << " ]]\n";
2879 }
2880
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002881 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002882 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002883 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002884 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002885 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2886 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002887 }
2888 OS << " ]]\n";
2889 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002890 }
2891}
2892
Tobias Grosser75805372011-04-29 06:27:02 +00002893void Scop::printStatements(raw_ostream &OS) const {
2894 OS << "Statements {\n";
2895
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002896 for (const ScopStmt &Stmt : *this)
2897 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002898
2899 OS.indent(4) << "}\n";
2900}
2901
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002902void Scop::printArrayInfo(raw_ostream &OS) const {
2903 OS << "Arrays {\n";
2904
Tobias Grosserab671442015-05-23 05:58:27 +00002905 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002906 Array.second->print(OS);
2907
2908 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002909
2910 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2911
2912 for (auto &Array : arrays())
2913 Array.second->print(OS, /* SizeAsPwAff */ true);
2914
2915 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002916}
2917
Tobias Grosser75805372011-04-29 06:27:02 +00002918void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002919 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2920 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002921 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002922 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002923 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002924 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002925 const auto &MAs = std::get<1>(IAClass);
2926 if (MAs.empty()) {
2927 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002928 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002929 MAs.front()->print(OS);
2930 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002931 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002932 }
2933 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002934 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002935 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002936 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002937 printStatements(OS.indent(4));
2938}
2939
2940void Scop::dump() const { print(dbgs()); }
2941
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002942isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002943
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002944__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
2945 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002946}
2947
Tobias Grosser808cd692015-07-14 09:33:13 +00002948__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002949 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002950
Tobias Grosser808cd692015-07-14 09:33:13 +00002951 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002952 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002953
2954 return Domain;
2955}
2956
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002957__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002958 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002959
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002960 for (ScopStmt &Stmt : *this) {
2961 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002962 if (!MA->isMustWrite())
2963 continue;
2964
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002965 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002966 isl_map *AccessDomain = MA->getAccessRelation();
2967 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2968 Write = isl_union_map_add_map(Write, AccessDomain);
2969 }
2970 }
2971 return isl_union_map_coalesce(Write);
2972}
2973
2974__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002975 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002976
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002977 for (ScopStmt &Stmt : *this) {
2978 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002979 if (!MA->isMayWrite())
2980 continue;
2981
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002982 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002983 isl_map *AccessDomain = MA->getAccessRelation();
2984 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2985 Write = isl_union_map_add_map(Write, AccessDomain);
2986 }
2987 }
2988 return isl_union_map_coalesce(Write);
2989}
2990
Tobias Grosser37eb4222014-02-20 21:43:54 +00002991__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002992 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002993
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002994 for (ScopStmt &Stmt : *this) {
2995 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002996 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002997 continue;
2998
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002999 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00003000 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00003001 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3002 Write = isl_union_map_add_map(Write, AccessDomain);
3003 }
3004 }
3005 return isl_union_map_coalesce(Write);
3006}
3007
3008__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003009 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003010
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003011 for (ScopStmt &Stmt : *this) {
3012 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00003013 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00003014 continue;
3015
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003016 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00003017 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00003018
3019 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3020 Read = isl_union_map_add_map(Read, AccessDomain);
3021 }
3022 }
3023 return isl_union_map_coalesce(Read);
3024}
3025
Tobias Grosser808cd692015-07-14 09:33:13 +00003026__isl_give isl_union_map *Scop::getSchedule() const {
3027 auto Tree = getScheduleTree();
3028 auto S = isl_schedule_get_map(Tree);
3029 isl_schedule_free(Tree);
3030 return S;
3031}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003032
Tobias Grosser808cd692015-07-14 09:33:13 +00003033__isl_give isl_schedule *Scop::getScheduleTree() const {
3034 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3035 getDomains());
3036}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003037
Tobias Grosser808cd692015-07-14 09:33:13 +00003038void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3039 auto *S = isl_schedule_from_domain(getDomains());
3040 S = isl_schedule_insert_partial_schedule(
3041 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3042 isl_schedule_free(Schedule);
3043 Schedule = S;
3044}
3045
3046void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3047 isl_schedule_free(Schedule);
3048 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003049}
3050
3051bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3052 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003053 for (ScopStmt &Stmt : *this) {
3054 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003055 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3056 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3057
3058 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3059 isl_union_set_free(StmtDomain);
3060 isl_union_set_free(NewStmtDomain);
3061 continue;
3062 }
3063
3064 Changed = true;
3065
3066 isl_union_set_free(StmtDomain);
3067 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3068
3069 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003070 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003071 isl_union_set_free(NewStmtDomain);
3072 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003073 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003074 }
3075 isl_union_set_free(Domain);
3076 return Changed;
3077}
3078
Tobias Grosser75805372011-04-29 06:27:02 +00003079ScalarEvolution *Scop::getSE() const { return SE; }
3080
Johannes Doerfertf5673802015-10-01 23:48:18 +00003081bool Scop::isIgnored(RegionNode *RN) {
3082 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser75805372011-04-29 06:27:02 +00003083
Johannes Doerfertf5673802015-10-01 23:48:18 +00003084 // Check if there are accesses contained.
3085 bool ContainsAccesses = false;
3086 if (!RN->isSubRegion())
3087 ContainsAccesses = getAccessFunctions(BB);
3088 else
3089 for (BasicBlock *RBB : RN->getNodeAs<Region>()->blocks())
3090 ContainsAccesses |= (getAccessFunctions(RBB) != nullptr);
3091 if (!ContainsAccesses)
3092 return true;
3093
3094 // Check for reachability via non-error blocks.
3095 if (!DomainMap.count(BB))
3096 return true;
3097
3098 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003099 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003100 return true;
3101
3102 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003103}
3104
Tobias Grosser808cd692015-07-14 09:33:13 +00003105struct MapToDimensionDataTy {
3106 int N;
3107 isl_union_pw_multi_aff *Res;
3108};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003109
Tobias Grosser808cd692015-07-14 09:33:13 +00003110// @brief Create a function that maps the elements of 'Set' to its N-th
3111// dimension.
3112//
3113// The result is added to 'User->Res'.
3114//
3115// @param Set The input set.
3116// @param N The dimension to map to.
3117//
3118// @returns Zero if no error occurred, non-zero otherwise.
3119static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3120 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3121 int Dim;
3122 isl_space *Space;
3123 isl_pw_multi_aff *PMA;
3124
3125 Dim = isl_set_dim(Set, isl_dim_set);
3126 Space = isl_set_get_space(Set);
3127 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3128 Dim - Data->N);
3129 if (Data->N > 1)
3130 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3131 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3132
3133 isl_set_free(Set);
3134
3135 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003136}
3137
Tobias Grosser808cd692015-07-14 09:33:13 +00003138// @brief Create a function that maps the elements of Domain to their Nth
3139// dimension.
3140//
3141// @param Domain The set of elements to map.
3142// @param N The dimension to map to.
3143static __isl_give isl_multi_union_pw_aff *
3144mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003145 if (N <= 0 || isl_union_set_is_empty(Domain)) {
3146 isl_union_set_free(Domain);
3147 return nullptr;
3148 }
3149
Tobias Grosser808cd692015-07-14 09:33:13 +00003150 struct MapToDimensionDataTy Data;
3151 isl_space *Space;
3152
3153 Space = isl_union_set_get_space(Domain);
3154 Data.N = N;
3155 Data.Res = isl_union_pw_multi_aff_empty(Space);
3156 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
3157 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
3158
3159 isl_union_set_free(Domain);
3160 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3161}
3162
Michael Kruse9d080092015-09-11 21:41:48 +00003163ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003164 ScopStmt *Stmt;
3165 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003166 Stmts.emplace_back(*this, *BB);
Tobias Grosser808cd692015-07-14 09:33:13 +00003167 Stmt = &Stmts.back();
3168 StmtMap[BB] = Stmt;
3169 } else {
3170 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003171 Stmts.emplace_back(*this, *R);
Tobias Grosser808cd692015-07-14 09:33:13 +00003172 Stmt = &Stmts.back();
3173 for (BasicBlock *BB : R->blocks())
3174 StmtMap[BB] = Stmt;
3175 }
3176 return Stmt;
3177}
3178
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003179void Scop::buildSchedule(
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003180 Region *R,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003181 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003182
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003183 if (SD.isNonAffineSubRegion(R, &getRegion())) {
Johannes Doerfertc6987c12015-09-26 13:41:43 +00003184 Loop *L = getLoopSurroundingRegion(*R, LI);
3185 auto &LSchedulePair = LoopSchedules[L];
Michael Krusecac948e2015-10-02 13:53:07 +00003186 ScopStmt *Stmt = getStmtForBasicBlock(R->getEntry());
Michael Kruseafe06702015-10-02 16:33:27 +00003187 isl_set *Domain = Stmt->getDomain();
Michael Krusecac948e2015-10-02 13:53:07 +00003188 auto *UDomain = isl_union_set_from_set(Domain);
3189 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003190 LSchedulePair.first = StmtSchedule;
3191 return;
3192 }
3193
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003194 ReversePostOrderTraversal<Region *> RTraversal(R);
3195 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00003196
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003197 if (RN->isSubRegion()) {
3198 Region *SubRegion = RN->getNodeAs<Region>();
3199 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003200 buildSchedule(SubRegion, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003201 continue;
3202 }
Tobias Grosser75805372011-04-29 06:27:02 +00003203 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003204
3205 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert30c22652015-10-18 21:17:11 +00003206 if (!getRegion().contains(L))
3207 L = getLoopSurroundingRegion(getRegion(), LI);
3208
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003209 int LD = getRelativeLoopDepth(L);
3210 auto &LSchedulePair = LoopSchedules[L];
3211 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3212
Michael Krusecac948e2015-10-02 13:53:07 +00003213 BasicBlock *BB = getRegionNodeBasicBlock(RN);
3214 ScopStmt *Stmt = getStmtForBasicBlock(BB);
3215 if (Stmt) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003216 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3217 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3218 LSchedulePair.first =
3219 combineInSequence(LSchedulePair.first, StmtSchedule);
3220 }
3221
3222 unsigned NumVisited = LSchedulePair.second;
3223 while (L && NumVisited == L->getNumBlocks()) {
3224 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
3225 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
3226 LSchedulePair.first =
3227 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
3228
3229 auto *PL = L->getParentLoop();
Johannes Doerfertdca28372015-11-03 00:28:07 +00003230
3231 // Either we have a proper loop and we also build a schedule for the
3232 // parent loop or we have a infinite loop that does not have a proper
3233 // parent loop. In the former case this conditional will be skipped, in
3234 // the latter case however we will break here as we do not build a domain
3235 // nor a schedule for a infinite loop.
3236 assert(LoopSchedules.count(PL) || LSchedulePair.first == nullptr);
3237 if (!LoopSchedules.count(PL))
3238 break;
3239
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003240 auto &PSchedulePair = LoopSchedules[PL];
3241 PSchedulePair.first =
3242 combineInSequence(PSchedulePair.first, LSchedulePair.first);
3243 PSchedulePair.second += NumVisited;
3244
3245 L = PL;
3246 NumVisited = PSchedulePair.second;
3247 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003248 }
Tobias Grosser75805372011-04-29 06:27:02 +00003249}
3250
Johannes Doerfert7c494212014-10-31 23:13:39 +00003251ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003252 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003253 if (StmtMapIt == StmtMap.end())
3254 return nullptr;
3255 return StmtMapIt->second;
3256}
3257
Johannes Doerfert96425c22015-08-30 21:13:53 +00003258int Scop::getRelativeLoopDepth(const Loop *L) const {
3259 Loop *OuterLoop =
3260 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3261 if (!OuterLoop)
3262 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003263 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3264}
3265
Michael Krused868b5d2015-09-10 15:25:24 +00003266void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003267 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003268
3269 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3270 // true, are not modeled as ordinary PHI nodes as they are not part of the
3271 // region. However, we model the operands in the predecessor blocks that are
3272 // part of the region as regular scalar accesses.
3273
3274 // If we can synthesize a PHI we can skip it, however only if it is in
3275 // the region. If it is not it can only be in the exit block of the region.
3276 // In this case we model the operands but not the PHI itself.
3277 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3278 return;
3279
3280 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3281 // detection. Hence, the PHI is a load of a new memory location in which the
3282 // incoming value was written at the end of the incoming basic block.
3283 bool OnlyNonAffineSubRegionOperands = true;
3284 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3285 Value *Op = PHI->getIncomingValue(u);
3286 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3287
3288 // Do not build scalar dependences inside a non-affine subregion.
3289 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3290 continue;
3291
3292 OnlyNonAffineSubRegionOperands = false;
3293
3294 if (!R.contains(OpBB))
3295 continue;
3296
3297 Instruction *OpI = dyn_cast<Instruction>(Op);
3298 if (OpI) {
3299 BasicBlock *OpIBB = OpI->getParent();
3300 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3301 // we have to insert a scalar dependence from the definition of OpI to
3302 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003303 if (scop->getStmtForBasicBlock(OpIBB) !=
3304 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003305 addScalarReadAccess(OpI, PHI, OpBB);
3306 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003307 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003308 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003309 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003310 }
3311
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003312 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003313 }
3314
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003315 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3316 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003317 }
3318}
3319
Michael Krused868b5d2015-09-10 15:25:24 +00003320bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3321 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003322 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3323 if (isIgnoredIntrinsic(Inst))
3324 return false;
3325
3326 bool AnyCrossStmtUse = false;
3327 BasicBlock *ParentBB = Inst->getParent();
3328
3329 for (User *U : Inst->users()) {
3330 Instruction *UI = dyn_cast<Instruction>(U);
3331
3332 // Ignore the strange user
3333 if (UI == 0)
3334 continue;
3335
3336 BasicBlock *UseParent = UI->getParent();
3337
Tobias Grosserbaffa092015-10-24 20:55:27 +00003338 // Ignore basic block local uses. A value that is defined in a scop, but
3339 // used in a PHI node in the same basic block does not count as basic block
3340 // local, as for such cases a control flow edge is passed between definition
3341 // and use.
3342 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003343 continue;
3344
3345 // Do not build scalar dependences inside a non-affine subregion.
3346 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3347 continue;
3348
Michael Kruse01cb3792015-10-17 21:07:08 +00003349 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003350 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003351 //
3352 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003353 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3354 // the control flow a different value will be assigned to the PHI node. In
3355 // case this is the case, there is no need to create an additional normal
3356 // scalar dependence. Hence, bail out before we register an "out-of-region"
3357 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003358 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3359 !R->getExitingBlock())
3360 continue;
3361
Michael Kruse7bf39442015-09-10 12:46:52 +00003362 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003363 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003364 AnyCrossStmtUse = true;
3365 continue;
3366 }
3367
Tobias Grosserbaffa092015-10-24 20:55:27 +00003368 // Uses by PHI nodes in the entry node count as external uses in case the
3369 // use is through an incoming block that is itself not contained in the
3370 // region.
3371 if (R->getEntry() == UseParent) {
3372 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3373 bool ExternalUse = false;
3374 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3375 if (PHI->getIncomingValue(i) == Inst &&
3376 !R->contains(PHI->getIncomingBlock(i))) {
3377 ExternalUse = true;
3378 break;
3379 }
3380 }
3381
3382 if (ExternalUse) {
3383 AnyCrossStmtUse = true;
3384 continue;
3385 }
3386 }
3387 }
3388
Michael Kruse7bf39442015-09-10 12:46:52 +00003389 // If the instruction can be synthesized and the user is in the region
3390 // we do not need to add scalar dependences.
3391 if (canSynthesizeInst)
3392 continue;
3393
3394 // No need to translate these scalar dependences into polyhedral form,
3395 // because synthesizable scalars can be generated by the code generator.
3396 if (canSynthesize(UI, LI, SE, R))
3397 continue;
3398
3399 // Skip PHI nodes in the region as they handle their operands on their own.
3400 if (isa<PHINode>(UI))
3401 continue;
3402
3403 // Now U is used in another statement.
3404 AnyCrossStmtUse = true;
3405
3406 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003407 // Use the def instruction as base address of the MemoryAccess, so that it
3408 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003409 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003410 }
3411
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003412 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003413 for (Value *Op : Inst->operands()) {
3414 if (canSynthesize(Op, LI, SE, R))
3415 continue;
3416
3417 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3418 if (R->contains(OpInst))
3419 continue;
3420
3421 if (isa<Constant>(Op))
3422 continue;
3423
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003424 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003425 }
3426 }
3427
3428 return AnyCrossStmtUse;
3429}
3430
3431extern MapInsnToMemAcc InsnToMemAcc;
3432
Michael Krusee2bccbb2015-09-18 19:59:43 +00003433void ScopInfo::buildMemoryAccess(
3434 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003435 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3436 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003437 unsigned Size;
3438 Type *SizeType;
3439 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003440 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003441
3442 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3443 SizeType = Load->getType();
3444 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003445 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003446 Val = Load;
3447 } else {
3448 StoreInst *Store = cast<StoreInst>(Inst);
3449 SizeType = Store->getValueOperand()->getType();
3450 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003451 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003452 Val = Store->getValueOperand();
3453 }
3454
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003455 auto Address = getPointerOperand(*Inst);
3456
3457 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003458 const SCEVUnknown *BasePointer =
3459 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3460
3461 assert(BasePointer && "Could not find base pointer");
3462 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3463
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003464 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3465 auto NewAddress = Address;
3466 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3467 auto Src = BitCast->getOperand(0);
3468 auto SrcTy = Src->getType();
3469 auto DstTy = BitCast->getType();
3470 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3471 NewAddress = Src;
3472 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003473
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003474 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3475 std::vector<const SCEV *> Subscripts;
3476 std::vector<int> Sizes;
3477 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3478 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003479
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003480 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003481
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003482 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003483 for (auto Subscript : Subscripts) {
3484 InvariantLoadsSetTy AccessILS;
3485 AllAffineSubcripts =
3486 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3487
3488 for (LoadInst *LInst : AccessILS)
3489 if (!ScopRIL.count(LInst))
3490 AllAffineSubcripts = false;
3491
3492 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003493 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003494 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003495
3496 if (AllAffineSubcripts && Sizes.size() > 0) {
3497 for (auto V : Sizes)
3498 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3499 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003500 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003501 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003502
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003503 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3504 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003505 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003506 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003507 }
3508 }
3509
Michael Kruse7bf39442015-09-10 12:46:52 +00003510 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003511 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003512 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3513 AccItr->second.DelinearizedSubscripts,
3514 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003515 return;
3516 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003517
3518 // Check if the access depends on a loop contained in a non-affine subregion.
3519 bool isVariantInNonAffineLoop = false;
3520 if (BoxedLoops) {
3521 SetVector<const Loop *> Loops;
3522 findLoops(AccessFunction, Loops);
3523 for (const Loop *L : Loops)
3524 if (BoxedLoops->count(L))
3525 isVariantInNonAffineLoop = true;
3526 }
3527
Johannes Doerfert09e36972015-10-07 20:17:36 +00003528 InvariantLoadsSetTy AccessILS;
3529 bool IsAffine =
3530 !isVariantInNonAffineLoop &&
3531 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3532
3533 for (LoadInst *LInst : AccessILS)
3534 if (!ScopRIL.count(LInst))
3535 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003536
Michael Krusecaac2b62015-09-26 15:51:44 +00003537 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003538 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003539 const SCEV *SizeSCEV =
3540 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003541
Michael Krusee2bccbb2015-09-18 19:59:43 +00003542 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3543 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003544
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003545 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3546 ArrayRef<const SCEV *>(AccessFunction),
3547 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003548}
3549
Michael Krused868b5d2015-09-10 15:25:24 +00003550void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003551
3552 if (SD->isNonAffineSubRegion(&SR, &R)) {
3553 for (BasicBlock *BB : SR.blocks())
3554 buildAccessFunctions(R, *BB, &SR);
3555 return;
3556 }
3557
3558 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3559 if (I->isSubRegion())
3560 buildAccessFunctions(R, *I->getNodeAs<Region>());
3561 else
3562 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3563}
3564
Michael Krusecac948e2015-10-02 13:53:07 +00003565void ScopInfo::buildStmts(Region &SR) {
3566 Region *R = getRegion();
3567
3568 if (SD->isNonAffineSubRegion(&SR, R)) {
3569 scop->addScopStmt(nullptr, &SR);
3570 return;
3571 }
3572
3573 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3574 if (I->isSubRegion())
3575 buildStmts(*I->getNodeAs<Region>());
3576 else
3577 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3578}
3579
Michael Krused868b5d2015-09-10 15:25:24 +00003580void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3581 Region *NonAffineSubRegion,
3582 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003583 Loop *L = LI->getLoopFor(&BB);
3584
3585 // The set of loops contained in non-affine subregions that are part of R.
3586 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3587
Johannes Doerfert09e36972015-10-07 20:17:36 +00003588 // The set of loads that are required to be invariant.
3589 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3590
Michael Kruse7bf39442015-09-10 12:46:52 +00003591 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
3592 Instruction *Inst = I;
3593
3594 PHINode *PHI = dyn_cast<PHINode>(Inst);
3595 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003596 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003597
3598 // For the exit block we stop modeling after the last PHI node.
3599 if (!PHI && IsExitBlock)
3600 break;
3601
Johannes Doerfert09e36972015-10-07 20:17:36 +00003602 // TODO: At this point we only know that elements of ScopRIL have to be
3603 // invariant and will be hoisted for the SCoP to be processed. Though,
3604 // there might be other invariant accesses that will be hoisted and
3605 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003606 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003607 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003608
3609 if (isIgnoredIntrinsic(Inst))
3610 continue;
3611
Johannes Doerfert09e36972015-10-07 20:17:36 +00003612 // Do not build scalar dependences for required invariant loads as we will
3613 // hoist them later on anyway or drop the SCoP if we cannot.
3614 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3615 continue;
3616
Michael Kruse7bf39442015-09-10 12:46:52 +00003617 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003618 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003619 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003620 }
3621 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003622}
Michael Kruse7bf39442015-09-10 12:46:52 +00003623
Michael Kruse2d0ece92015-09-24 11:41:21 +00003624void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3625 MemoryAccess::AccessType Type,
3626 Value *BaseAddress, unsigned ElemBytes,
3627 bool Affine, Value *AccessValue,
3628 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003629 ArrayRef<const SCEV *> Sizes,
3630 MemoryAccess::AccessOrigin Origin) {
Michael Krusecac948e2015-10-02 13:53:07 +00003631 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3632
3633 // Do not create a memory access for anything not in the SCoP. It would be
3634 // ignored anyway.
3635 if (!Stmt)
3636 return;
3637
Michael Krusee2bccbb2015-09-18 19:59:43 +00003638 AccFuncSetType &AccList = AccFuncMap[BB];
3639 size_t Identifier = AccList.size();
Michael Kruse7bf39442015-09-10 12:46:52 +00003640
Michael Krusee2bccbb2015-09-18 19:59:43 +00003641 Value *BaseAddr = BaseAddress;
3642 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3643
3644 std::string IdName = "__polly_array_ref_" + std::to_string(Identifier);
3645 isl_id *Id = isl_id_alloc(ctx, IdName.c_str(), nullptr);
3646
Michael Krusecac948e2015-10-02 13:53:07 +00003647 bool isApproximated =
3648 Stmt->isRegionStmt() && (Stmt->getRegion()->getEntry() != BB);
3649 if (isApproximated && Type == MemoryAccess::MUST_WRITE)
3650 Type = MemoryAccess::MAY_WRITE;
3651
3652 AccList.emplace_back(Stmt, Inst, Id, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003653 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003654 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003655}
3656
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003657void ScopInfo::addExplicitAccess(
3658 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
3659 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
3660 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
3661 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3662 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3663 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003664 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
3665 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003666}
3667void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3668 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3669 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003670 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003671}
3672void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3673 assert(!isa<PHINode>(User));
3674 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3675 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003676 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003677}
3678void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3679 BasicBlock *UserBB) {
3680 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003681 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3682 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003683}
3684void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3685 Value *IncomingValue, bool IsExitBlock) {
3686 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3687 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3688 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003689 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003690}
3691void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3692 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003693 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3694 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003695}
3696
Michael Kruse76e924d2015-09-30 09:16:07 +00003697void ScopInfo::buildScop(Region &R, DominatorTree &DT) {
Michael Kruse9d080092015-09-11 21:41:48 +00003698 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003699 scop = new Scop(R, AccFuncMap, *SD, *SE, DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003700
Michael Krusecac948e2015-10-02 13:53:07 +00003701 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003702 buildAccessFunctions(R, R);
3703
3704 // In case the region does not have an exiting block we will later (during
3705 // code generation) split the exit block. This will move potential PHI nodes
3706 // from the current exit block into the new region exiting block. Hence, PHI
3707 // nodes that are at this point not part of the region will be.
3708 // To handle these PHI nodes later we will now model their operands as scalar
3709 // accesses. Note that we do not model anything in the exit block if we have
3710 // an exiting block in the region, as there will not be any splitting later.
3711 if (!R.getExitingBlock())
3712 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3713
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003714 scop->init(*AA);
Michael Kruse7bf39442015-09-10 12:46:52 +00003715}
3716
Michael Krused868b5d2015-09-10 15:25:24 +00003717void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003718 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003719 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003720 return;
3721 }
3722
Michael Kruse9d080092015-09-11 21:41:48 +00003723 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003724}
3725
Michael Krused868b5d2015-09-10 15:25:24 +00003726void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003727 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003728 if (scop) {
3729 delete scop;
3730 scop = 0;
3731 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003732}
3733
3734//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003735ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003736 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003737 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003738}
3739
3740ScopInfo::~ScopInfo() {
3741 clear();
3742 isl_ctx_free(ctx);
3743}
3744
Tobias Grosser75805372011-04-29 06:27:02 +00003745void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00003746 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003747 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003748 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003749 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3750 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003751 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00003752 AU.setPreservesAll();
3753}
3754
3755bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003756 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003757
Michael Krused868b5d2015-09-10 15:25:24 +00003758 if (!SD->isMaxRegionInScop(*R))
3759 return false;
3760
3761 Function *F = R->getEntry()->getParent();
3762 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3763 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3764 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3765 TD = &F->getParent()->getDataLayout();
3766 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Krused868b5d2015-09-10 15:25:24 +00003767
Michael Kruse76e924d2015-09-30 09:16:07 +00003768 buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00003769
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003770 DEBUG(scop->print(dbgs()));
3771
Michael Kruseafe06702015-10-02 16:33:27 +00003772 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003773 delete scop;
3774 scop = nullptr;
3775 return false;
3776 }
3777
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003778 // Statistics.
3779 ++ScopFound;
3780 if (scop->getMaxLoopDepth() > 0)
3781 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00003782 return false;
3783}
3784
3785char ScopInfo::ID = 0;
3786
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003787Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3788
Tobias Grosser73600b82011-10-08 00:30:40 +00003789INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3790 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003791 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003792INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00003793INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003794INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003795INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003796INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003797INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003798INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3799 "Polly - Create polyhedral description of Scops", false,
3800 false)