blob: 319d0722dad6b16b8a3bbd93b13a3b1e4ab3b105 [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
Johannes Doerferta7686242015-11-08 19:12:05 +0000153 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(), false);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000154}
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,
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000644 AccessType Type, Value *BaseAddress,
645 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)
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000649 : Origin(Origin), AccType(Type), RedType(RT_NONE), Statement(Stmt),
Michael Krusecac948e2015-10-02 13:53:07 +0000650 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),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000654 NewAccessRelation(nullptr) {
655
656 std::string IdName = "__polly_array_ref";
657 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
658}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000659
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000660void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000661 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000662 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000663}
664
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000665const std::string MemoryAccess::getReductionOperatorStr() const {
666 return MemoryAccess::getReductionOperatorStr(getReductionType());
667}
668
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000669__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
670
Johannes Doerfertf6183392014-07-01 20:52:51 +0000671raw_ostream &polly::operator<<(raw_ostream &OS,
672 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000673 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000674 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000675 else
676 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000677 return OS;
678}
679
Tobias Grosser75805372011-04-29 06:27:02 +0000680void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000681 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000682 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000683 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000684 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000685 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000686 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000687 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000688 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000689 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000690 break;
691 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000692 OS << "[Reduction Type: " << getReductionType() << "] ";
Michael Kruse8d0b7342015-09-25 21:21:00 +0000693 OS << "[Scalar: " << isImplicit() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000694 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000695 if (hasNewAccessRelation())
696 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000697}
698
Tobias Grosser74394f02013-01-14 22:40:23 +0000699void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000700
701// Create a map in the size of the provided set domain, that maps from the
702// one element of the provided set domain to another element of the provided
703// set domain.
704// The mapping is limited to all points that are equal in all but the last
705// dimension and for which the last dimension of the input is strict smaller
706// than the last dimension of the output.
707//
708// getEqualAndLarger(set[i0, i1, ..., iX]):
709//
710// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
711// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
712//
Tobias Grosserf5338802011-10-06 00:03:35 +0000713static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000714 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000715 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000716 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000717
718 // Set all but the last dimension to be equal for the input and output
719 //
720 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
721 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000722 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000723 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000724
725 // Set the last dimension of the input to be strict smaller than the
726 // last dimension of the output.
727 //
728 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000729 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
730 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000731 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000732}
733
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000734__isl_give isl_set *
735MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000736 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000737 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000738 isl_space *Space = isl_space_range(isl_map_get_space(S));
739 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000740
Sebastian Popa00a0292012-12-18 07:46:06 +0000741 S = isl_map_reverse(S);
742 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000743
Sebastian Popa00a0292012-12-18 07:46:06 +0000744 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
745 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
746 NextScatt = isl_map_apply_domain(NextScatt, S);
747 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000748
Sebastian Popa00a0292012-12-18 07:46:06 +0000749 isl_set *Deltas = isl_map_deltas(NextScatt);
750 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000751}
752
Sebastian Popa00a0292012-12-18 07:46:06 +0000753bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000754 int StrideWidth) const {
755 isl_set *Stride, *StrideX;
756 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000757
Sebastian Popa00a0292012-12-18 07:46:06 +0000758 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000759 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000760 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
761 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
762 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
763 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000764 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000765
Tobias Grosser28dd4862012-01-24 16:42:16 +0000766 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000767 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000768
Tobias Grosser28dd4862012-01-24 16:42:16 +0000769 return IsStrideX;
770}
771
Sebastian Popa00a0292012-12-18 07:46:06 +0000772bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
773 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000774}
775
Sebastian Popa00a0292012-12-18 07:46:06 +0000776bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
777 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000778}
779
Tobias Grosser166c4222015-09-05 07:46:40 +0000780void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
781 isl_map_free(NewAccessRelation);
782 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000783}
Tobias Grosser75805372011-04-29 06:27:02 +0000784
785//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000786
Tobias Grosser808cd692015-07-14 09:33:13 +0000787isl_map *ScopStmt::getSchedule() const {
788 isl_set *Domain = getDomain();
789 if (isl_set_is_empty(Domain)) {
790 isl_set_free(Domain);
791 return isl_map_from_aff(
792 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
793 }
794 auto *Schedule = getParent()->getSchedule();
795 Schedule = isl_union_map_intersect_domain(
796 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
797 if (isl_union_map_is_empty(Schedule)) {
798 isl_set_free(Domain);
799 isl_union_map_free(Schedule);
800 return isl_map_from_aff(
801 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
802 }
803 auto *M = isl_map_from_union_map(Schedule);
804 M = isl_map_coalesce(M);
805 M = isl_map_gist_domain(M, Domain);
806 M = isl_map_coalesce(M);
807 return M;
808}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000809
Johannes Doerfert574182d2015-08-12 10:19:50 +0000810__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000811 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
812 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000813}
814
Tobias Grosser37eb4222014-02-20 21:43:54 +0000815void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
816 assert(isl_set_is_subset(NewDomain, Domain) &&
817 "New domain is not a subset of old domain!");
818 isl_set_free(Domain);
819 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000820}
821
Michael Krusecac948e2015-10-02 13:53:07 +0000822void ScopStmt::buildAccessRelations() {
823 for (MemoryAccess *Access : MemAccs) {
824 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000825
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000826 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Michael Krusecac948e2015-10-02 13:53:07 +0000827 Access->getBaseAddr(), ElementType, Access->Sizes, Access->isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000828
Michael Krusecac948e2015-10-02 13:53:07 +0000829 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000830 }
831}
832
Michael Krusecac948e2015-10-02 13:53:07 +0000833void ScopStmt::addAccess(MemoryAccess *Access) {
834 Instruction *AccessInst = Access->getAccessInstruction();
835
836 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
837 if (!MAL)
838 MAL = new MemoryAccessList();
839 MAL->emplace_front(Access);
840 MemAccs.push_back(MAL->front());
841}
842
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000843void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000844 for (MemoryAccess *MA : *this)
845 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000846
847 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000848}
849
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000850/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
851static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
852 void *User) {
853 isl_set **BoundedParts = static_cast<isl_set **>(User);
854 if (isl_basic_set_is_bounded(BSet))
855 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
856 else
857 isl_basic_set_free(BSet);
858 return isl_stat_ok;
859}
860
861/// @brief Return the bounded parts of @p S.
862static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
863 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
864 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
865 isl_set_free(S);
866 return BoundedParts;
867}
868
869/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
870///
871/// @returns A separation of @p S into first an unbounded then a bounded subset,
872/// both with regards to the dimension @p Dim.
873static std::pair<__isl_give isl_set *, __isl_give isl_set *>
874partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
875
876 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000877 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000878
879 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000880 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000881
882 // Remove dimensions that are greater than Dim as they are not interesting.
883 assert(NumDimsS >= Dim + 1);
884 OnlyDimS =
885 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
886
887 // Create artificial parametric upper bounds for dimensions smaller than Dim
888 // as we are not interested in them.
889 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
890 for (unsigned u = 0; u < Dim; u++) {
891 isl_constraint *C = isl_inequality_alloc(
892 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
893 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
894 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
895 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
896 }
897
898 // Collect all bounded parts of OnlyDimS.
899 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
900
901 // Create the dimensions greater than Dim again.
902 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
903 NumDimsS - Dim - 1);
904
905 // Remove the artificial upper bound parameters again.
906 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
907
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000908 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000909 return std::make_pair(UnboundedParts, BoundedParts);
910}
911
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000912/// @brief Set the dimension Ids from @p From in @p To.
913static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
914 __isl_take isl_set *To) {
915 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
916 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
917 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
918 }
919 return To;
920}
921
922/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000923static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000924 __isl_take isl_pw_aff *L,
925 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +0000926 switch (Pred) {
927 case ICmpInst::ICMP_EQ:
928 return isl_pw_aff_eq_set(L, R);
929 case ICmpInst::ICMP_NE:
930 return isl_pw_aff_ne_set(L, R);
931 case ICmpInst::ICMP_SLT:
932 return isl_pw_aff_lt_set(L, R);
933 case ICmpInst::ICMP_SLE:
934 return isl_pw_aff_le_set(L, R);
935 case ICmpInst::ICMP_SGT:
936 return isl_pw_aff_gt_set(L, R);
937 case ICmpInst::ICMP_SGE:
938 return isl_pw_aff_ge_set(L, R);
939 case ICmpInst::ICMP_ULT:
940 return isl_pw_aff_lt_set(L, R);
941 case ICmpInst::ICMP_UGT:
942 return isl_pw_aff_gt_set(L, R);
943 case ICmpInst::ICMP_ULE:
944 return isl_pw_aff_le_set(L, R);
945 case ICmpInst::ICMP_UGE:
946 return isl_pw_aff_ge_set(L, R);
947 default:
948 llvm_unreachable("Non integer predicate not supported");
949 }
950}
951
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000952/// @brief Create the conditions under which @p L @p Pred @p R is true.
953///
954/// Helper function that will make sure the dimensions of the result have the
955/// same isl_id's as the @p Domain.
956static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
957 __isl_take isl_pw_aff *L,
958 __isl_take isl_pw_aff *R,
959 __isl_keep isl_set *Domain) {
960 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
961 return setDimensionIds(Domain, ConsequenceCondSet);
962}
963
964/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000965///
966/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000967/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
968/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000969static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000970buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +0000971 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
972
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000973 Value *Condition = getConditionFromTerminator(SI);
974 assert(Condition && "No condition for switch");
975
976 ScalarEvolution &SE = *S.getSE();
977 BasicBlock *BB = SI->getParent();
978 isl_pw_aff *LHS, *RHS;
979 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
980
981 unsigned NumSuccessors = SI->getNumSuccessors();
982 ConditionSets.resize(NumSuccessors);
983 for (auto &Case : SI->cases()) {
984 unsigned Idx = Case.getSuccessorIndex();
985 ConstantInt *CaseValue = Case.getCaseValue();
986
987 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
988 isl_set *CaseConditionSet =
989 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
990 ConditionSets[Idx] = isl_set_coalesce(
991 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
992 }
993
994 assert(ConditionSets[0] == nullptr && "Default condition set was set");
995 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
996 for (unsigned u = 2; u < NumSuccessors; u++)
997 ConditionSetUnion =
998 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
999 ConditionSets[0] = setDimensionIds(
1000 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1001
1002 S.markAsOptimized();
1003 isl_pw_aff_free(LHS);
1004}
1005
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001006/// @brief Build the conditions sets for the branch condition @p Condition in
1007/// the @p Domain.
1008///
1009/// This will fill @p ConditionSets with the conditions under which control
1010/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1011/// have as many elements as @p TI has successors.
1012static void
1013buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1014 __isl_keep isl_set *Domain,
1015 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1016
1017 isl_set *ConsequenceCondSet = nullptr;
1018 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1019 if (CCond->isZero())
1020 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1021 else
1022 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1023 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1024 auto Opcode = BinOp->getOpcode();
1025 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1026
1027 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1028 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1029
1030 isl_set_free(ConditionSets.pop_back_val());
1031 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1032 isl_set_free(ConditionSets.pop_back_val());
1033 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1034
1035 if (Opcode == Instruction::And)
1036 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1037 else
1038 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1039 } else {
1040 auto *ICond = dyn_cast<ICmpInst>(Condition);
1041 assert(ICond &&
1042 "Condition of exiting branch was neither constant nor ICmp!");
1043
1044 ScalarEvolution &SE = *S.getSE();
1045 BasicBlock *BB = TI->getParent();
1046 isl_pw_aff *LHS, *RHS;
1047 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1048 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1049 ConsequenceCondSet =
1050 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1051 }
1052
1053 assert(ConsequenceCondSet);
1054 isl_set *AlternativeCondSet =
1055 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1056
1057 ConditionSets.push_back(isl_set_coalesce(
1058 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1059 ConditionSets.push_back(isl_set_coalesce(
1060 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1061}
1062
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001063/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1064///
1065/// This will fill @p ConditionSets with the conditions under which control
1066/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1067/// have as many elements as @p TI has successors.
1068static void
1069buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1070 __isl_keep isl_set *Domain,
1071 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1072
1073 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1074 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1075
1076 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1077
1078 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001079 ConditionSets.push_back(isl_set_copy(Domain));
1080 return;
1081 }
1082
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001083 Value *Condition = getConditionFromTerminator(TI);
1084 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001085
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001086 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001087}
1088
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001089void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001090 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001091
Tobias Grosser084d8f72012-05-29 09:29:44 +00001092 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1093
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001094 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001095 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001096}
1097
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001098void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001099 isl_ctx *Ctx = Parent.getIslCtx();
1100 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1101 Type *Ty = GEP->getPointerOperandType();
1102 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001103 ScopDetection &SD = Parent.getSD();
1104
1105 // The set of loads that are required to be invariant.
1106 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001107
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001108 std::vector<const SCEV *> Subscripts;
1109 std::vector<int> Sizes;
1110
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001111 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001112
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001113 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001114 Ty = PtrTy->getElementType();
1115 }
1116
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001117 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001118
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001119 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001120
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001121 for (size_t i = 0; i < Sizes.size(); i++) {
1122 auto Expr = Subscripts[i + IndexOffset];
1123 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001124
Johannes Doerfert09e36972015-10-07 20:17:36 +00001125 InvariantLoadsSetTy AccessILS;
1126 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1127 continue;
1128
1129 bool NonAffine = false;
1130 for (LoadInst *LInst : AccessILS)
1131 if (!ScopRIL.count(LInst))
1132 NonAffine = true;
1133
1134 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001135 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001136
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001137 isl_pw_aff *AccessOffset = getPwAff(Expr);
1138 AccessOffset =
1139 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001140
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001141 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1142 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001143
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001144 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1145 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1146 OutOfBound = isl_set_params(OutOfBound);
1147 isl_set *InBound = isl_set_complement(OutOfBound);
1148 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001149
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001150 // A => B == !A or B
1151 isl_set *InBoundIfExecuted =
1152 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001153
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001154 Parent.addAssumption(InBoundIfExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001155 }
1156
1157 isl_local_space_free(LSpace);
1158}
1159
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001160void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1161 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001162 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1163 deriveAssumptionsFromGEP(GEP);
1164}
1165
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001166void ScopStmt::collectSurroundingLoops() {
1167 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1168 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1169 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1170 isl_id_free(DimId);
1171 }
1172}
1173
Michael Kruse9d080092015-09-11 21:41:48 +00001174ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001175 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001176
Tobias Grosser16c44032015-07-09 07:31:45 +00001177 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001178}
1179
Michael Kruse9d080092015-09-11 21:41:48 +00001180ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001181 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001182
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001183 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001184}
1185
1186void ScopStmt::init() {
1187 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001188
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001189 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001190 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001191 buildAccessRelations();
1192
1193 if (BB) {
1194 deriveAssumptions(BB);
1195 } else {
1196 for (BasicBlock *Block : R->blocks()) {
1197 deriveAssumptions(Block);
1198 }
1199 }
1200
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001201 if (DetectReductions)
1202 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001203}
1204
Johannes Doerferte58a0122014-06-27 20:31:28 +00001205/// @brief Collect loads which might form a reduction chain with @p StoreMA
1206///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001207/// Check if the stored value for @p StoreMA is a binary operator with one or
1208/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001209/// used only once (by @p StoreMA) and its load operands are also used only
1210/// once, we have found a possible reduction chain. It starts at an operand
1211/// load and includes the binary operator and @p StoreMA.
1212///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001213/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001214/// escape this block or into any other store except @p StoreMA.
1215void ScopStmt::collectCandiateReductionLoads(
1216 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1217 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1218 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001219 return;
1220
1221 // Skip if there is not one binary operator between the load and the store
1222 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001223 if (!BinOp)
1224 return;
1225
1226 // Skip if the binary operators has multiple uses
1227 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001228 return;
1229
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001230 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001231 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1232 return;
1233
Johannes Doerfert9890a052014-07-01 00:32:29 +00001234 // Skip if the binary operator is outside the current SCoP
1235 if (BinOp->getParent() != Store->getParent())
1236 return;
1237
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001238 // Skip if it is a multiplicative reduction and we disabled them
1239 if (DisableMultiplicativeReductions &&
1240 (BinOp->getOpcode() == Instruction::Mul ||
1241 BinOp->getOpcode() == Instruction::FMul))
1242 return;
1243
Johannes Doerferte58a0122014-06-27 20:31:28 +00001244 // Check the binary operator operands for a candidate load
1245 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1246 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1247 if (!PossibleLoad0 && !PossibleLoad1)
1248 return;
1249
1250 // A load is only a candidate if it cannot escape (thus has only this use)
1251 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001252 if (PossibleLoad0->getParent() == Store->getParent())
1253 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001254 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001255 if (PossibleLoad1->getParent() == Store->getParent())
1256 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001257}
1258
1259/// @brief Check for reductions in this ScopStmt
1260///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001261/// Iterate over all store memory accesses and check for valid binary reduction
1262/// like chains. For all candidates we check if they have the same base address
1263/// and there are no other accesses which overlap with them. The base address
1264/// check rules out impossible reductions candidates early. The overlap check,
1265/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001266/// guarantees that none of the intermediate results will escape during
1267/// execution of the loop nest. We basically check here that no other memory
1268/// access can access the same memory as the potential reduction.
1269void ScopStmt::checkForReductions() {
1270 SmallVector<MemoryAccess *, 2> Loads;
1271 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1272
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001273 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001274 // stores and collecting possible reduction loads.
1275 for (MemoryAccess *StoreMA : MemAccs) {
1276 if (StoreMA->isRead())
1277 continue;
1278
1279 Loads.clear();
1280 collectCandiateReductionLoads(StoreMA, Loads);
1281 for (MemoryAccess *LoadMA : Loads)
1282 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1283 }
1284
1285 // Then check each possible candidate pair.
1286 for (const auto &CandidatePair : Candidates) {
1287 bool Valid = true;
1288 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1289 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1290
1291 // Skip those with obviously unequal base addresses.
1292 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1293 isl_map_free(LoadAccs);
1294 isl_map_free(StoreAccs);
1295 continue;
1296 }
1297
1298 // And check if the remaining for overlap with other memory accesses.
1299 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1300 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1301 isl_set *AllAccs = isl_map_range(AllAccsRel);
1302
1303 for (MemoryAccess *MA : MemAccs) {
1304 if (MA == CandidatePair.first || MA == CandidatePair.second)
1305 continue;
1306
1307 isl_map *AccRel =
1308 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1309 isl_set *Accs = isl_map_range(AccRel);
1310
1311 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1312 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1313 Valid = Valid && isl_set_is_empty(OverlapAccs);
1314 isl_set_free(OverlapAccs);
1315 }
1316 }
1317
1318 isl_set_free(AllAccs);
1319 if (!Valid)
1320 continue;
1321
Johannes Doerfertf6183392014-07-01 20:52:51 +00001322 const LoadInst *Load =
1323 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1324 MemoryAccess::ReductionType RT =
1325 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1326
Johannes Doerferte58a0122014-06-27 20:31:28 +00001327 // If no overlapping access was found we mark the load and store as
1328 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001329 CandidatePair.first->markAsReductionLike(RT);
1330 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001331 }
Tobias Grosser75805372011-04-29 06:27:02 +00001332}
1333
Tobias Grosser74394f02013-01-14 22:40:23 +00001334std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001335
Tobias Grosser54839312015-04-21 11:37:25 +00001336std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001337 auto *S = getSchedule();
1338 auto Str = stringFromIslObj(S);
1339 isl_map_free(S);
1340 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001341}
1342
Tobias Grosser74394f02013-01-14 22:40:23 +00001343unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001344
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001345unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001346
Tobias Grosser75805372011-04-29 06:27:02 +00001347const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1348
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001349const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001350 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001351}
1352
Tobias Grosser74394f02013-01-14 22:40:23 +00001353isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001354
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001355__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001356
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001357__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001358 return isl_set_get_space(Domain);
1359}
1360
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001361__isl_give isl_id *ScopStmt::getDomainId() const {
1362 return isl_set_get_tuple_id(Domain);
1363}
Tobias Grossercd95b772012-08-30 11:49:38 +00001364
Tobias Grosser75805372011-04-29 06:27:02 +00001365ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001366 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001367 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001368}
1369
1370void ScopStmt::print(raw_ostream &OS) const {
1371 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001372 OS.indent(12) << "Domain :=\n";
1373
1374 if (Domain) {
1375 OS.indent(16) << getDomainStr() << ";\n";
1376 } else
1377 OS.indent(16) << "n/a\n";
1378
Tobias Grosser54839312015-04-21 11:37:25 +00001379 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001380
1381 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001382 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001383 } else
1384 OS.indent(16) << "n/a\n";
1385
Tobias Grosser083d3d32014-06-28 08:59:45 +00001386 for (MemoryAccess *Access : MemAccs)
1387 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001388}
1389
1390void ScopStmt::dump() const { print(dbgs()); }
1391
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001392void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001393
1394 // Remove all memory accesses in @p InvMAs from this statement together
1395 // with all scalar accesses that were caused by them. The tricky iteration
1396 // order uses is needed because the MemAccs is a vector and the order in
1397 // which the accesses of each memory access list (MAL) are stored in this
1398 // vector is reversed.
1399 for (MemoryAccess *MA : InvMAs) {
1400 auto &MAL = *lookupAccessesFor(MA->getAccessInstruction());
1401 MAL.reverse();
1402
1403 auto MALIt = MAL.begin();
1404 auto MALEnd = MAL.end();
1405 auto MemAccsIt = MemAccs.begin();
1406 while (MALIt != MALEnd) {
1407 while (*MemAccsIt != *MALIt)
1408 MemAccsIt++;
1409
1410 MALIt++;
1411 MemAccs.erase(MemAccsIt);
1412 }
1413
1414 InstructionToAccess.erase(MA->getAccessInstruction());
1415 delete &MAL;
1416 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001417}
1418
Tobias Grosser75805372011-04-29 06:27:02 +00001419//===----------------------------------------------------------------------===//
1420/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001421
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001422void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001423 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1424 isl_set_free(Context);
1425 Context = NewContext;
1426}
1427
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001428/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1429struct SCEVSensitiveParameterRewriter
1430 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1431 ValueToValueMap &VMap;
1432 ScalarEvolution &SE;
1433
1434public:
1435 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1436 : VMap(VMap), SE(SE) {}
1437
1438 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1439 ValueToValueMap &VMap) {
1440 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1441 return SSPR.visit(E);
1442 }
1443
1444 const SCEV *visit(const SCEV *E) {
1445 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1446 }
1447
1448 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1449
1450 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1451 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1452 }
1453
1454 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1455 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1456 }
1457
1458 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1459 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1460 }
1461
1462 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1463 SmallVector<const SCEV *, 4> Operands;
1464 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1465 Operands.push_back(visit(E->getOperand(i)));
1466 return SE.getAddExpr(Operands);
1467 }
1468
1469 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1470 SmallVector<const SCEV *, 4> Operands;
1471 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1472 Operands.push_back(visit(E->getOperand(i)));
1473 return SE.getMulExpr(Operands);
1474 }
1475
1476 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1477 SmallVector<const SCEV *, 4> Operands;
1478 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1479 Operands.push_back(visit(E->getOperand(i)));
1480 return SE.getSMaxExpr(Operands);
1481 }
1482
1483 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1484 SmallVector<const SCEV *, 4> Operands;
1485 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1486 Operands.push_back(visit(E->getOperand(i)));
1487 return SE.getUMaxExpr(Operands);
1488 }
1489
1490 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1491 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1492 }
1493
1494 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1495 auto *Start = visit(E->getStart());
1496 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1497 visit(E->getStepRecurrence(SE)),
1498 E->getLoop(), SCEV::FlagAnyWrap);
1499 return SE.getAddExpr(Start, AddRec);
1500 }
1501
1502 const SCEV *visitUnknown(const SCEVUnknown *E) {
1503 if (auto *NewValue = VMap.lookup(E->getValue()))
1504 return SE.getUnknown(NewValue);
1505 return E;
1506 }
1507};
1508
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001509const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001510 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001511}
1512
Tobias Grosserabfbe632013-02-05 12:09:06 +00001513void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001514 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001515 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001516
1517 // Normalize the SCEV to get the representing element for an invariant load.
1518 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1519
Tobias Grosser60b54f12011-11-08 15:41:28 +00001520 if (ParameterIds.find(Parameter) != ParameterIds.end())
1521 continue;
1522
1523 int dimension = Parameters.size();
1524
1525 Parameters.push_back(Parameter);
1526 ParameterIds[Parameter] = dimension;
1527 }
1528}
1529
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001530__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001531 // Normalize the SCEV to get the representing element for an invariant load.
1532 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1533
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001534 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001535
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001536 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001537 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001538
Tobias Grosser8f99c162011-11-15 11:38:55 +00001539 std::string ParameterName;
1540
1541 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1542 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001543 ParameterName = Val->getName();
Johannes Doerferte071f6d2015-11-03 16:49:59 +00001544 if (!Val->hasName())
1545 if (LoadInst *LI = dyn_cast<LoadInst>(Val))
1546 ParameterName =
1547 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001548 }
1549
1550 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001551 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001552
Tobias Grosser20532b82014-04-11 17:56:49 +00001553 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1554 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001555}
Tobias Grosser75805372011-04-29 06:27:02 +00001556
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001557isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1558 isl_set *DomainContext = isl_union_set_params(getDomains());
1559 return isl_set_intersect_params(C, DomainContext);
1560}
1561
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001562void Scop::buildBoundaryContext() {
1563 BoundaryContext = Affinator.getWrappingContext();
1564 BoundaryContext = isl_set_complement(BoundaryContext);
1565 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
1566}
1567
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001568void Scop::addUserContext() {
1569 if (UserContextStr.empty())
1570 return;
1571
1572 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1573 isl_space *Space = getParamSpace();
1574 if (isl_space_dim(Space, isl_dim_param) !=
1575 isl_set_dim(UserContext, isl_dim_param)) {
1576 auto SpaceStr = isl_space_to_str(Space);
1577 errs() << "Error: the context provided in -polly-context has not the same "
1578 << "number of dimensions than the computed context. Due to this "
1579 << "mismatch, the -polly-context option is ignored. Please provide "
1580 << "the context in the parameter space: " << SpaceStr << ".\n";
1581 free(SpaceStr);
1582 isl_set_free(UserContext);
1583 isl_space_free(Space);
1584 return;
1585 }
1586
1587 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1588 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1589 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1590
1591 if (strcmp(NameContext, NameUserContext) != 0) {
1592 auto SpaceStr = isl_space_to_str(Space);
1593 errs() << "Error: the name of dimension " << i
1594 << " provided in -polly-context "
1595 << "is '" << NameUserContext << "', but the name in the computed "
1596 << "context is '" << NameContext
1597 << "'. Due to this name mismatch, "
1598 << "the -polly-context option is ignored. Please provide "
1599 << "the context in the parameter space: " << SpaceStr << ".\n";
1600 free(SpaceStr);
1601 isl_set_free(UserContext);
1602 isl_space_free(Space);
1603 return;
1604 }
1605
1606 UserContext =
1607 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1608 isl_space_get_dim_id(Space, isl_dim_param, i));
1609 }
1610
1611 Context = isl_set_intersect(Context, UserContext);
1612 isl_space_free(Space);
1613}
1614
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001615void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001616 DenseMap<const SCEV *, LoadInst *> EquivClasses;
1617
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001618 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001619 for (LoadInst *LInst : RIL) {
1620 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1621
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001622 LoadInst *&ClassRep = EquivClasses[PointerSCEV];
1623 if (!ClassRep)
1624 ClassRep = LInst;
1625 else
1626 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001627 }
1628}
1629
Tobias Grosser6be480c2011-11-08 15:41:13 +00001630void Scop::buildContext() {
1631 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001632 Context = isl_set_universe(isl_space_copy(Space));
1633 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001634}
1635
Tobias Grosser18daaca2012-05-22 10:47:27 +00001636void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001637 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001638 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001639
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001640 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001641
Johannes Doerferte7044942015-02-24 11:58:30 +00001642 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001643 }
1644}
1645
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001646void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001647 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001648 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001649
Tobias Grosser083d3d32014-06-28 08:59:45 +00001650 for (const auto &ParamID : ParameterIds) {
1651 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001652 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001653 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001654 }
1655
1656 // Align the parameters of all data structures to the model.
1657 Context = isl_set_align_params(Context, Space);
1658
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001659 for (ScopStmt &Stmt : *this)
1660 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001661}
1662
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001663static __isl_give isl_set *
1664simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1665 const Scop &S) {
1666 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1667 AssumptionContext = isl_set_gist_params(AssumptionContext, DomainParameters);
1668 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1669 return AssumptionContext;
1670}
1671
1672void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001673 // The parameter constraints of the iteration domains give us a set of
1674 // constraints that need to hold for all cases where at least a single
1675 // statement iteration is executed in the whole scop. We now simplify the
1676 // assumed context under the assumption that such constraints hold and at
1677 // least a single statement iteration is executed. For cases where no
1678 // statement instances are executed, the assumptions we have taken about
1679 // the executed code do not matter and can be changed.
1680 //
1681 // WARNING: This only holds if the assumptions we have taken do not reduce
1682 // the set of statement instances that are executed. Otherwise we
1683 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001684 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001685 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001686 // performed. In such a case, modifying the run-time conditions and
1687 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001688 // to not be executed.
1689 //
1690 // Example:
1691 //
1692 // When delinearizing the following code:
1693 //
1694 // for (long i = 0; i < 100; i++)
1695 // for (long j = 0; j < m; j++)
1696 // A[i+p][j] = 1.0;
1697 //
1698 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001699 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001700 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001701 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1702 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001703}
1704
Johannes Doerfertb164c792014-09-18 11:17:17 +00001705/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001706static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001707 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1708 isl_pw_multi_aff *MinPMA, *MaxPMA;
1709 isl_pw_aff *LastDimAff;
1710 isl_aff *OneAff;
1711 unsigned Pos;
1712
Johannes Doerfert9143d672014-09-27 11:02:39 +00001713 // Restrict the number of parameters involved in the access as the lexmin/
1714 // lexmax computation will take too long if this number is high.
1715 //
1716 // Experiments with a simple test case using an i7 4800MQ:
1717 //
1718 // #Parameters involved | Time (in sec)
1719 // 6 | 0.01
1720 // 7 | 0.04
1721 // 8 | 0.12
1722 // 9 | 0.40
1723 // 10 | 1.54
1724 // 11 | 6.78
1725 // 12 | 30.38
1726 //
1727 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1728 unsigned InvolvedParams = 0;
1729 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1730 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1731 InvolvedParams++;
1732
1733 if (InvolvedParams > RunTimeChecksMaxParameters) {
1734 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001735 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001736 }
1737 }
1738
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001739 Set = isl_set_remove_divs(Set);
1740
Johannes Doerfertb164c792014-09-18 11:17:17 +00001741 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1742 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1743
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001744 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1745 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1746
Johannes Doerfertb164c792014-09-18 11:17:17 +00001747 // Adjust the last dimension of the maximal access by one as we want to
1748 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1749 // we test during code generation might now point after the end of the
1750 // allocated array but we will never dereference it anyway.
1751 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1752 "Assumed at least one output dimension");
1753 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1754 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1755 OneAff = isl_aff_zero_on_domain(
1756 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1757 OneAff = isl_aff_add_constant_si(OneAff, 1);
1758 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1759 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1760
1761 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1762
1763 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001764 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001765}
1766
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001767static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1768 isl_set *Domain = MA->getStatement()->getDomain();
1769 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1770 return isl_set_reset_tuple_id(Domain);
1771}
1772
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001773/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1774static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001775 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001776 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001777
1778 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1779 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001780 Locations = isl_union_set_coalesce(Locations);
1781 Locations = isl_union_set_detect_equalities(Locations);
1782 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001783 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001784 isl_union_set_free(Locations);
1785 return Valid;
1786}
1787
Johannes Doerfert96425c22015-08-30 21:13:53 +00001788/// @brief Helper to treat non-affine regions and basic blocks the same.
1789///
1790///{
1791
1792/// @brief Return the block that is the representing block for @p RN.
1793static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1794 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1795 : RN->getNodeAs<BasicBlock>();
1796}
1797
1798/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001799static inline BasicBlock *
1800getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001801 if (RN->isSubRegion()) {
1802 assert(idx == 0);
1803 return RN->getNodeAs<Region>()->getExit();
1804 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001805 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001806}
1807
1808/// @brief Return the smallest loop surrounding @p RN.
1809static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1810 if (!RN->isSubRegion())
1811 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1812
1813 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1814 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1815 while (L && NonAffineSubRegion->contains(L))
1816 L = L->getParentLoop();
1817 return L;
1818}
1819
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001820static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1821 if (!RN->isSubRegion())
1822 return 1;
1823
1824 unsigned NumBlocks = 0;
1825 Region *R = RN->getNodeAs<Region>();
1826 for (auto BB : R->blocks()) {
1827 (void)BB;
1828 NumBlocks++;
1829 }
1830 return NumBlocks;
1831}
1832
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001833static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1834 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001835 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001836 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001837 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001838 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001839 return true;
1840 return false;
1841}
1842
Johannes Doerfert96425c22015-08-30 21:13:53 +00001843///}
1844
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001845static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1846 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001847 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001848 isl_id *DimId =
1849 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1850 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1851}
1852
Johannes Doerfert96425c22015-08-30 21:13:53 +00001853isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1854 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1855 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001856 return getDomainConditions(BB);
1857}
1858
1859isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1860 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001861 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001862}
1863
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001864void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001865
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001866 auto *EntryBB = R->getEntry();
1867 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1868 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001869
1870 Loop *L = LI.getLoopFor(EntryBB);
1871 while (LD-- >= 0) {
1872 S = addDomainDimId(S, LD + 1, L);
1873 L = L->getParentLoop();
1874 }
1875
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001876 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001877
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001878 if (SD.isNonAffineSubRegion(R, R))
1879 return;
1880
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001881 buildDomainsWithBranchConstraints(R);
1882 propagateDomainConstraints(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001883}
1884
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001885void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001886 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001887
1888 // To create the domain for each block in R we iterate over all blocks and
1889 // subregions in R and propagate the conditions under which the current region
1890 // element is executed. To this end we iterate in reverse post order over R as
1891 // it ensures that we first visit all predecessors of a region node (either a
1892 // basic block or a subregion) before we visit the region node itself.
1893 // Initially, only the domain for the SCoP region entry block is set and from
1894 // there we propagate the current domain to all successors, however we add the
1895 // condition that the successor is actually executed next.
1896 // As we are only interested in non-loop carried constraints here we can
1897 // simply skip loop back edges.
1898
1899 ReversePostOrderTraversal<Region *> RTraversal(R);
1900 for (auto *RN : RTraversal) {
1901
1902 // Recurse for affine subregions but go on for basic blocks and non-affine
1903 // subregions.
1904 if (RN->isSubRegion()) {
1905 Region *SubRegion = RN->getNodeAs<Region>();
1906 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001907 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001908 continue;
1909 }
1910 }
1911
Johannes Doerfertf5673802015-10-01 23:48:18 +00001912 // Error blocks are assumed not to be executed. Therefor they are not
1913 // checked properly in the ScopDetection. Any attempt to generate control
1914 // conditions from them might result in a crash. However, this is only true
1915 // for the first step of the domain generation (this function) where we
1916 // push the control conditions of a block to the successors. In the second
1917 // step (propagateDomainConstraints) we only receive domain constraints from
1918 // the predecessors and can therefor look at the domain of a error block.
1919 // That allows us to generate the assumptions needed for them not to be
1920 // executed at runtime.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001921 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001922 continue;
1923
Johannes Doerfert96425c22015-08-30 21:13:53 +00001924 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001925 TerminatorInst *TI = BB->getTerminator();
1926
Johannes Doerfertf5673802015-10-01 23:48:18 +00001927 isl_set *Domain = DomainMap.lookup(BB);
1928 if (!Domain) {
1929 DEBUG(dbgs() << "\tSkip: " << BB->getName()
1930 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001931 continue;
1932 }
1933
Johannes Doerfert96425c22015-08-30 21:13:53 +00001934 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001935
1936 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1937 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1938
1939 // Build the condition sets for the successor nodes of the current region
1940 // node. If it is a non-affine subregion we will always execute the single
1941 // exit node, hence the single entry node domain is the condition set. For
1942 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001943 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001944 if (RN->isSubRegion())
1945 ConditionSets.push_back(isl_set_copy(Domain));
1946 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001947 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001948
1949 // Now iterate over the successors and set their initial domain based on
1950 // their condition set. We skip back edges here and have to be careful when
1951 // we leave a loop not to keep constraints over a dimension that doesn't
1952 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001953 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00001954 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001955 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001956 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001957
1958 // Skip back edges.
1959 if (DT.dominates(SuccBB, BB)) {
1960 isl_set_free(CondSet);
1961 continue;
1962 }
1963
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001964 // Do not adjust the number of dimensions if we enter a boxed loop or are
1965 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001966 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001967 Region *SuccRegion = RI.getRegionFor(SuccBB);
Johannes Doerfert634909c2015-10-04 14:57:41 +00001968 if (SD.isNonAffineSubRegion(SuccRegion, &getRegion()))
1969 while (SuccBBLoop && SuccRegion->contains(SuccBBLoop))
1970 SuccBBLoop = SuccBBLoop->getParentLoop();
1971
1972 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001973
1974 // Check if the edge to SuccBB is a loop entry or exit edge. If so
1975 // adjust the dimensionality accordingly. Lastly, if we leave a loop
1976 // and enter a new one we need to drop the old constraints.
1977 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001978 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001979 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001980 CondSet = isl_set_project_out(CondSet, isl_dim_set,
1981 isl_set_n_dim(CondSet) - LoopDepthDiff,
1982 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001983 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001984 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001985 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001986 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001987 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001988 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001989 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
1990 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001991 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001992 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00001993 }
1994
1995 // Set the domain for the successor or merge it with an existing domain in
1996 // case there are multiple paths (without loop back edges) to the
1997 // successor block.
1998 isl_set *&SuccDomain = DomainMap[SuccBB];
1999 if (!SuccDomain)
2000 SuccDomain = CondSet;
2001 else
2002 SuccDomain = isl_set_union(SuccDomain, CondSet);
2003
2004 SuccDomain = isl_set_coalesce(SuccDomain);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002005 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2006 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002007 }
2008 }
2009}
2010
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002011/// @brief Return the domain for @p BB wrt @p DomainMap.
2012///
2013/// This helper function will lookup @p BB in @p DomainMap but also handle the
2014/// case where @p BB is contained in a non-affine subregion using the region
2015/// tree obtained by @p RI.
2016static __isl_give isl_set *
2017getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2018 RegionInfo &RI) {
2019 auto DIt = DomainMap.find(BB);
2020 if (DIt != DomainMap.end())
2021 return isl_set_copy(DIt->getSecond());
2022
2023 Region *R = RI.getRegionFor(BB);
2024 while (R->getEntry() == BB)
2025 R = R->getParent();
2026 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2027}
2028
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002029void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002030 // Iterate over the region R and propagate the domain constrains from the
2031 // predecessors to the current node. In contrast to the
2032 // buildDomainsWithBranchConstraints function, this one will pull the domain
2033 // information from the predecessors instead of pushing it to the successors.
2034 // Additionally, we assume the domains to be already present in the domain
2035 // map here. However, we iterate again in reverse post order so we know all
2036 // predecessors have been visited before a block or non-affine subregion is
2037 // visited.
2038
2039 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2040 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2041
2042 ReversePostOrderTraversal<Region *> RTraversal(R);
2043 for (auto *RN : RTraversal) {
2044
2045 // Recurse for affine subregions but go on for basic blocks and non-affine
2046 // subregions.
2047 if (RN->isSubRegion()) {
2048 Region *SubRegion = RN->getNodeAs<Region>();
2049 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002050 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002051 continue;
2052 }
2053 }
2054
Johannes Doerfertf5673802015-10-01 23:48:18 +00002055 // Get the domain for the current block and check if it was initialized or
2056 // not. The only way it was not is if this block is only reachable via error
2057 // blocks, thus will not be executed under the assumptions we make. Such
2058 // blocks have to be skipped as their predecessors might not have domains
2059 // either. It would not benefit us to compute the domain anyway, only the
2060 // domains of the error blocks that are reachable from non-error blocks
2061 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002062 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002063 isl_set *&Domain = DomainMap[BB];
2064 if (!Domain) {
2065 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2066 << ", it is only reachable from error blocks.\n");
2067 DomainMap.erase(BB);
2068 continue;
2069 }
2070 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2071
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002072 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2073 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2074
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002075 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2076 for (auto *PredBB : predecessors(BB)) {
2077
2078 // Skip backedges
2079 if (DT.dominates(BB, PredBB))
2080 continue;
2081
2082 isl_set *PredBBDom = nullptr;
2083
2084 // Handle the SCoP entry block with its outside predecessors.
2085 if (!getRegion().contains(PredBB))
2086 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2087
2088 if (!PredBBDom) {
2089 // Determine the loop depth of the predecessor and adjust its domain to
2090 // the domain of the current block. This can mean we have to:
2091 // o) Drop a dimension if this block is the exit of a loop, not the
2092 // header of a new loop and the predecessor was part of the loop.
2093 // o) Add an unconstrainted new dimension if this block is the header
2094 // of a loop and the predecessor is not part of it.
2095 // o) Drop the information about the innermost loop dimension when the
2096 // predecessor and the current block are surrounded by different
2097 // loops in the same depth.
2098 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2099 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2100 while (BoxedLoops.count(PredBBLoop))
2101 PredBBLoop = PredBBLoop->getParentLoop();
2102
2103 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002104 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002105 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002106 PredBBDom = isl_set_project_out(
2107 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2108 LoopDepthDiff);
2109 else if (PredBBLoopDepth < BBLoopDepth) {
2110 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002111 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002112 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2113 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002114 PredBBDom = isl_set_drop_constraints_involving_dims(
2115 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002116 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002117 }
2118
2119 PredDom = isl_set_union(PredDom, PredBBDom);
2120 }
2121
2122 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002123 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002124
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002125 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002126 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002127
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002128 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002129 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002130 IsOptimized = true;
2131 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2132 addAssumption(isl_set_complement(DomPar));
2133 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002134 }
2135}
2136
2137/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2138/// is incremented by one and all other dimensions are equal, e.g.,
2139/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2140/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2141static __isl_give isl_map *
2142createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2143 auto *MapSpace = isl_space_map_from_set(SetSpace);
2144 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2145 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2146 if (u != Dim)
2147 NextIterationMap =
2148 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2149 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2150 C = isl_constraint_set_constant_si(C, 1);
2151 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2152 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2153 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2154 return NextIterationMap;
2155}
2156
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002157void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002158 int LoopDepth = getRelativeLoopDepth(L);
2159 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002160
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002161 BasicBlock *HeaderBB = L->getHeader();
2162 assert(DomainMap.count(HeaderBB));
2163 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002164
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002165 isl_map *NextIterationMap =
2166 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002167
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002168 isl_set *UnionBackedgeCondition =
2169 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002170
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002171 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2172 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002173
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002174 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002175
2176 // If the latch is only reachable via error statements we skip it.
2177 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2178 if (!LatchBBDom)
2179 continue;
2180
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002181 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002182
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002183 TerminatorInst *TI = LatchBB->getTerminator();
2184 BranchInst *BI = dyn_cast<BranchInst>(TI);
2185 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002186 BackedgeCondition = isl_set_copy(LatchBBDom);
2187 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002188 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002189 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002190 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002191
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002192 // Free the non back edge condition set as we do not need it.
2193 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002194
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002195 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002196 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002197
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002198 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2199 assert(LatchLoopDepth >= LoopDepth);
2200 BackedgeCondition =
2201 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2202 LatchLoopDepth - LoopDepth);
2203 UnionBackedgeCondition =
2204 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002205 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002206
2207 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2208 for (int i = 0; i < LoopDepth; i++)
2209 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2210
2211 isl_set *UnionBackedgeConditionComplement =
2212 isl_set_complement(UnionBackedgeCondition);
2213 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2214 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2215 UnionBackedgeConditionComplement =
2216 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2217 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2218 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2219
2220 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2221 HeaderBBDom = Parts.second;
2222
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002223 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2224 // the bounded assumptions to the context as they are already implied by the
2225 // <nsw> tag.
2226 if (Affinator.hasNSWAddRecForLoop(L)) {
2227 isl_set_free(Parts.first);
2228 return;
2229 }
2230
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002231 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2232 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfert707a4062015-09-20 16:38:19 +00002233 addAssumption(BoundedCtx);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002234}
2235
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002236void Scop::buildAliasChecks(AliasAnalysis &AA) {
2237 if (!PollyUseRuntimeAliasChecks)
2238 return;
2239
2240 if (buildAliasGroups(AA))
2241 return;
2242
2243 // If a problem occurs while building the alias groups we need to delete
2244 // this SCoP and pretend it wasn't valid in the first place. To this end
2245 // we make the assumed context infeasible.
2246 addAssumption(isl_set_empty(getParamSpace()));
2247
2248 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2249 << " could not be created as the number of parameters involved "
2250 "is too high. The SCoP will be "
2251 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2252 "the maximal number of parameters but be advised that the "
2253 "compile time might increase exponentially.\n\n");
2254}
2255
Johannes Doerfert9143d672014-09-27 11:02:39 +00002256bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002257 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002258 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002259 // for all memory accesses inside the SCoP.
2260 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002261 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002262 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002263 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002264 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002265 // if their access domains intersect, otherwise they are in different
2266 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002267 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002268 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002269 // and maximal accesses to each array of a group in read only and non
2270 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002271 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2272
2273 AliasSetTracker AST(AA);
2274
2275 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002276 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002277 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002278
2279 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002280 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002281 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2282 isl_set_free(StmtDomain);
2283 if (StmtDomainEmpty)
2284 continue;
2285
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002286 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00002287 if (MA->isImplicit())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002288 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002289 if (!MA->isRead())
2290 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002291 Instruction *Acc = MA->getAccessInstruction();
2292 PtrToAcc[getPointerOperand(*Acc)] = MA;
2293 AST.add(Acc);
2294 }
2295 }
2296
2297 SmallVector<AliasGroupTy, 4> AliasGroups;
2298 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002299 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002300 continue;
2301 AliasGroupTy AG;
2302 for (auto PR : AS)
2303 AG.push_back(PtrToAcc[PR.getValue()]);
2304 assert(AG.size() > 1 &&
2305 "Alias groups should contain at least two accesses");
2306 AliasGroups.push_back(std::move(AG));
2307 }
2308
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002309 // Split the alias groups based on their domain.
2310 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2311 AliasGroupTy NewAG;
2312 AliasGroupTy &AG = AliasGroups[u];
2313 AliasGroupTy::iterator AGI = AG.begin();
2314 isl_set *AGDomain = getAccessDomain(*AGI);
2315 while (AGI != AG.end()) {
2316 MemoryAccess *MA = *AGI;
2317 isl_set *MADomain = getAccessDomain(MA);
2318 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2319 NewAG.push_back(MA);
2320 AGI = AG.erase(AGI);
2321 isl_set_free(MADomain);
2322 } else {
2323 AGDomain = isl_set_union(AGDomain, MADomain);
2324 AGI++;
2325 }
2326 }
2327 if (NewAG.size() > 1)
2328 AliasGroups.push_back(std::move(NewAG));
2329 isl_set_free(AGDomain);
2330 }
2331
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002332 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002333 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2334 for (AliasGroupTy &AG : AliasGroups) {
2335 NonReadOnlyBaseValues.clear();
2336 ReadOnlyPairs.clear();
2337
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002338 if (AG.size() < 2) {
2339 AG.clear();
2340 continue;
2341 }
2342
Johannes Doerfert13771732014-10-01 12:40:46 +00002343 for (auto II = AG.begin(); II != AG.end();) {
2344 Value *BaseAddr = (*II)->getBaseAddr();
2345 if (HasWriteAccess.count(BaseAddr)) {
2346 NonReadOnlyBaseValues.insert(BaseAddr);
2347 II++;
2348 } else {
2349 ReadOnlyPairs[BaseAddr].insert(*II);
2350 II = AG.erase(II);
2351 }
2352 }
2353
2354 // If we don't have read only pointers check if there are at least two
2355 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002356 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002357 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002358 continue;
2359 }
2360
2361 // If we don't have non read only pointers clear the alias group.
2362 if (NonReadOnlyBaseValues.empty()) {
2363 AG.clear();
2364 continue;
2365 }
2366
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002367 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002368 MinMaxAliasGroups.emplace_back();
2369 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2370 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2371 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2372 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002373
2374 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002375
2376 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002377 for (MemoryAccess *MA : AG)
2378 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002379
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002380 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2381 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002382
2383 // Bail out if the number of values we need to compare is too large.
2384 // This is important as the number of comparisions grows quadratically with
2385 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002386 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2387 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002388 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002389
2390 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002391 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002392 Accesses = isl_union_map_empty(getParamSpace());
2393
2394 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2395 for (MemoryAccess *MA : ReadOnlyPair.second)
2396 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2397
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002398 Valid =
2399 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002400
2401 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002402 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002403 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002404
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002405 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002406}
2407
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002408static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2409 Loop *L = LI.getLoopFor(R.getEntry());
2410 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2411}
2412
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002413static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2414 ScopDetection &SD) {
2415
2416 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2417
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002418 unsigned MinLD = INT_MAX, MaxLD = 0;
2419 for (BasicBlock *BB : R.blocks()) {
2420 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002421 if (!R.contains(L))
2422 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002423 if (BoxedLoops && BoxedLoops->count(L))
2424 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002425 unsigned LD = L->getLoopDepth();
2426 MinLD = std::min(MinLD, LD);
2427 MaxLD = std::max(MaxLD, LD);
2428 }
2429 }
2430
2431 // Handle the case that there is no loop in the SCoP first.
2432 if (MaxLD == 0)
2433 return 1;
2434
2435 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2436 assert(MaxLD >= MinLD &&
2437 "Maximal loop depth was smaller than mininaml loop depth?");
2438 return MaxLD - MinLD + 1;
2439}
2440
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002441Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002442 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002443 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002444 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2445 AccFuncMap(AccFuncMap), IsOptimized(false),
2446 HasSingleExitEdge(R.getExitingBlock()), MaxLoopDepth(MaxLoopDepth),
2447 IslCtx(Context), Context(nullptr), Affinator(this),
2448 AssumedContext(nullptr), BoundaryContext(nullptr), Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002449
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002450void Scop::init(AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002451 buildContext();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002452 buildInvariantEquivalenceClasses();
2453
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002454 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002455
Michael Krusecac948e2015-10-02 13:53:07 +00002456 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002457 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002458 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002459 if (Stmts.empty())
2460 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002461
Michael Krusecac948e2015-10-02 13:53:07 +00002462 // The ScopStmts now have enough information to initialize themselves.
2463 for (ScopStmt &Stmt : Stmts)
2464 Stmt.init();
2465
2466 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002467 Loop *L = getLoopSurroundingRegion(R, LI);
2468 LoopSchedules[L];
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002469 buildSchedule(&R, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002470 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002471
Tobias Grosser8286b832015-11-02 11:29:32 +00002472 if (isl_set_is_empty(AssumedContext))
2473 return;
2474
2475 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002476 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002477 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002478 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002479 buildBoundaryContext();
2480 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002481 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002482
2483 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002484 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002485}
2486
2487Scop::~Scop() {
2488 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002489 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002490 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002491 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002492
Johannes Doerfert96425c22015-08-30 21:13:53 +00002493 for (auto It : DomainMap)
2494 isl_set_free(It.second);
2495
Johannes Doerfertb164c792014-09-18 11:17:17 +00002496 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002497 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002498 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002499 isl_pw_multi_aff_free(MMA.first);
2500 isl_pw_multi_aff_free(MMA.second);
2501 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002502 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002503 isl_pw_multi_aff_free(MMA.first);
2504 isl_pw_multi_aff_free(MMA.second);
2505 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002506 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002507
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002508 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002509 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002510}
2511
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002512void Scop::updateAccessDimensionality() {
2513 for (auto &Stmt : *this)
2514 for (auto &Access : Stmt)
2515 Access->updateDimensionality();
2516}
2517
Michael Krusecac948e2015-10-02 13:53:07 +00002518void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002519 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2520 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002521 RegionNode *RN = Stmt.isRegionStmt()
2522 ? Stmt.getRegion()->getNode()
2523 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002524
Johannes Doerferteca9e892015-11-03 16:54:49 +00002525 bool RemoveStmt = StmtIt->isEmpty();
2526 if (!RemoveStmt)
2527 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2528 if (!RemoveStmt)
2529 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002530
Johannes Doerferteca9e892015-11-03 16:54:49 +00002531 // Remove read only statements only after invariant loop hoisting.
2532 if (!RemoveStmt && !RemoveIgnoredStmts) {
2533 bool OnlyRead = true;
2534 for (MemoryAccess *MA : Stmt) {
2535 if (MA->isRead())
2536 continue;
2537
2538 OnlyRead = false;
2539 break;
2540 }
2541
2542 RemoveStmt = OnlyRead;
2543 }
2544
2545 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002546 // Remove the statement because it is unnecessary.
2547 if (Stmt.isRegionStmt())
2548 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2549 StmtMap.erase(BB);
2550 else
2551 StmtMap.erase(Stmt.getBasicBlock());
2552
2553 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002554 continue;
2555 }
2556
Michael Krusecac948e2015-10-02 13:53:07 +00002557 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002558 }
2559}
2560
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002561const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2562 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2563 if (!LInst)
2564 return nullptr;
2565
2566 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2567 LInst = cast<LoadInst>(Rep);
2568
2569 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2570 for (auto &IAClass : InvariantEquivClasses)
2571 if (PointerSCEV == std::get<0>(IAClass))
2572 return &IAClass;
2573
2574 return nullptr;
2575}
2576
2577void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2578
2579 // Get the context under which the statement is executed.
2580 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2581 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2582 DomainCtx = isl_set_detect_equalities(DomainCtx);
2583 DomainCtx = isl_set_coalesce(DomainCtx);
2584
2585 // Project out all parameters that relate to loads in the statement. Otherwise
2586 // we could have cyclic dependences on the constraints under which the
2587 // hoisted loads are executed and we could not determine an order in which to
2588 // pre-load them. This happens because not only lower bounds are part of the
2589 // domain but also upper bounds.
2590 for (MemoryAccess *MA : InvMAs) {
2591 Instruction *AccInst = MA->getAccessInstruction();
2592 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002593 SetVector<Value *> Values;
2594 for (const SCEV *Parameter : Parameters) {
2595 Values.clear();
2596 findValues(Parameter, Values);
2597 if (!Values.count(AccInst))
2598 continue;
2599
2600 if (isl_id *ParamId = getIdForParam(Parameter)) {
2601 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2602 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2603 isl_id_free(ParamId);
2604 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002605 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002606 }
2607 }
2608
2609 for (MemoryAccess *MA : InvMAs) {
2610 // Check for another invariant access that accesses the same location as
2611 // MA and if found consolidate them. Otherwise create a new equivalence
2612 // class at the end of InvariantEquivClasses.
2613 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2614 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2615
2616 bool Consolidated = false;
2617 for (auto &IAClass : InvariantEquivClasses) {
2618 if (PointerSCEV != std::get<0>(IAClass))
2619 continue;
2620
2621 Consolidated = true;
2622
2623 // Add MA to the list of accesses that are in this class.
2624 auto &MAs = std::get<1>(IAClass);
2625 MAs.push_front(MA);
2626
2627 // Unify the execution context of the class and this statement.
2628 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
2629 IAClassDomainCtx = isl_set_coalesce(
2630 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2631 break;
2632 }
2633
2634 if (Consolidated)
2635 continue;
2636
2637 // If we did not consolidate MA, thus did not find an equivalence class
2638 // for it, we create a new one.
2639 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2640 isl_set_copy(DomainCtx));
2641 }
2642
2643 isl_set_free(DomainCtx);
2644}
2645
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002646void Scop::hoistInvariantLoads() {
2647 isl_union_map *Writes = getWrites();
2648 for (ScopStmt &Stmt : *this) {
2649
2650 // TODO: Loads that are not loop carried, hence are in a statement with
2651 // zero iterators, are by construction invariant, though we
Johannes Doerfert09e36972015-10-07 20:17:36 +00002652 // currently "hoist" them anyway. This is necessary because we allow
2653 // them to be treated as parameters (e.g., in conditions) and our code
2654 // generation would otherwise use the old value.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002655
Johannes Doerfert8930f482015-10-02 14:51:00 +00002656 BasicBlock *BB = Stmt.isBlockStmt() ? Stmt.getBasicBlock()
2657 : Stmt.getRegion()->getEntry();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002658 isl_set *Domain = Stmt.getDomain();
2659 MemoryAccessList InvMAs;
2660
2661 for (MemoryAccess *MA : Stmt) {
2662 if (MA->isImplicit() || MA->isWrite() || !MA->isAffine())
2663 continue;
2664
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002665 // Skip accesses that have an invariant base pointer which is defined but
2666 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2667 // returns a pointer that is used as a base address. However, as we want
2668 // to hoist indirect pointers, we allow the base pointer to be defined in
Johannes Doerfert654c3282015-10-21 22:14:57 +00002669 // the region if it is also a memory access. Each ScopArrayInfo object
2670 // that has a base pointer origin has a base pointer that is loaded and
2671 // that it is invariant, thus it will be hoisted too. However, if there is
Tobias Grosser27e19a02015-10-25 12:05:14 +00002672 // no base pointer origin we check that the base pointer is defined
Johannes Doerfert654c3282015-10-21 22:14:57 +00002673 // outside the region.
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002674 const ScopArrayInfo *SAI = MA->getScopArrayInfo();
Johannes Doerfert654c3282015-10-21 22:14:57 +00002675 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2676 SAI = BasePtrOriginSAI;
2677
2678 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2679 if (R.contains(BasePtrInst))
2680 continue;
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002681
Johannes Doerfert8930f482015-10-02 14:51:00 +00002682 // Skip accesses in non-affine subregions as they might not be executed
2683 // under the same condition as the entry of the non-affine subregion.
2684 if (BB != MA->getAccessInstruction()->getParent())
2685 continue;
2686
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002687 isl_map *AccessRelation = MA->getAccessRelation();
Johannes Doerfertb864c2c2015-10-18 19:50:18 +00002688
2689 // Skip accesses that have an empty access relation. These can be caused
2690 // by multiple offsets with a type cast in-between that cause the overall
2691 // byte offset to be not divisible by the new types sizes.
2692 if (isl_map_is_empty(AccessRelation)) {
2693 isl_map_free(AccessRelation);
2694 continue;
2695 }
2696
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002697 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2698 Stmt.getNumIterators())) {
2699 isl_map_free(AccessRelation);
2700 continue;
2701 }
2702
2703 AccessRelation =
2704 isl_map_intersect_domain(AccessRelation, isl_set_copy(Domain));
2705 isl_set *AccessRange = isl_map_range(AccessRelation);
2706
2707 isl_union_map *Written = isl_union_map_intersect_range(
2708 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2709 bool IsWritten = !isl_union_map_is_empty(Written);
2710 isl_union_map_free(Written);
2711
2712 if (IsWritten)
2713 continue;
2714
2715 InvMAs.push_front(MA);
2716 }
2717
2718 // We inserted invariant accesses always in the front but need them to be
2719 // sorted in a "natural order". The statements are already sorted in reverse
2720 // post order and that suffices for the accesses too. The reason we require
2721 // an order in the first place is the dependences between invariant loads
2722 // that can be caused by indirect loads.
2723 InvMAs.reverse();
2724
2725 // Transfer the memory access from the statement to the SCoP.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002726 Stmt.removeMemoryAccesses(InvMAs);
2727 addInvariantLoads(Stmt, InvMAs);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002728
2729 isl_set_free(Domain);
2730 }
2731 isl_union_map_free(Writes);
2732
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002733 if (!InvariantEquivClasses.empty())
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002734 IsOptimized = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00002735
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002736 auto &ScopRIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002737 // Check required invariant loads that were tagged during SCoP detection.
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002738 for (LoadInst *LI : ScopRIL) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00002739 assert(LI && getRegion().contains(LI));
2740 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
2741 if (Stmt && Stmt->lookupAccessesFor(LI) != nullptr) {
2742 DEBUG(dbgs() << "\n\nWARNING: Load (" << *LI
2743 << ") is required to be invariant but was not marked as "
2744 "such. SCoP for "
2745 << getRegion() << " will be dropped\n\n");
2746 addAssumption(isl_set_empty(getParamSpace()));
2747 return;
2748 }
2749 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002750}
2751
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002752const ScopArrayInfo *
2753Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Michael Kruse28468772015-09-14 15:45:33 +00002754 ArrayRef<const SCEV *> Sizes, bool IsPHI) {
Johannes Doerferta7686242015-11-08 19:12:05 +00002755 bool IsScalar = Sizes.empty();
2756 auto ScalarTypePair = std::make_pair(IsScalar, IsPHI);
2757 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, ScalarTypePair)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002758 if (!SAI) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002759 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
2760 this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002761 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002762 // In case of mismatching array sizes, we bail out by setting the run-time
2763 // context to false.
2764 if (!SAI->updateSizes(Sizes))
2765 addAssumption(isl_set_empty(getParamSpace()));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002766 }
Tobias Grosserab671442015-05-23 05:58:27 +00002767 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002768}
2769
Johannes Doerferta7686242015-11-08 19:12:05 +00002770const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsScalar,
2771 bool IsPHI) {
2772 auto ScalarTypePair = std::make_pair(IsScalar, IsPHI);
2773 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, ScalarTypePair)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002774 assert(SAI && "No ScopArrayInfo available for this base pointer");
2775 return SAI;
2776}
2777
Tobias Grosser74394f02013-01-14 22:40:23 +00002778std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002779std::string Scop::getAssumedContextStr() const {
2780 return stringFromIslObj(AssumedContext);
2781}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002782std::string Scop::getBoundaryContextStr() const {
2783 return stringFromIslObj(BoundaryContext);
2784}
Tobias Grosser75805372011-04-29 06:27:02 +00002785
2786std::string Scop::getNameStr() const {
2787 std::string ExitName, EntryName;
2788 raw_string_ostream ExitStr(ExitName);
2789 raw_string_ostream EntryStr(EntryName);
2790
Tobias Grosserf240b482014-01-09 10:42:15 +00002791 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002792 EntryStr.str();
2793
2794 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002795 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002796 ExitStr.str();
2797 } else
2798 ExitName = "FunctionExit";
2799
2800 return EntryName + "---" + ExitName;
2801}
2802
Tobias Grosser74394f02013-01-14 22:40:23 +00002803__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002804__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002805 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002806}
2807
Tobias Grossere86109f2013-10-29 21:05:49 +00002808__isl_give isl_set *Scop::getAssumedContext() const {
2809 return isl_set_copy(AssumedContext);
2810}
2811
Johannes Doerfert43788c52015-08-20 05:58:56 +00002812__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2813 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002814 RuntimeCheckContext =
2815 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2816 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002817 return RuntimeCheckContext;
2818}
2819
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002820bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002821 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002822 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002823 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2824 isl_set_free(RuntimeCheckContext);
2825 return IsFeasible;
2826}
2827
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002828void Scop::addAssumption(__isl_take isl_set *Set) {
2829 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002830 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002831}
2832
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002833__isl_give isl_set *Scop::getBoundaryContext() const {
2834 return isl_set_copy(BoundaryContext);
2835}
2836
Tobias Grosser75805372011-04-29 06:27:02 +00002837void Scop::printContext(raw_ostream &OS) const {
2838 OS << "Context:\n";
2839
2840 if (!Context) {
2841 OS.indent(4) << "n/a\n\n";
2842 return;
2843 }
2844
2845 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002846
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002847 OS.indent(4) << "Assumed Context:\n";
2848 if (!AssumedContext) {
2849 OS.indent(4) << "n/a\n\n";
2850 return;
2851 }
2852
2853 OS.indent(4) << getAssumedContextStr() << "\n";
2854
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002855 OS.indent(4) << "Boundary Context:\n";
2856 if (!BoundaryContext) {
2857 OS.indent(4) << "n/a\n\n";
2858 return;
2859 }
2860
2861 OS.indent(4) << getBoundaryContextStr() << "\n";
2862
Tobias Grosser083d3d32014-06-28 08:59:45 +00002863 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002864 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002865 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2866 }
Tobias Grosser75805372011-04-29 06:27:02 +00002867}
2868
Johannes Doerfertb164c792014-09-18 11:17:17 +00002869void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002870 int noOfGroups = 0;
2871 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002872 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002873 noOfGroups += 1;
2874 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002875 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002876 }
2877
Tobias Grosserbb853c22015-07-25 12:31:03 +00002878 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002879 if (MinMaxAliasGroups.empty()) {
2880 OS.indent(8) << "n/a\n";
2881 return;
2882 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002883
Tobias Grosserbb853c22015-07-25 12:31:03 +00002884 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002885
2886 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002887 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002888 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002889 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002890 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2891 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002892 }
2893 OS << " ]]\n";
2894 }
2895
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002896 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002897 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002898 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002899 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002900 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2901 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002902 }
2903 OS << " ]]\n";
2904 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002905 }
2906}
2907
Tobias Grosser75805372011-04-29 06:27:02 +00002908void Scop::printStatements(raw_ostream &OS) const {
2909 OS << "Statements {\n";
2910
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002911 for (const ScopStmt &Stmt : *this)
2912 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002913
2914 OS.indent(4) << "}\n";
2915}
2916
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002917void Scop::printArrayInfo(raw_ostream &OS) const {
2918 OS << "Arrays {\n";
2919
Tobias Grosserab671442015-05-23 05:58:27 +00002920 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002921 Array.second->print(OS);
2922
2923 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002924
2925 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2926
2927 for (auto &Array : arrays())
2928 Array.second->print(OS, /* SizeAsPwAff */ true);
2929
2930 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002931}
2932
Tobias Grosser75805372011-04-29 06:27:02 +00002933void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002934 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2935 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002936 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002937 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002938 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002939 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002940 const auto &MAs = std::get<1>(IAClass);
2941 if (MAs.empty()) {
2942 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002943 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002944 MAs.front()->print(OS);
2945 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002946 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002947 }
2948 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002949 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002950 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002951 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002952 printStatements(OS.indent(4));
2953}
2954
2955void Scop::dump() const { print(dbgs()); }
2956
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002957isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002958
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002959__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
2960 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002961}
2962
Tobias Grosser808cd692015-07-14 09:33:13 +00002963__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002964 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002965
Tobias Grosser808cd692015-07-14 09:33:13 +00002966 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002967 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002968
2969 return Domain;
2970}
2971
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002972__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002973 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002974
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002975 for (ScopStmt &Stmt : *this) {
2976 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002977 if (!MA->isMustWrite())
2978 continue;
2979
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002980 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002981 isl_map *AccessDomain = MA->getAccessRelation();
2982 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2983 Write = isl_union_map_add_map(Write, AccessDomain);
2984 }
2985 }
2986 return isl_union_map_coalesce(Write);
2987}
2988
2989__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002990 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002991
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002992 for (ScopStmt &Stmt : *this) {
2993 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002994 if (!MA->isMayWrite())
2995 continue;
2996
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002997 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002998 isl_map *AccessDomain = MA->getAccessRelation();
2999 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3000 Write = isl_union_map_add_map(Write, AccessDomain);
3001 }
3002 }
3003 return isl_union_map_coalesce(Write);
3004}
3005
Tobias Grosser37eb4222014-02-20 21:43:54 +00003006__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003007 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003008
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003009 for (ScopStmt &Stmt : *this) {
3010 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00003011 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00003012 continue;
3013
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003014 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00003015 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00003016 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3017 Write = isl_union_map_add_map(Write, AccessDomain);
3018 }
3019 }
3020 return isl_union_map_coalesce(Write);
3021}
3022
3023__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003024 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003025
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003026 for (ScopStmt &Stmt : *this) {
3027 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00003028 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00003029 continue;
3030
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003031 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00003032 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00003033
3034 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3035 Read = isl_union_map_add_map(Read, AccessDomain);
3036 }
3037 }
3038 return isl_union_map_coalesce(Read);
3039}
3040
Tobias Grosser808cd692015-07-14 09:33:13 +00003041__isl_give isl_union_map *Scop::getSchedule() const {
3042 auto Tree = getScheduleTree();
3043 auto S = isl_schedule_get_map(Tree);
3044 isl_schedule_free(Tree);
3045 return S;
3046}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003047
Tobias Grosser808cd692015-07-14 09:33:13 +00003048__isl_give isl_schedule *Scop::getScheduleTree() const {
3049 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3050 getDomains());
3051}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003052
Tobias Grosser808cd692015-07-14 09:33:13 +00003053void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3054 auto *S = isl_schedule_from_domain(getDomains());
3055 S = isl_schedule_insert_partial_schedule(
3056 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3057 isl_schedule_free(Schedule);
3058 Schedule = S;
3059}
3060
3061void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3062 isl_schedule_free(Schedule);
3063 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003064}
3065
3066bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3067 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003068 for (ScopStmt &Stmt : *this) {
3069 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003070 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3071 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3072
3073 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3074 isl_union_set_free(StmtDomain);
3075 isl_union_set_free(NewStmtDomain);
3076 continue;
3077 }
3078
3079 Changed = true;
3080
3081 isl_union_set_free(StmtDomain);
3082 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3083
3084 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003085 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003086 isl_union_set_free(NewStmtDomain);
3087 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003088 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003089 }
3090 isl_union_set_free(Domain);
3091 return Changed;
3092}
3093
Tobias Grosser75805372011-04-29 06:27:02 +00003094ScalarEvolution *Scop::getSE() const { return SE; }
3095
Johannes Doerfertf5673802015-10-01 23:48:18 +00003096bool Scop::isIgnored(RegionNode *RN) {
3097 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser75805372011-04-29 06:27:02 +00003098
Johannes Doerfertf5673802015-10-01 23:48:18 +00003099 // Check if there are accesses contained.
3100 bool ContainsAccesses = false;
3101 if (!RN->isSubRegion())
3102 ContainsAccesses = getAccessFunctions(BB);
3103 else
3104 for (BasicBlock *RBB : RN->getNodeAs<Region>()->blocks())
3105 ContainsAccesses |= (getAccessFunctions(RBB) != nullptr);
3106 if (!ContainsAccesses)
3107 return true;
3108
3109 // Check for reachability via non-error blocks.
3110 if (!DomainMap.count(BB))
3111 return true;
3112
3113 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003114 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003115 return true;
3116
3117 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003118}
3119
Tobias Grosser808cd692015-07-14 09:33:13 +00003120struct MapToDimensionDataTy {
3121 int N;
3122 isl_union_pw_multi_aff *Res;
3123};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003124
Tobias Grosser808cd692015-07-14 09:33:13 +00003125// @brief Create a function that maps the elements of 'Set' to its N-th
3126// dimension.
3127//
3128// The result is added to 'User->Res'.
3129//
3130// @param Set The input set.
3131// @param N The dimension to map to.
3132//
3133// @returns Zero if no error occurred, non-zero otherwise.
3134static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3135 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3136 int Dim;
3137 isl_space *Space;
3138 isl_pw_multi_aff *PMA;
3139
3140 Dim = isl_set_dim(Set, isl_dim_set);
3141 Space = isl_set_get_space(Set);
3142 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3143 Dim - Data->N);
3144 if (Data->N > 1)
3145 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3146 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3147
3148 isl_set_free(Set);
3149
3150 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003151}
3152
Tobias Grosser808cd692015-07-14 09:33:13 +00003153// @brief Create a function that maps the elements of Domain to their Nth
3154// dimension.
3155//
3156// @param Domain The set of elements to map.
3157// @param N The dimension to map to.
3158static __isl_give isl_multi_union_pw_aff *
3159mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003160 if (N <= 0 || isl_union_set_is_empty(Domain)) {
3161 isl_union_set_free(Domain);
3162 return nullptr;
3163 }
3164
Tobias Grosser808cd692015-07-14 09:33:13 +00003165 struct MapToDimensionDataTy Data;
3166 isl_space *Space;
3167
3168 Space = isl_union_set_get_space(Domain);
3169 Data.N = N;
3170 Data.Res = isl_union_pw_multi_aff_empty(Space);
3171 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
3172 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
3173
3174 isl_union_set_free(Domain);
3175 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3176}
3177
Michael Kruse9d080092015-09-11 21:41:48 +00003178ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003179 ScopStmt *Stmt;
3180 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003181 Stmts.emplace_back(*this, *BB);
Tobias Grosser808cd692015-07-14 09:33:13 +00003182 Stmt = &Stmts.back();
3183 StmtMap[BB] = Stmt;
3184 } else {
3185 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003186 Stmts.emplace_back(*this, *R);
Tobias Grosser808cd692015-07-14 09:33:13 +00003187 Stmt = &Stmts.back();
3188 for (BasicBlock *BB : R->blocks())
3189 StmtMap[BB] = Stmt;
3190 }
3191 return Stmt;
3192}
3193
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003194void Scop::buildSchedule(
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003195 Region *R,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003196 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003197
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003198 if (SD.isNonAffineSubRegion(R, &getRegion())) {
Johannes Doerfertc6987c12015-09-26 13:41:43 +00003199 Loop *L = getLoopSurroundingRegion(*R, LI);
3200 auto &LSchedulePair = LoopSchedules[L];
Michael Krusecac948e2015-10-02 13:53:07 +00003201 ScopStmt *Stmt = getStmtForBasicBlock(R->getEntry());
Michael Kruseafe06702015-10-02 16:33:27 +00003202 isl_set *Domain = Stmt->getDomain();
Michael Krusecac948e2015-10-02 13:53:07 +00003203 auto *UDomain = isl_union_set_from_set(Domain);
3204 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003205 LSchedulePair.first = StmtSchedule;
3206 return;
3207 }
3208
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003209 ReversePostOrderTraversal<Region *> RTraversal(R);
3210 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00003211
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003212 if (RN->isSubRegion()) {
3213 Region *SubRegion = RN->getNodeAs<Region>();
3214 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003215 buildSchedule(SubRegion, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003216 continue;
3217 }
Tobias Grosser75805372011-04-29 06:27:02 +00003218 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003219
3220 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert30c22652015-10-18 21:17:11 +00003221 if (!getRegion().contains(L))
3222 L = getLoopSurroundingRegion(getRegion(), LI);
3223
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003224 int LD = getRelativeLoopDepth(L);
3225 auto &LSchedulePair = LoopSchedules[L];
3226 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3227
Michael Krusecac948e2015-10-02 13:53:07 +00003228 BasicBlock *BB = getRegionNodeBasicBlock(RN);
3229 ScopStmt *Stmt = getStmtForBasicBlock(BB);
3230 if (Stmt) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003231 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3232 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3233 LSchedulePair.first =
3234 combineInSequence(LSchedulePair.first, StmtSchedule);
3235 }
3236
3237 unsigned NumVisited = LSchedulePair.second;
3238 while (L && NumVisited == L->getNumBlocks()) {
3239 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
3240 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
3241 LSchedulePair.first =
3242 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
3243
3244 auto *PL = L->getParentLoop();
Johannes Doerfertdca28372015-11-03 00:28:07 +00003245
3246 // Either we have a proper loop and we also build a schedule for the
3247 // parent loop or we have a infinite loop that does not have a proper
3248 // parent loop. In the former case this conditional will be skipped, in
3249 // the latter case however we will break here as we do not build a domain
3250 // nor a schedule for a infinite loop.
3251 assert(LoopSchedules.count(PL) || LSchedulePair.first == nullptr);
3252 if (!LoopSchedules.count(PL))
3253 break;
3254
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003255 auto &PSchedulePair = LoopSchedules[PL];
3256 PSchedulePair.first =
3257 combineInSequence(PSchedulePair.first, LSchedulePair.first);
3258 PSchedulePair.second += NumVisited;
3259
3260 L = PL;
3261 NumVisited = PSchedulePair.second;
3262 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003263 }
Tobias Grosser75805372011-04-29 06:27:02 +00003264}
3265
Johannes Doerfert7c494212014-10-31 23:13:39 +00003266ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003267 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003268 if (StmtMapIt == StmtMap.end())
3269 return nullptr;
3270 return StmtMapIt->second;
3271}
3272
Johannes Doerfert96425c22015-08-30 21:13:53 +00003273int Scop::getRelativeLoopDepth(const Loop *L) const {
3274 Loop *OuterLoop =
3275 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3276 if (!OuterLoop)
3277 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003278 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3279}
3280
Michael Krused868b5d2015-09-10 15:25:24 +00003281void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003282 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003283
3284 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3285 // true, are not modeled as ordinary PHI nodes as they are not part of the
3286 // region. However, we model the operands in the predecessor blocks that are
3287 // part of the region as regular scalar accesses.
3288
3289 // If we can synthesize a PHI we can skip it, however only if it is in
3290 // the region. If it is not it can only be in the exit block of the region.
3291 // In this case we model the operands but not the PHI itself.
3292 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3293 return;
3294
3295 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3296 // detection. Hence, the PHI is a load of a new memory location in which the
3297 // incoming value was written at the end of the incoming basic block.
3298 bool OnlyNonAffineSubRegionOperands = true;
3299 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3300 Value *Op = PHI->getIncomingValue(u);
3301 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3302
3303 // Do not build scalar dependences inside a non-affine subregion.
3304 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3305 continue;
3306
3307 OnlyNonAffineSubRegionOperands = false;
3308
3309 if (!R.contains(OpBB))
3310 continue;
3311
3312 Instruction *OpI = dyn_cast<Instruction>(Op);
3313 if (OpI) {
3314 BasicBlock *OpIBB = OpI->getParent();
3315 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3316 // we have to insert a scalar dependence from the definition of OpI to
3317 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003318 if (scop->getStmtForBasicBlock(OpIBB) !=
3319 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003320 addScalarReadAccess(OpI, PHI, OpBB);
3321 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003322 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003323 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003324 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003325 }
3326
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003327 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003328 }
3329
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003330 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3331 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003332 }
3333}
3334
Michael Krused868b5d2015-09-10 15:25:24 +00003335bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3336 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003337 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3338 if (isIgnoredIntrinsic(Inst))
3339 return false;
3340
3341 bool AnyCrossStmtUse = false;
3342 BasicBlock *ParentBB = Inst->getParent();
3343
3344 for (User *U : Inst->users()) {
3345 Instruction *UI = dyn_cast<Instruction>(U);
3346
3347 // Ignore the strange user
3348 if (UI == 0)
3349 continue;
3350
3351 BasicBlock *UseParent = UI->getParent();
3352
Tobias Grosserbaffa092015-10-24 20:55:27 +00003353 // Ignore basic block local uses. A value that is defined in a scop, but
3354 // used in a PHI node in the same basic block does not count as basic block
3355 // local, as for such cases a control flow edge is passed between definition
3356 // and use.
3357 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003358 continue;
3359
Michael Krusef714d472015-11-05 13:18:43 +00003360 // Uses by PHI nodes in the entry node count as external uses in case the
3361 // use is through an incoming block that is itself not contained in the
3362 // region.
3363 if (R->getEntry() == UseParent) {
3364 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3365 bool ExternalUse = false;
3366 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3367 if (PHI->getIncomingValue(i) == Inst &&
3368 !R->contains(PHI->getIncomingBlock(i))) {
3369 ExternalUse = true;
3370 break;
3371 }
3372 }
3373
3374 if (ExternalUse) {
3375 AnyCrossStmtUse = true;
3376 continue;
3377 }
3378 }
3379 }
3380
Michael Kruse7bf39442015-09-10 12:46:52 +00003381 // Do not build scalar dependences inside a non-affine subregion.
3382 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3383 continue;
3384
Michael Kruse01cb3792015-10-17 21:07:08 +00003385 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003386 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003387 //
3388 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003389 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3390 // the control flow a different value will be assigned to the PHI node. In
3391 // case this is the case, there is no need to create an additional normal
3392 // scalar dependence. Hence, bail out before we register an "out-of-region"
3393 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003394 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3395 !R->getExitingBlock())
3396 continue;
3397
Michael Kruse7bf39442015-09-10 12:46:52 +00003398 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003399 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003400 AnyCrossStmtUse = true;
3401 continue;
3402 }
3403
3404 // If the instruction can be synthesized and the user is in the region
3405 // we do not need to add scalar dependences.
3406 if (canSynthesizeInst)
3407 continue;
3408
3409 // No need to translate these scalar dependences into polyhedral form,
3410 // because synthesizable scalars can be generated by the code generator.
3411 if (canSynthesize(UI, LI, SE, R))
3412 continue;
3413
3414 // Skip PHI nodes in the region as they handle their operands on their own.
3415 if (isa<PHINode>(UI))
3416 continue;
3417
3418 // Now U is used in another statement.
3419 AnyCrossStmtUse = true;
3420
3421 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003422 // Use the def instruction as base address of the MemoryAccess, so that it
3423 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003424 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003425 }
3426
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003427 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003428 for (Value *Op : Inst->operands()) {
3429 if (canSynthesize(Op, LI, SE, R))
3430 continue;
3431
3432 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3433 if (R->contains(OpInst))
3434 continue;
3435
3436 if (isa<Constant>(Op))
3437 continue;
3438
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003439 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003440 }
3441 }
3442
3443 return AnyCrossStmtUse;
3444}
3445
3446extern MapInsnToMemAcc InsnToMemAcc;
3447
Michael Krusee2bccbb2015-09-18 19:59:43 +00003448void ScopInfo::buildMemoryAccess(
3449 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003450 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3451 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003452 unsigned Size;
3453 Type *SizeType;
3454 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003455 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003456
3457 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3458 SizeType = Load->getType();
3459 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003460 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003461 Val = Load;
3462 } else {
3463 StoreInst *Store = cast<StoreInst>(Inst);
3464 SizeType = Store->getValueOperand()->getType();
3465 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003466 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003467 Val = Store->getValueOperand();
3468 }
3469
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003470 auto Address = getPointerOperand(*Inst);
3471
3472 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003473 const SCEVUnknown *BasePointer =
3474 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3475
3476 assert(BasePointer && "Could not find base pointer");
3477 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3478
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003479 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3480 auto NewAddress = Address;
3481 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3482 auto Src = BitCast->getOperand(0);
3483 auto SrcTy = Src->getType();
3484 auto DstTy = BitCast->getType();
3485 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3486 NewAddress = Src;
3487 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003488
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003489 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3490 std::vector<const SCEV *> Subscripts;
3491 std::vector<int> Sizes;
3492 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3493 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003494
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003495 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003496
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003497 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003498 for (auto Subscript : Subscripts) {
3499 InvariantLoadsSetTy AccessILS;
3500 AllAffineSubcripts =
3501 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3502
3503 for (LoadInst *LInst : AccessILS)
3504 if (!ScopRIL.count(LInst))
3505 AllAffineSubcripts = false;
3506
3507 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003508 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003509 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003510
3511 if (AllAffineSubcripts && Sizes.size() > 0) {
3512 for (auto V : Sizes)
3513 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3514 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003515 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003516 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003517
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003518 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3519 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003520 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003521 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003522 }
3523 }
3524
Michael Kruse7bf39442015-09-10 12:46:52 +00003525 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003526 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003527 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3528 AccItr->second.DelinearizedSubscripts,
3529 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003530 return;
3531 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003532
3533 // Check if the access depends on a loop contained in a non-affine subregion.
3534 bool isVariantInNonAffineLoop = false;
3535 if (BoxedLoops) {
3536 SetVector<const Loop *> Loops;
3537 findLoops(AccessFunction, Loops);
3538 for (const Loop *L : Loops)
3539 if (BoxedLoops->count(L))
3540 isVariantInNonAffineLoop = true;
3541 }
3542
Johannes Doerfert09e36972015-10-07 20:17:36 +00003543 InvariantLoadsSetTy AccessILS;
3544 bool IsAffine =
3545 !isVariantInNonAffineLoop &&
3546 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3547
3548 for (LoadInst *LInst : AccessILS)
3549 if (!ScopRIL.count(LInst))
3550 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003551
Michael Krusecaac2b62015-09-26 15:51:44 +00003552 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003553 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003554 const SCEV *SizeSCEV =
3555 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003556
Michael Krusee2bccbb2015-09-18 19:59:43 +00003557 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3558 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003559
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003560 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3561 ArrayRef<const SCEV *>(AccessFunction),
3562 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003563}
3564
Michael Krused868b5d2015-09-10 15:25:24 +00003565void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003566
3567 if (SD->isNonAffineSubRegion(&SR, &R)) {
3568 for (BasicBlock *BB : SR.blocks())
3569 buildAccessFunctions(R, *BB, &SR);
3570 return;
3571 }
3572
3573 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3574 if (I->isSubRegion())
3575 buildAccessFunctions(R, *I->getNodeAs<Region>());
3576 else
3577 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3578}
3579
Michael Krusecac948e2015-10-02 13:53:07 +00003580void ScopInfo::buildStmts(Region &SR) {
3581 Region *R = getRegion();
3582
3583 if (SD->isNonAffineSubRegion(&SR, R)) {
3584 scop->addScopStmt(nullptr, &SR);
3585 return;
3586 }
3587
3588 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3589 if (I->isSubRegion())
3590 buildStmts(*I->getNodeAs<Region>());
3591 else
3592 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3593}
3594
Michael Krused868b5d2015-09-10 15:25:24 +00003595void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3596 Region *NonAffineSubRegion,
3597 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003598 Loop *L = LI->getLoopFor(&BB);
3599
3600 // The set of loops contained in non-affine subregions that are part of R.
3601 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3602
Johannes Doerfert09e36972015-10-07 20:17:36 +00003603 // The set of loads that are required to be invariant.
3604 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3605
Michael Kruse7bf39442015-09-10 12:46:52 +00003606 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00003607 Instruction *Inst = &*I;
Michael Kruse7bf39442015-09-10 12:46:52 +00003608
3609 PHINode *PHI = dyn_cast<PHINode>(Inst);
3610 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003611 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003612
3613 // For the exit block we stop modeling after the last PHI node.
3614 if (!PHI && IsExitBlock)
3615 break;
3616
Johannes Doerfert09e36972015-10-07 20:17:36 +00003617 // TODO: At this point we only know that elements of ScopRIL have to be
3618 // invariant and will be hoisted for the SCoP to be processed. Though,
3619 // there might be other invariant accesses that will be hoisted and
3620 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003621 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003622 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003623
3624 if (isIgnoredIntrinsic(Inst))
3625 continue;
3626
Johannes Doerfert09e36972015-10-07 20:17:36 +00003627 // Do not build scalar dependences for required invariant loads as we will
3628 // hoist them later on anyway or drop the SCoP if we cannot.
3629 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3630 continue;
3631
Michael Kruse7bf39442015-09-10 12:46:52 +00003632 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003633 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003634 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003635 }
3636 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003637}
Michael Kruse7bf39442015-09-10 12:46:52 +00003638
Michael Kruse2d0ece92015-09-24 11:41:21 +00003639void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3640 MemoryAccess::AccessType Type,
3641 Value *BaseAddress, unsigned ElemBytes,
3642 bool Affine, Value *AccessValue,
3643 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003644 ArrayRef<const SCEV *> Sizes,
3645 MemoryAccess::AccessOrigin Origin) {
Michael Krusecac948e2015-10-02 13:53:07 +00003646 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3647
3648 // Do not create a memory access for anything not in the SCoP. It would be
3649 // ignored anyway.
3650 if (!Stmt)
3651 return;
3652
Michael Krusee2bccbb2015-09-18 19:59:43 +00003653 AccFuncSetType &AccList = AccFuncMap[BB];
Michael Krusee2bccbb2015-09-18 19:59:43 +00003654 Value *BaseAddr = BaseAddress;
3655 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3656
Michael Krusecac948e2015-10-02 13:53:07 +00003657 bool isApproximated =
3658 Stmt->isRegionStmt() && (Stmt->getRegion()->getEntry() != BB);
3659 if (isApproximated && Type == MemoryAccess::MUST_WRITE)
3660 Type = MemoryAccess::MAY_WRITE;
3661
Tobias Grosserf1bfd752015-11-05 20:15:37 +00003662 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003663 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003664 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003665}
3666
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003667void ScopInfo::addExplicitAccess(
3668 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
3669 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
3670 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
3671 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3672 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3673 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003674 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
3675 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003676}
3677void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3678 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3679 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003680 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003681}
3682void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3683 assert(!isa<PHINode>(User));
3684 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3685 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003686 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003687}
3688void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3689 BasicBlock *UserBB) {
3690 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003691 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3692 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003693}
3694void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3695 Value *IncomingValue, bool IsExitBlock) {
3696 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3697 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3698 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003699 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003700}
3701void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3702 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003703 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3704 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003705}
3706
Michael Kruse76e924d2015-09-30 09:16:07 +00003707void ScopInfo::buildScop(Region &R, DominatorTree &DT) {
Michael Kruse9d080092015-09-11 21:41:48 +00003708 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003709 scop = new Scop(R, AccFuncMap, *SD, *SE, DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003710
Michael Krusecac948e2015-10-02 13:53:07 +00003711 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003712 buildAccessFunctions(R, R);
3713
3714 // In case the region does not have an exiting block we will later (during
3715 // code generation) split the exit block. This will move potential PHI nodes
3716 // from the current exit block into the new region exiting block. Hence, PHI
3717 // nodes that are at this point not part of the region will be.
3718 // To handle these PHI nodes later we will now model their operands as scalar
3719 // accesses. Note that we do not model anything in the exit block if we have
3720 // an exiting block in the region, as there will not be any splitting later.
3721 if (!R.getExitingBlock())
3722 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3723
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003724 scop->init(*AA);
Michael Kruse7bf39442015-09-10 12:46:52 +00003725}
3726
Michael Krused868b5d2015-09-10 15:25:24 +00003727void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003728 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003729 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003730 return;
3731 }
3732
Michael Kruse9d080092015-09-11 21:41:48 +00003733 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003734}
3735
Michael Krused868b5d2015-09-10 15:25:24 +00003736void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003737 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003738 if (scop) {
3739 delete scop;
3740 scop = 0;
3741 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003742}
3743
3744//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003745ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003746 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003747 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003748}
3749
3750ScopInfo::~ScopInfo() {
3751 clear();
3752 isl_ctx_free(ctx);
3753}
3754
Tobias Grosser75805372011-04-29 06:27:02 +00003755void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00003756 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003757 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003758 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003759 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3760 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003761 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00003762 AU.setPreservesAll();
3763}
3764
3765bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003766 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003767
Michael Krused868b5d2015-09-10 15:25:24 +00003768 if (!SD->isMaxRegionInScop(*R))
3769 return false;
3770
3771 Function *F = R->getEntry()->getParent();
3772 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3773 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3774 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3775 TD = &F->getParent()->getDataLayout();
3776 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Krused868b5d2015-09-10 15:25:24 +00003777
Michael Kruse76e924d2015-09-30 09:16:07 +00003778 buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00003779
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003780 DEBUG(scop->print(dbgs()));
3781
Michael Kruseafe06702015-10-02 16:33:27 +00003782 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003783 delete scop;
3784 scop = nullptr;
3785 return false;
3786 }
3787
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003788 // Statistics.
3789 ++ScopFound;
3790 if (scop->getMaxLoopDepth() > 0)
3791 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00003792 return false;
3793}
3794
3795char ScopInfo::ID = 0;
3796
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003797Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3798
Tobias Grosser73600b82011-10-08 00:30:40 +00003799INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3800 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003801 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003802INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00003803INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003804INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003805INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003806INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003807INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003808INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3809 "Polly - Create polyhedral description of Scops", false,
3810 false)