blob: 3e3afa58c5bc3535e8421edcc78e719cd71fba5d [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
2//
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
Sebastian Pop27c10c62013-03-22 22:07:43 +000020#include "polly/CodeGen/BlockGenerators.h"
Tobias Grosser75805372011-04-29 06:27:02 +000021#include "polly/LinkAllPasses.h"
Sebastian Pop27c10c62013-03-22 22:07:43 +000022#include "polly/ScopInfo.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000023#include "polly/Options.h"
Tobias Grosser75805372011-04-29 06:27:02 +000024#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000025#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000026#include "polly/Support/ScopHelper.h"
Sebastian Pop27c10c62013-03-22 22:07:43 +000027#include "polly/TempScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000028#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000029#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000030#include "llvm/ADT/StringExtras.h"
Tobias Grosser83628182013-05-07 08:11:54 +000031#include "llvm/Analysis/LoopInfo.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000032#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser83628182013-05-07 08:11:54 +000033#include "llvm/Analysis/RegionIterator.h"
34#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000035#include "llvm/Support/Debug.h"
36
37#include "isl/constraint.h"
38#include "isl/set.h"
39#include "isl/map.h"
Tobias Grosser37eb4222014-02-20 21:43:54 +000040#include "isl/union_map.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000041#include "isl/aff.h"
42#include "isl/printer.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000043#include "isl/local_space.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000044#include "isl/options.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000045#include "isl/val.h"
Chandler Carruth95fef942014-04-22 03:30:19 +000046
Tobias Grosser75805372011-04-29 06:27:02 +000047#include <sstream>
48#include <string>
49#include <vector>
50
51using namespace llvm;
52using namespace polly;
53
Chandler Carruth95fef942014-04-22 03:30:19 +000054#define DEBUG_TYPE "polly-scops"
55
Tobias Grosser74394f02013-01-14 22:40:23 +000056STATISTIC(ScopFound, "Number of valid Scops");
57STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000058
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000059// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000060// operations can overflow easily. Additive reductions and bit operations
61// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000062static cl::opt<bool> DisableMultiplicativeReductions(
63 "polly-disable-multiplicative-reductions",
64 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
65 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000066
Johannes Doerfert9143d672014-09-27 11:02:39 +000067static cl::opt<unsigned> RunTimeChecksMaxParameters(
68 "polly-rtc-max-parameters",
69 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
70 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
71
Tobias Grosser0695ee42013-09-17 03:30:31 +000072/// Translate a 'const SCEV *' expression in an isl_pw_aff.
Tobias Grosserabfbe632013-02-05 12:09:06 +000073struct SCEVAffinator : public SCEVVisitor<SCEVAffinator, isl_pw_aff *> {
Tobias Grosser0695ee42013-09-17 03:30:31 +000074public:
Tobias Grosser0695ee42013-09-17 03:30:31 +000075 /// @brief Translate a 'const SCEV *' to an isl_pw_aff.
76 ///
77 /// @param Stmt The location at which the scalar evolution expression
78 /// is evaluated.
79 /// @param Expr The expression that is translated.
80 static __isl_give isl_pw_aff *getPwAff(ScopStmt *Stmt, const SCEV *Expr);
81
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000082private:
Tobias Grosser3cc99742012-06-06 16:33:15 +000083 isl_ctx *Ctx;
Tobias Grosserf5338802011-10-06 00:03:35 +000084 int NbLoopSpaces;
Tobias Grosser3cc99742012-06-06 16:33:15 +000085 const Scop *S;
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000086
Tobias Grosser0695ee42013-09-17 03:30:31 +000087 SCEVAffinator(const ScopStmt *Stmt);
88 int getLoopDepth(const Loop *L);
Tobias Grosser60b54f12011-11-08 15:41:28 +000089
Tobias Grosser0695ee42013-09-17 03:30:31 +000090 __isl_give isl_pw_aff *visit(const SCEV *Expr);
91 __isl_give isl_pw_aff *visitConstant(const SCEVConstant *Expr);
92 __isl_give isl_pw_aff *visitTruncateExpr(const SCEVTruncateExpr *Expr);
93 __isl_give isl_pw_aff *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr);
94 __isl_give isl_pw_aff *visitSignExtendExpr(const SCEVSignExtendExpr *Expr);
95 __isl_give isl_pw_aff *visitAddExpr(const SCEVAddExpr *Expr);
96 __isl_give isl_pw_aff *visitMulExpr(const SCEVMulExpr *Expr);
97 __isl_give isl_pw_aff *visitUDivExpr(const SCEVUDivExpr *Expr);
98 __isl_give isl_pw_aff *visitAddRecExpr(const SCEVAddRecExpr *Expr);
99 __isl_give isl_pw_aff *visitSMaxExpr(const SCEVSMaxExpr *Expr);
100 __isl_give isl_pw_aff *visitUMaxExpr(const SCEVUMaxExpr *Expr);
101 __isl_give isl_pw_aff *visitUnknown(const SCEVUnknown *Expr);
Tobias Grosser60b54f12011-11-08 15:41:28 +0000102
Tobias Grosser0695ee42013-09-17 03:30:31 +0000103 friend struct SCEVVisitor<SCEVAffinator, isl_pw_aff *>;
104};
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000105
Tobias Grosser0695ee42013-09-17 03:30:31 +0000106SCEVAffinator::SCEVAffinator(const ScopStmt *Stmt)
107 : Ctx(Stmt->getIslCtx()), NbLoopSpaces(Stmt->getNumIterators()),
108 S(Stmt->getParent()) {}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000109
Tobias Grosser0695ee42013-09-17 03:30:31 +0000110__isl_give isl_pw_aff *SCEVAffinator::getPwAff(ScopStmt *Stmt,
111 const SCEV *Scev) {
112 Scop *S = Stmt->getParent();
113 const Region *Reg = &S->getRegion();
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000114
Tobias Grosser0695ee42013-09-17 03:30:31 +0000115 S->addParams(getParamsInAffineExpr(Reg, Scev, *S->getSE()));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000116
Tobias Grosser0695ee42013-09-17 03:30:31 +0000117 SCEVAffinator Affinator(Stmt);
118 return Affinator.visit(Scev);
119}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000120
Tobias Grosser0695ee42013-09-17 03:30:31 +0000121__isl_give isl_pw_aff *SCEVAffinator::visit(const SCEV *Expr) {
122 // In case the scev is a valid parameter, we do not further analyze this
123 // expression, but create a new parameter in the isl_pw_aff. This allows us
124 // to treat subexpressions that we cannot translate into an piecewise affine
125 // expression, as constant parameters of the piecewise affine expression.
126 if (isl_id *Id = S->getIdForParam(Expr)) {
127 isl_space *Space = isl_space_set_alloc(Ctx, 1, NbLoopSpaces);
128 Space = isl_space_set_dim_id(Space, isl_dim_param, 0, Id);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000129
Tobias Grosser0695ee42013-09-17 03:30:31 +0000130 isl_set *Domain = isl_set_universe(isl_space_copy(Space));
131 isl_aff *Affine = isl_aff_zero_on_domain(isl_local_space_from_space(Space));
132 Affine = isl_aff_add_coefficient_si(Affine, isl_dim_param, 0, 1);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000133
134 return isl_pw_aff_alloc(Domain, Affine);
135 }
136
Tobias Grosser0695ee42013-09-17 03:30:31 +0000137 return SCEVVisitor<SCEVAffinator, isl_pw_aff *>::visit(Expr);
138}
139
Tobias Grosser0d170132013-10-03 13:09:19 +0000140__isl_give isl_pw_aff *SCEVAffinator::visitConstant(const SCEVConstant *Expr) {
Tobias Grosser0695ee42013-09-17 03:30:31 +0000141 ConstantInt *Value = Expr->getValue();
142 isl_val *v;
143
144 // LLVM does not define if an integer value is interpreted as a signed or
145 // unsigned value. Hence, without further information, it is unknown how
146 // this value needs to be converted to GMP. At the moment, we only support
147 // signed operations. So we just interpret it as signed. Later, there are
148 // two options:
149 //
150 // 1. We always interpret any value as signed and convert the values on
151 // demand.
152 // 2. We pass down the signedness of the calculation and use it to interpret
153 // this constant correctly.
154 v = isl_valFromAPInt(Ctx, Value->getValue(), /* isSigned */ true);
155
156 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
Johannes Doerfert9c147372014-11-19 15:36:59 +0000157 isl_local_space *ls = isl_local_space_from_space(Space);
158 return isl_pw_aff_from_aff(isl_aff_val_on_domain(ls, v));
Tobias Grosser0695ee42013-09-17 03:30:31 +0000159}
160
161__isl_give isl_pw_aff *
162SCEVAffinator::visitTruncateExpr(const SCEVTruncateExpr *Expr) {
163 llvm_unreachable("SCEVTruncateExpr not yet supported");
164}
165
166__isl_give isl_pw_aff *
167SCEVAffinator::visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
168 llvm_unreachable("SCEVZeroExtendExpr not yet supported");
169}
170
171__isl_give isl_pw_aff *
172SCEVAffinator::visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
173 // Assuming the value is signed, a sign extension is basically a noop.
174 // TODO: Reconsider this as soon as we support unsigned values.
175 return visit(Expr->getOperand());
176}
177
178__isl_give isl_pw_aff *SCEVAffinator::visitAddExpr(const SCEVAddExpr *Expr) {
179 isl_pw_aff *Sum = visit(Expr->getOperand(0));
180
181 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
182 isl_pw_aff *NextSummand = visit(Expr->getOperand(i));
183 Sum = isl_pw_aff_add(Sum, NextSummand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000184 }
185
Tobias Grosser0695ee42013-09-17 03:30:31 +0000186 // TODO: Check for NSW and NUW.
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000187
Tobias Grosser0695ee42013-09-17 03:30:31 +0000188 return Sum;
189}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000190
Tobias Grosser0695ee42013-09-17 03:30:31 +0000191__isl_give isl_pw_aff *SCEVAffinator::visitMulExpr(const SCEVMulExpr *Expr) {
192 isl_pw_aff *Product = visit(Expr->getOperand(0));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000193
Tobias Grosser0695ee42013-09-17 03:30:31 +0000194 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
195 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
196
197 if (!isl_pw_aff_is_cst(Product) && !isl_pw_aff_is_cst(NextOperand)) {
198 isl_pw_aff_free(Product);
199 isl_pw_aff_free(NextOperand);
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000200 return nullptr;
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000201 }
202
Tobias Grosser0695ee42013-09-17 03:30:31 +0000203 Product = isl_pw_aff_mul(Product, NextOperand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000204 }
205
Tobias Grosser0695ee42013-09-17 03:30:31 +0000206 // TODO: Check for NSW and NUW.
207 return Product;
208}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000209
Tobias Grosser0695ee42013-09-17 03:30:31 +0000210__isl_give isl_pw_aff *SCEVAffinator::visitUDivExpr(const SCEVUDivExpr *Expr) {
211 llvm_unreachable("SCEVUDivExpr not yet supported");
212}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000213
Tobias Grosser0695ee42013-09-17 03:30:31 +0000214__isl_give isl_pw_aff *
215SCEVAffinator::visitAddRecExpr(const SCEVAddRecExpr *Expr) {
216 assert(Expr->isAffine() && "Only affine AddRecurrences allowed");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000217
Tobias Grosser0695ee42013-09-17 03:30:31 +0000218 // Directly generate isl_pw_aff for Expr if 'start' is zero.
219 if (Expr->getStart()->isZero()) {
220 assert(S->getRegion().contains(Expr->getLoop()) &&
221 "Scop does not contain the loop referenced in this AddRec");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000222
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000223 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser0695ee42013-09-17 03:30:31 +0000224 isl_pw_aff *Step = visit(Expr->getOperand(1));
225 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
226 isl_local_space *LocalSpace = isl_local_space_from_space(Space);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000227
Tobias Grosser0695ee42013-09-17 03:30:31 +0000228 int loopDimension = getLoopDepth(Expr->getLoop());
229
230 isl_aff *LAff = isl_aff_set_coefficient_si(
231 isl_aff_zero_on_domain(LocalSpace), isl_dim_in, loopDimension, 1);
232 isl_pw_aff *LPwAff = isl_pw_aff_from_aff(LAff);
233
234 // TODO: Do we need to check for NSW and NUW?
235 return isl_pw_aff_add(Start, isl_pw_aff_mul(Step, LPwAff));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000236 }
237
Tobias Grosser0695ee42013-09-17 03:30:31 +0000238 // Translate AddRecExpr from '{start, +, inc}' into 'start + {0, +, inc}'
239 // if 'start' is not zero.
240 ScalarEvolution &SE = *S->getSE();
241 const SCEV *ZeroStartExpr = SE.getAddRecExpr(
242 SE.getConstant(Expr->getStart()->getType(), 0),
243 Expr->getStepRecurrence(SE), Expr->getLoop(), SCEV::FlagAnyWrap);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000244
Tobias Grosser0695ee42013-09-17 03:30:31 +0000245 isl_pw_aff *ZeroStartResult = visit(ZeroStartExpr);
246 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000247
Tobias Grosser0695ee42013-09-17 03:30:31 +0000248 return isl_pw_aff_add(ZeroStartResult, Start);
249}
250
251__isl_give isl_pw_aff *SCEVAffinator::visitSMaxExpr(const SCEVSMaxExpr *Expr) {
252 isl_pw_aff *Max = visit(Expr->getOperand(0));
253
254 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
255 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
256 Max = isl_pw_aff_max(Max, NextOperand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000257 }
258
Tobias Grosser0695ee42013-09-17 03:30:31 +0000259 return Max;
260}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000261
Tobias Grosser0695ee42013-09-17 03:30:31 +0000262__isl_give isl_pw_aff *SCEVAffinator::visitUMaxExpr(const SCEVUMaxExpr *Expr) {
263 llvm_unreachable("SCEVUMaxExpr not yet supported");
264}
265
266__isl_give isl_pw_aff *SCEVAffinator::visitUnknown(const SCEVUnknown *Expr) {
Tobias Grosserf4daf342014-08-16 09:08:55 +0000267 llvm_unreachable("Unknowns are always parameters");
Tobias Grosser0695ee42013-09-17 03:30:31 +0000268}
269
270int SCEVAffinator::getLoopDepth(const Loop *L) {
271 Loop *outerLoop = S->getRegion().outermostLoopInRegion(const_cast<Loop *>(L));
272 assert(outerLoop && "Scop does not contain this loop");
273 return L->getLoopDepth() - outerLoop->getLoopDepth();
274}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000275
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000276ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *AccessType, isl_ctx *Ctx,
277 const SmallVector<const SCEV *, 4> &DimensionSizes)
278 : BasePtr(BasePtr), AccessType(AccessType), DimensionSizes(DimensionSizes) {
279 const std::string BasePtrName = getIslCompatibleName("MemRef_", BasePtr, "");
280 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
281}
282
283ScopArrayInfo::~ScopArrayInfo() { isl_id_free(Id); }
284
285isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
286
287void ScopArrayInfo::dump() const { print(errs()); }
288
289void ScopArrayInfo::print(raw_ostream &OS) const {
290 OS << "ScopArrayInfo:\n";
291 OS << " Base: " << *getBasePtr() << "\n";
292 OS << " Type: " << *getType() << "\n";
293 OS << " Dimension Sizes:\n";
294 for (unsigned u = 0; u < getNumberOfDimensions(); u++)
295 OS << " " << u << ") " << *DimensionSizes[u] << "\n";
296 OS << "\n";
297}
298
299const ScopArrayInfo *
300ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
301 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
302 assert(Id && "Output dimension didn't have an ID");
303 return getFromId(Id);
304}
305
306const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
307 void *User = isl_id_get_user(Id);
308 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
309 isl_id_free(Id);
310 return SAI;
311}
312
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000313const std::string
314MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
315 switch (RT) {
316 case MemoryAccess::RT_NONE:
317 llvm_unreachable("Requested a reduction operator string for a memory "
318 "access which isn't a reduction");
319 case MemoryAccess::RT_ADD:
320 return "+";
321 case MemoryAccess::RT_MUL:
322 return "*";
323 case MemoryAccess::RT_BOR:
324 return "|";
325 case MemoryAccess::RT_BXOR:
326 return "^";
327 case MemoryAccess::RT_BAND:
328 return "&";
329 }
330 llvm_unreachable("Unknown reduction type");
331 return "";
332}
333
Johannes Doerfertf6183392014-07-01 20:52:51 +0000334/// @brief Return the reduction type for a given binary operator
335static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
336 const Instruction *Load) {
337 if (!BinOp)
338 return MemoryAccess::RT_NONE;
339 switch (BinOp->getOpcode()) {
340 case Instruction::FAdd:
341 if (!BinOp->hasUnsafeAlgebra())
342 return MemoryAccess::RT_NONE;
343 // Fall through
344 case Instruction::Add:
345 return MemoryAccess::RT_ADD;
346 case Instruction::Or:
347 return MemoryAccess::RT_BOR;
348 case Instruction::Xor:
349 return MemoryAccess::RT_BXOR;
350 case Instruction::And:
351 return MemoryAccess::RT_BAND;
352 case Instruction::FMul:
353 if (!BinOp->hasUnsafeAlgebra())
354 return MemoryAccess::RT_NONE;
355 // Fall through
356 case Instruction::Mul:
357 if (DisableMultiplicativeReductions)
358 return MemoryAccess::RT_NONE;
359 return MemoryAccess::RT_MUL;
360 default:
361 return MemoryAccess::RT_NONE;
362 }
363}
Tobias Grosser75805372011-04-29 06:27:02 +0000364//===----------------------------------------------------------------------===//
365
366MemoryAccess::~MemoryAccess() {
Tobias Grosser54a86e62011-08-18 06:31:46 +0000367 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000368 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000369}
370
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000371static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
372 switch (Access.getType()) {
373 case IRAccess::READ:
374 return MemoryAccess::READ;
375 case IRAccess::MUST_WRITE:
376 return MemoryAccess::MUST_WRITE;
377 case IRAccess::MAY_WRITE:
378 return MemoryAccess::MAY_WRITE;
379 }
380 llvm_unreachable("Unknown IRAccess type!");
381}
382
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000383const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
384 isl_id *ArrayId = getArrayId();
385 void *User = isl_id_get_user(ArrayId);
386 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
387 isl_id_free(ArrayId);
388 return SAI;
389}
390
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000391isl_id *MemoryAccess::getArrayId() const {
392 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
393}
394
Johannes Doerferta99130f2014-10-13 12:58:03 +0000395isl_pw_multi_aff *
396MemoryAccess::applyScheduleToAccessRelation(isl_union_map *USchedule) const {
397 isl_map *Schedule, *ScheduledAccRel;
398 isl_union_set *UDomain;
399
400 UDomain = isl_union_set_from_set(getStatement()->getDomain());
401 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
402 Schedule = isl_map_from_union_map(USchedule);
403 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
404 return isl_pw_multi_aff_from_map(ScheduledAccRel);
405}
406
407isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000408 return isl_map_copy(AccessRelation);
409}
410
Johannes Doerferta99130f2014-10-13 12:58:03 +0000411std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000412 return stringFromIslObj(AccessRelation);
413}
414
Johannes Doerferta99130f2014-10-13 12:58:03 +0000415__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000416 return isl_map_get_space(AccessRelation);
417}
418
Tobias Grosser5d453812011-10-06 00:04:11 +0000419isl_map *MemoryAccess::getNewAccessRelation() const {
420 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000421}
422
423isl_basic_map *MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000424 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000425 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000426
Tobias Grosser084d8f72012-05-29 09:29:44 +0000427 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000428 isl_basic_set_universe(Statement->getDomainSpace()),
429 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000430}
431
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000432// Formalize no out-of-bound access assumption
433//
434// When delinearizing array accesses we optimistically assume that the
435// delinearized accesses do not access out of bound locations (the subscript
436// expression of each array evaluates for each statement instance that is
437// executed to a value that is larger than zero and strictly smaller than the
438// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000439// dimension for which we do not need to assume any upper bound. At this point
440// we formalize this assumption to ensure that at code generation time the
441// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000442//
443// To find the set of constraints necessary to avoid out of bound accesses, we
444// first build the set of data locations that are not within array bounds. We
445// then apply the reverse access relation to obtain the set of iterations that
446// may contain invalid accesses and reduce this set of iterations to the ones
447// that are actually executed by intersecting them with the domain of the
448// statement. If we now project out all loop dimensions, we obtain a set of
449// parameters that may cause statement instances to be executed that may
450// possibly yield out of bound memory accesses. The complement of these
451// constraints is the set of constraints that needs to be assumed to ensure such
452// statement instances are never executed.
453void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000454 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000455 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000456 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000457 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
458 isl_pw_aff *Var =
459 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
460 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
461
462 isl_set *DimOutside;
463
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000464 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
465 isl_pw_aff *SizeE = SCEVAffinator::getPwAff(Statement, Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000466
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000467 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
468 Statement->getNumIterators());
469 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
470 isl_space_dim(Space, isl_dim_set));
471 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
472 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000473
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000474 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000475
476 Outside = isl_set_union(Outside, DimOutside);
477 }
478
479 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
480 Outside = isl_set_intersect(Outside, Statement->getDomain());
481 Outside = isl_set_params(Outside);
482 Outside = isl_set_complement(Outside);
483 Statement->getParent()->addAssumption(Outside);
484 isl_space_free(Space);
485}
486
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000487MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000488 ScopStmt *Statement, const ScopArrayInfo *SAI)
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000489 : AccType(getMemoryAccessType(Access)), Statement(Statement), Inst(AccInst),
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000490 newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000491
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000492 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000493 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000494 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000495
496 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000497
Tobias Grossera1879642011-12-20 10:43:14 +0000498 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000499 // We overapproximate non-affine accesses with a possible access to the
500 // whole array. For read accesses it does not make a difference, if an
501 // access must or may happen. However, for write accesses it is important to
502 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000503 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000504 AccessRelation =
505 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000506 return;
507 }
508
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000509 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000510 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000511
Tobias Grosser79baa212014-04-10 08:38:02 +0000512 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Sebastian Pop18016682014-04-08 21:20:44 +0000513 isl_pw_aff *Affine =
514 SCEVAffinator::getPwAff(Statement, Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000515
Sebastian Pop422e33f2014-06-03 18:16:31 +0000516 if (Size == 1) {
517 // For the non delinearized arrays, divide the access function of the last
518 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000519 //
520 // A stride one array access in C expressed as A[i] is expressed in
521 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
522 // two subsequent values of 'i' index two values that are stored next to
523 // each other in memory. By this division we make this characteristic
524 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000525 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000526 Affine = isl_pw_aff_scale_down_val(Affine, v);
527 }
528
529 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
530
Tobias Grosser79baa212014-04-10 08:38:02 +0000531 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000532 }
533
Tobias Grosser79baa212014-04-10 08:38:02 +0000534 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000535 AccessRelation = isl_map_set_tuple_id(
536 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000537 AccessRelation =
538 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
539
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000540 assumeNoOutOfBound(Access);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000541 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000542}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000543
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000544void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000545 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000546 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000547}
548
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000549const std::string MemoryAccess::getReductionOperatorStr() const {
550 return MemoryAccess::getReductionOperatorStr(getReductionType());
551}
552
Johannes Doerfertf6183392014-07-01 20:52:51 +0000553raw_ostream &polly::operator<<(raw_ostream &OS,
554 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000555 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000556 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000557 else
558 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000559 return OS;
560}
561
Tobias Grosser75805372011-04-29 06:27:02 +0000562void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000563 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000564 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000565 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000566 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000567 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000568 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000569 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000570 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000571 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000572 break;
573 }
Johannes Doerfertf6183392014-07-01 20:52:51 +0000574 OS << "[Reduction Type: " << getReductionType() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000575 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000576}
577
Tobias Grosser74394f02013-01-14 22:40:23 +0000578void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000579
580// Create a map in the size of the provided set domain, that maps from the
581// one element of the provided set domain to another element of the provided
582// set domain.
583// The mapping is limited to all points that are equal in all but the last
584// dimension and for which the last dimension of the input is strict smaller
585// than the last dimension of the output.
586//
587// getEqualAndLarger(set[i0, i1, ..., iX]):
588//
589// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
590// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
591//
Tobias Grosserf5338802011-10-06 00:03:35 +0000592static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000593 isl_space *Space = isl_space_map_from_set(setDomain);
594 isl_map *Map = isl_map_universe(isl_space_copy(Space));
595 isl_local_space *MapLocalSpace = isl_local_space_from_space(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000596 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000597
598 // Set all but the last dimension to be equal for the input and output
599 //
600 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
601 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000602 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000603 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000604
605 // Set the last dimension of the input to be strict smaller than the
606 // last dimension of the output.
607 //
608 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
609 //
Tobias Grosseredab1352013-06-21 06:41:31 +0000610 isl_val *v;
611 isl_ctx *Ctx = isl_map_get_ctx(Map);
Tobias Grosserf5338802011-10-06 00:03:35 +0000612 isl_constraint *c = isl_inequality_alloc(isl_local_space_copy(MapLocalSpace));
Tobias Grosseredab1352013-06-21 06:41:31 +0000613 v = isl_val_int_from_si(Ctx, -1);
614 c = isl_constraint_set_coefficient_val(c, isl_dim_in, lastDimension, v);
615 v = isl_val_int_from_si(Ctx, 1);
616 c = isl_constraint_set_coefficient_val(c, isl_dim_out, lastDimension, v);
617 v = isl_val_int_from_si(Ctx, -1);
618 c = isl_constraint_set_constant_val(c, v);
Tobias Grosser75805372011-04-29 06:27:02 +0000619
Tobias Grosserc327932c2012-02-01 14:23:36 +0000620 Map = isl_map_add_constraint(Map, c);
Tobias Grosser75805372011-04-29 06:27:02 +0000621
Tobias Grosser23b36662011-10-17 08:32:36 +0000622 isl_local_space_free(MapLocalSpace);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000623 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000624}
625
Sebastian Popa00a0292012-12-18 07:46:06 +0000626isl_set *MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000627 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000628 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000629 isl_space *Space = isl_space_range(isl_map_get_space(S));
630 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000631
Sebastian Popa00a0292012-12-18 07:46:06 +0000632 S = isl_map_reverse(S);
633 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000634
Sebastian Popa00a0292012-12-18 07:46:06 +0000635 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
636 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
637 NextScatt = isl_map_apply_domain(NextScatt, S);
638 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000639
Sebastian Popa00a0292012-12-18 07:46:06 +0000640 isl_set *Deltas = isl_map_deltas(NextScatt);
641 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000642}
643
Sebastian Popa00a0292012-12-18 07:46:06 +0000644bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000645 int StrideWidth) const {
646 isl_set *Stride, *StrideX;
647 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000648
Sebastian Popa00a0292012-12-18 07:46:06 +0000649 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000650 StrideX = isl_set_universe(isl_set_get_space(Stride));
651 StrideX = isl_set_fix_si(StrideX, isl_dim_set, 0, StrideWidth);
652 IsStrideX = isl_set_is_equal(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000653
Tobias Grosser28dd4862012-01-24 16:42:16 +0000654 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000655 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000656
Tobias Grosser28dd4862012-01-24 16:42:16 +0000657 return IsStrideX;
658}
659
Sebastian Popa00a0292012-12-18 07:46:06 +0000660bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
661 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000662}
663
Tobias Grosser79baa212014-04-10 08:38:02 +0000664bool MemoryAccess::isScalar() const {
665 return isl_map_n_out(AccessRelation) == 0;
666}
667
Sebastian Popa00a0292012-12-18 07:46:06 +0000668bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
669 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000670}
671
Tobias Grosser5d453812011-10-06 00:04:11 +0000672void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000673 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000674 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000675}
Tobias Grosser75805372011-04-29 06:27:02 +0000676
677//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000678
Tobias Grosser74394f02013-01-14 22:40:23 +0000679isl_map *ScopStmt::getScattering() const { return isl_map_copy(Scattering); }
Tobias Grossercf3942d2011-10-06 00:04:05 +0000680
Tobias Grosser37eb4222014-02-20 21:43:54 +0000681void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
682 assert(isl_set_is_subset(NewDomain, Domain) &&
683 "New domain is not a subset of old domain!");
684 isl_set_free(Domain);
685 Domain = NewDomain;
686 Scattering = isl_map_intersect_domain(Scattering, isl_set_copy(Domain));
687}
688
Tobias Grossercf3942d2011-10-06 00:04:05 +0000689void ScopStmt::setScattering(isl_map *NewScattering) {
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000690 assert(NewScattering && "New scattering is nullptr");
Tobias Grosserb76f38532011-08-20 11:11:25 +0000691 isl_map_free(Scattering);
Tobias Grossercf3942d2011-10-06 00:04:05 +0000692 Scattering = NewScattering;
Tobias Grosserb76f38532011-08-20 11:11:25 +0000693}
694
Tobias Grosser75805372011-04-29 06:27:02 +0000695void ScopStmt::buildScattering(SmallVectorImpl<unsigned> &Scatter) {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000696 unsigned NbIterators = getNumIterators();
697 unsigned NbScatteringDims = Parent.getMaxLoopDepth() * 2 + 1;
698
Tobias Grosser084d8f72012-05-29 09:29:44 +0000699 isl_space *Space = isl_space_set_alloc(getIslCtx(), 0, NbScatteringDims);
Tobias Grosserf5338802011-10-06 00:03:35 +0000700 Space = isl_space_set_tuple_name(Space, isl_dim_out, "scattering");
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000701
Tobias Grosser084d8f72012-05-29 09:29:44 +0000702 Scattering = isl_map_from_domain_and_range(isl_set_universe(getDomainSpace()),
703 isl_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000704
705 // Loop dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000706 for (unsigned i = 0; i < NbIterators; ++i)
Tobias Grosserabfbe632013-02-05 12:09:06 +0000707 Scattering =
708 isl_map_equate(Scattering, isl_dim_out, 2 * i + 1, isl_dim_in, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000709
710 // Constant dimensions
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000711 for (unsigned i = 0; i < NbIterators + 1; ++i)
712 Scattering = isl_map_fix_si(Scattering, isl_dim_out, 2 * i, Scatter[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000713
714 // Fill scattering dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000715 for (unsigned i = 2 * NbIterators + 1; i < NbScatteringDims; ++i)
716 Scattering = isl_map_fix_si(Scattering, isl_dim_out, i, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000717
Tobias Grosser37487052011-10-06 00:03:42 +0000718 Scattering = isl_map_align_params(Scattering, Parent.getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000719}
720
Johannes Doerfert75bd66e2014-10-31 23:16:02 +0000721void ScopStmt::buildAccesses(TempScop &tempScop) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000722 for (const auto &AccessPair : *tempScop.getAccessFunctions(BB)) {
723 const IRAccess &Access = AccessPair.first;
724 Instruction *AccessInst = AccessPair.second;
725
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000726 Type *AccessType = getAccessInstType(AccessInst)->getPointerTo();
727 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
728 Access.getBase(), AccessType, Access.Sizes);
729
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000730 MemAccs.push_back(new MemoryAccess(Access, AccessInst, this, SAI));
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000731
732 // We do not track locations for scalar memory accesses at the moment.
733 //
734 // We do not have a use for this information at the moment. If we need this
735 // at some point, the "instruction -> access" mapping needs to be enhanced
736 // as a single instruction could then possibly perform multiple accesses.
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000737 if (!Access.isScalar()) {
738 assert(!InstructionToAccess.count(AccessInst) &&
Tobias Grosser3fc91542014-02-20 21:43:45 +0000739 "Unexpected 1-to-N mapping on instruction to access map!");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000740 InstructionToAccess[AccessInst] = MemAccs.back();
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000741 }
Tobias Grosser75805372011-04-29 06:27:02 +0000742 }
743}
744
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000745void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000746 for (MemoryAccess *MA : *this)
747 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000748
749 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
750 Scattering = isl_map_align_params(Scattering, Parent.getParamSpace());
751}
752
Tobias Grosser65b00582011-11-08 15:41:19 +0000753__isl_give isl_set *ScopStmt::buildConditionSet(const Comparison &Comp) {
Tobias Grossera601fbd2011-11-09 22:34:44 +0000754 isl_pw_aff *L = SCEVAffinator::getPwAff(this, Comp.getLHS());
755 isl_pw_aff *R = SCEVAffinator::getPwAff(this, Comp.getRHS());
Tobias Grosser75805372011-04-29 06:27:02 +0000756
Tobias Grosserd2795d02011-08-18 07:51:40 +0000757 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000758 case ICmpInst::ICMP_EQ:
Tobias Grosser048c8792011-10-23 20:59:20 +0000759 return isl_pw_aff_eq_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000760 case ICmpInst::ICMP_NE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000761 return isl_pw_aff_ne_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000762 case ICmpInst::ICMP_SLT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000763 return isl_pw_aff_lt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000764 case ICmpInst::ICMP_SLE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000765 return isl_pw_aff_le_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000766 case ICmpInst::ICMP_SGT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000767 return isl_pw_aff_gt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000768 case ICmpInst::ICMP_SGE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000769 return isl_pw_aff_ge_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000770 case ICmpInst::ICMP_ULT:
771 case ICmpInst::ICMP_UGT:
772 case ICmpInst::ICMP_ULE:
Tobias Grosser75805372011-04-29 06:27:02 +0000773 case ICmpInst::ICMP_UGE:
Tobias Grosserd2795d02011-08-18 07:51:40 +0000774 llvm_unreachable("Unsigned comparisons not yet supported");
Tobias Grosser75805372011-04-29 06:27:02 +0000775 default:
776 llvm_unreachable("Non integer predicate not supported");
777 }
Tobias Grosser75805372011-04-29 06:27:02 +0000778}
779
Tobias Grossere19661e2011-10-07 08:46:57 +0000780__isl_give isl_set *ScopStmt::addLoopBoundsToDomain(__isl_take isl_set *Domain,
Tobias Grosser60b54f12011-11-08 15:41:28 +0000781 TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000782 isl_space *Space;
783 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000784
Tobias Grossere19661e2011-10-07 08:46:57 +0000785 Space = isl_set_get_space(Domain);
786 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000787
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000788 ScalarEvolution *SE = getParent()->getSE();
Tobias Grosser75805372011-04-29 06:27:02 +0000789 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000790 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000791 isl_pw_aff *IV =
792 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000793
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000794 // 0 <= IV.
795 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
796 Domain = isl_set_intersect(Domain, LowerBound);
797
798 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000799 const Loop *L = getLoopForDimension(i);
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000800 const SCEV *LatchExecutions = SE->getBackedgeTakenCount(L);
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000801 isl_pw_aff *UpperBound = SCEVAffinator::getPwAff(this, LatchExecutions);
802 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
Tobias Grosser75805372011-04-29 06:27:02 +0000803 Domain = isl_set_intersect(Domain, UpperBoundSet);
804 }
805
Tobias Grosserf5338802011-10-06 00:03:35 +0000806 isl_local_space_free(LocalSpace);
Tobias Grossere19661e2011-10-07 08:46:57 +0000807 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000808}
809
Tobias Grossere602a072013-05-07 07:30:56 +0000810__isl_give isl_set *ScopStmt::addConditionsToDomain(__isl_take isl_set *Domain,
811 TempScop &tempScop,
812 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000813 const Region *TopRegion = tempScop.getMaxRegion().getParent(),
Tobias Grosserd7e58642013-04-10 06:55:45 +0000814 *CurrentRegion = &CurRegion;
Tobias Grossere19661e2011-10-07 08:46:57 +0000815 const BasicBlock *BranchingBB = BB;
Tobias Grosser75805372011-04-29 06:27:02 +0000816
Tobias Grosser75805372011-04-29 06:27:02 +0000817 do {
Tobias Grossere19661e2011-10-07 08:46:57 +0000818 if (BranchingBB != CurrentRegion->getEntry()) {
819 if (const BBCond *Condition = tempScop.getBBCond(BranchingBB))
Tobias Grosser083d3d32014-06-28 08:59:45 +0000820 for (const auto &C : *Condition) {
821 isl_set *ConditionSet = buildConditionSet(C);
Tobias Grossere19661e2011-10-07 08:46:57 +0000822 Domain = isl_set_intersect(Domain, ConditionSet);
Tobias Grosser75805372011-04-29 06:27:02 +0000823 }
824 }
Tobias Grossere19661e2011-10-07 08:46:57 +0000825 BranchingBB = CurrentRegion->getEntry();
826 CurrentRegion = CurrentRegion->getParent();
827 } while (TopRegion != CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000828
Tobias Grossere19661e2011-10-07 08:46:57 +0000829 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000830}
831
Tobias Grossere602a072013-05-07 07:30:56 +0000832__isl_give isl_set *ScopStmt::buildDomain(TempScop &tempScop,
833 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000834 isl_space *Space;
835 isl_set *Domain;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000836 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000837
838 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
839
Tobias Grosser084d8f72012-05-29 09:29:44 +0000840 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
841
Tobias Grossere19661e2011-10-07 08:46:57 +0000842 Domain = isl_set_universe(Space);
Tobias Grossere19661e2011-10-07 08:46:57 +0000843 Domain = addLoopBoundsToDomain(Domain, tempScop);
844 Domain = addConditionsToDomain(Domain, tempScop, CurRegion);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000845 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grossere19661e2011-10-07 08:46:57 +0000846
847 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000848}
849
Tobias Grosser74394f02013-01-14 22:40:23 +0000850ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Sebastian Pop860e0212013-02-15 21:26:44 +0000851 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest,
Tobias Grosser75805372011-04-29 06:27:02 +0000852 SmallVectorImpl<unsigned> &Scatter)
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000853 : Parent(parent), BB(&bb), IVS(Nest.size()), NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000854 // Setup the induction variables.
Sebastian Pop860e0212013-02-15 21:26:44 +0000855 for (unsigned i = 0, e = Nest.size(); i < e; ++i) {
Sebastian Pop27c10c62013-03-22 22:07:43 +0000856 if (!SCEVCodegen) {
857 PHINode *PN = Nest[i]->getCanonicalInductionVariable();
858 assert(PN && "Non canonical IV in Scop!");
Tobias Grosser826b2af2013-03-21 16:14:50 +0000859 IVS[i] = PN;
Sebastian Pop27c10c62013-03-22 22:07:43 +0000860 }
Sebastian Pop860e0212013-02-15 21:26:44 +0000861 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +0000862 }
863
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000864 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +0000865
Tobias Grossere19661e2011-10-07 08:46:57 +0000866 Domain = buildDomain(tempScop, CurRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000867 buildScattering(Scatter);
Johannes Doerfert75bd66e2014-10-31 23:16:02 +0000868 buildAccesses(tempScop);
Johannes Doerferte58a0122014-06-27 20:31:28 +0000869 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000870}
871
Johannes Doerferte58a0122014-06-27 20:31:28 +0000872/// @brief Collect loads which might form a reduction chain with @p StoreMA
873///
874/// Check if the stored value for @p StoreMA is a binary operator with one or
875/// two loads as operands. If the binary operand is commutative & associative,
876/// used only once (by @p StoreMA) and its load operands are also used only
877/// once, we have found a possible reduction chain. It starts at an operand
878/// load and includes the binary operator and @p StoreMA.
879///
880/// Note: We allow only one use to ensure the load and binary operator cannot
881/// escape this block or into any other store except @p StoreMA.
882void ScopStmt::collectCandiateReductionLoads(
883 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
884 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
885 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000886 return;
887
888 // Skip if there is not one binary operator between the load and the store
889 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +0000890 if (!BinOp)
891 return;
892
893 // Skip if the binary operators has multiple uses
894 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000895 return;
896
897 // Skip if the opcode of the binary operator is not commutative/associative
898 if (!BinOp->isCommutative() || !BinOp->isAssociative())
899 return;
900
Johannes Doerfert9890a052014-07-01 00:32:29 +0000901 // Skip if the binary operator is outside the current SCoP
902 if (BinOp->getParent() != Store->getParent())
903 return;
904
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000905 // Skip if it is a multiplicative reduction and we disabled them
906 if (DisableMultiplicativeReductions &&
907 (BinOp->getOpcode() == Instruction::Mul ||
908 BinOp->getOpcode() == Instruction::FMul))
909 return;
910
Johannes Doerferte58a0122014-06-27 20:31:28 +0000911 // Check the binary operator operands for a candidate load
912 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
913 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
914 if (!PossibleLoad0 && !PossibleLoad1)
915 return;
916
917 // A load is only a candidate if it cannot escape (thus has only this use)
918 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000919 if (PossibleLoad0->getParent() == Store->getParent())
920 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000921 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000922 if (PossibleLoad1->getParent() == Store->getParent())
923 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000924}
925
926/// @brief Check for reductions in this ScopStmt
927///
928/// Iterate over all store memory accesses and check for valid binary reduction
929/// like chains. For all candidates we check if they have the same base address
930/// and there are no other accesses which overlap with them. The base address
931/// check rules out impossible reductions candidates early. The overlap check,
932/// together with the "only one user" check in collectCandiateReductionLoads,
933/// guarantees that none of the intermediate results will escape during
934/// execution of the loop nest. We basically check here that no other memory
935/// access can access the same memory as the potential reduction.
936void ScopStmt::checkForReductions() {
937 SmallVector<MemoryAccess *, 2> Loads;
938 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
939
940 // First collect candidate load-store reduction chains by iterating over all
941 // stores and collecting possible reduction loads.
942 for (MemoryAccess *StoreMA : MemAccs) {
943 if (StoreMA->isRead())
944 continue;
945
946 Loads.clear();
947 collectCandiateReductionLoads(StoreMA, Loads);
948 for (MemoryAccess *LoadMA : Loads)
949 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
950 }
951
952 // Then check each possible candidate pair.
953 for (const auto &CandidatePair : Candidates) {
954 bool Valid = true;
955 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
956 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
957
958 // Skip those with obviously unequal base addresses.
959 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
960 isl_map_free(LoadAccs);
961 isl_map_free(StoreAccs);
962 continue;
963 }
964
965 // And check if the remaining for overlap with other memory accesses.
966 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
967 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
968 isl_set *AllAccs = isl_map_range(AllAccsRel);
969
970 for (MemoryAccess *MA : MemAccs) {
971 if (MA == CandidatePair.first || MA == CandidatePair.second)
972 continue;
973
974 isl_map *AccRel =
975 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
976 isl_set *Accs = isl_map_range(AccRel);
977
978 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
979 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
980 Valid = Valid && isl_set_is_empty(OverlapAccs);
981 isl_set_free(OverlapAccs);
982 }
983 }
984
985 isl_set_free(AllAccs);
986 if (!Valid)
987 continue;
988
Johannes Doerfertf6183392014-07-01 20:52:51 +0000989 const LoadInst *Load =
990 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
991 MemoryAccess::ReductionType RT =
992 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
993
Johannes Doerferte58a0122014-06-27 20:31:28 +0000994 // If no overlapping access was found we mark the load and store as
995 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000996 CandidatePair.first->markAsReductionLike(RT);
997 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +0000998 }
Tobias Grosser75805372011-04-29 06:27:02 +0000999}
1000
Tobias Grosser74394f02013-01-14 22:40:23 +00001001std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001002
1003std::string ScopStmt::getScatteringStr() const {
Tobias Grossercf3942d2011-10-06 00:04:05 +00001004 return stringFromIslObj(Scattering);
Tobias Grosser75805372011-04-29 06:27:02 +00001005}
1006
Tobias Grosser74394f02013-01-14 22:40:23 +00001007unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001008
1009unsigned ScopStmt::getNumIterators() const {
1010 // The final read has one dimension with one element.
1011 if (!BB)
1012 return 1;
1013
Sebastian Pop860e0212013-02-15 21:26:44 +00001014 return NestLoops.size();
Tobias Grosser75805372011-04-29 06:27:02 +00001015}
1016
1017unsigned ScopStmt::getNumScattering() const {
1018 return isl_map_dim(Scattering, isl_dim_out);
1019}
1020
1021const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1022
Tobias Grosserabfbe632013-02-05 12:09:06 +00001023const PHINode *
1024ScopStmt::getInductionVariableForDimension(unsigned Dimension) const {
Sebastian Popf30d3b22013-02-15 21:26:48 +00001025 return IVS[Dimension];
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001026}
1027
1028const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001029 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001030}
1031
Tobias Grosser74394f02013-01-14 22:40:23 +00001032isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001033
Tobias Grosser74394f02013-01-14 22:40:23 +00001034isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001035
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001036isl_space *ScopStmt::getDomainSpace() const {
1037 return isl_set_get_space(Domain);
1038}
1039
Tobias Grosser74394f02013-01-14 22:40:23 +00001040isl_id *ScopStmt::getDomainId() const { return isl_set_get_tuple_id(Domain); }
Tobias Grossercd95b772012-08-30 11:49:38 +00001041
Tobias Grosser75805372011-04-29 06:27:02 +00001042ScopStmt::~ScopStmt() {
1043 while (!MemAccs.empty()) {
1044 delete MemAccs.back();
1045 MemAccs.pop_back();
1046 }
1047
1048 isl_set_free(Domain);
1049 isl_map_free(Scattering);
1050}
1051
1052void ScopStmt::print(raw_ostream &OS) const {
1053 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001054 OS.indent(12) << "Domain :=\n";
1055
1056 if (Domain) {
1057 OS.indent(16) << getDomainStr() << ";\n";
1058 } else
1059 OS.indent(16) << "n/a\n";
1060
1061 OS.indent(12) << "Scattering :=\n";
1062
1063 if (Domain) {
1064 OS.indent(16) << getScatteringStr() << ";\n";
1065 } else
1066 OS.indent(16) << "n/a\n";
1067
Tobias Grosser083d3d32014-06-28 08:59:45 +00001068 for (MemoryAccess *Access : MemAccs)
1069 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001070}
1071
1072void ScopStmt::dump() const { print(dbgs()); }
1073
1074//===----------------------------------------------------------------------===//
1075/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001076
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001077void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001078 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1079 isl_set_free(Context);
1080 Context = NewContext;
1081}
1082
Tobias Grosserabfbe632013-02-05 12:09:06 +00001083void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001084 for (const SCEV *Parameter : NewParameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001085 if (ParameterIds.find(Parameter) != ParameterIds.end())
1086 continue;
1087
1088 int dimension = Parameters.size();
1089
1090 Parameters.push_back(Parameter);
1091 ParameterIds[Parameter] = dimension;
1092 }
1093}
1094
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001095__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1096 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001097
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001098 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001099 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001100
Tobias Grosser8f99c162011-11-15 11:38:55 +00001101 std::string ParameterName;
1102
1103 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1104 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001105 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001106 }
1107
1108 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001109 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001110
Tobias Grosser20532b82014-04-11 17:56:49 +00001111 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1112 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001113}
Tobias Grosser75805372011-04-29 06:27:02 +00001114
Tobias Grosser6be480c2011-11-08 15:41:13 +00001115void Scop::buildContext() {
1116 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001117 Context = isl_set_universe(isl_space_copy(Space));
1118 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001119}
1120
Tobias Grosser18daaca2012-05-22 10:47:27 +00001121void Scop::addParameterBounds() {
1122 for (unsigned i = 0; i < isl_set_dim(Context, isl_dim_param); ++i) {
Tobias Grosseredab1352013-06-21 06:41:31 +00001123 isl_val *V;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001124 isl_id *Id;
1125 const SCEV *Scev;
1126 const IntegerType *T;
1127
1128 Id = isl_set_get_dim_id(Context, isl_dim_param, i);
Tobias Grosserabfbe632013-02-05 12:09:06 +00001129 Scev = (const SCEV *)isl_id_get_user(Id);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001130 T = dyn_cast<IntegerType>(Scev->getType());
1131 isl_id_free(Id);
1132
1133 assert(T && "Not an integer type");
1134 int Width = T->getBitWidth();
1135
Tobias Grosseredab1352013-06-21 06:41:31 +00001136 V = isl_val_int_from_si(IslCtx, Width - 1);
1137 V = isl_val_2exp(V);
1138 V = isl_val_neg(V);
1139 Context = isl_set_lower_bound_val(Context, isl_dim_param, i, V);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001140
Tobias Grosseredab1352013-06-21 06:41:31 +00001141 V = isl_val_int_from_si(IslCtx, Width - 1);
1142 V = isl_val_2exp(V);
1143 V = isl_val_sub_ui(V, 1);
1144 Context = isl_set_upper_bound_val(Context, isl_dim_param, i, V);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001145 }
1146}
1147
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001148void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001149 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001150 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001151
Tobias Grosser083d3d32014-06-28 08:59:45 +00001152 for (const auto &ParamID : ParameterIds) {
1153 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001154 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001155 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001156 }
1157
1158 // Align the parameters of all data structures to the model.
1159 Context = isl_set_align_params(Context, Space);
1160
Tobias Grosser083d3d32014-06-28 08:59:45 +00001161 for (ScopStmt *Stmt : *this)
1162 Stmt->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001163}
1164
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001165void Scop::simplifyAssumedContext() {
1166 // The parameter constraints of the iteration domains give us a set of
1167 // constraints that need to hold for all cases where at least a single
1168 // statement iteration is executed in the whole scop. We now simplify the
1169 // assumed context under the assumption that such constraints hold and at
1170 // least a single statement iteration is executed. For cases where no
1171 // statement instances are executed, the assumptions we have taken about
1172 // the executed code do not matter and can be changed.
1173 //
1174 // WARNING: This only holds if the assumptions we have taken do not reduce
1175 // the set of statement instances that are executed. Otherwise we
1176 // may run into a case where the iteration domains suggest that
1177 // for a certain set of parameter constraints no code is executed,
1178 // but in the original program some computation would have been
1179 // performed. In such a case, modifying the run-time conditions and
1180 // possibly influencing the run-time check may cause certain scops
1181 // to not be executed.
1182 //
1183 // Example:
1184 //
1185 // When delinearizing the following code:
1186 //
1187 // for (long i = 0; i < 100; i++)
1188 // for (long j = 0; j < m; j++)
1189 // A[i+p][j] = 1.0;
1190 //
1191 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
1192 // otherwise we would access out of bound data. Now, knowing that code is
1193 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1194 AssumedContext =
1195 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
1196}
1197
Johannes Doerfertb164c792014-09-18 11:17:17 +00001198/// @brief Add the minimal/maximal access in @p Set to @p User.
1199static int buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
1200 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1201 isl_pw_multi_aff *MinPMA, *MaxPMA;
1202 isl_pw_aff *LastDimAff;
1203 isl_aff *OneAff;
1204 unsigned Pos;
1205
Johannes Doerfert9143d672014-09-27 11:02:39 +00001206 // Restrict the number of parameters involved in the access as the lexmin/
1207 // lexmax computation will take too long if this number is high.
1208 //
1209 // Experiments with a simple test case using an i7 4800MQ:
1210 //
1211 // #Parameters involved | Time (in sec)
1212 // 6 | 0.01
1213 // 7 | 0.04
1214 // 8 | 0.12
1215 // 9 | 0.40
1216 // 10 | 1.54
1217 // 11 | 6.78
1218 // 12 | 30.38
1219 //
1220 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1221 unsigned InvolvedParams = 0;
1222 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1223 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1224 InvolvedParams++;
1225
1226 if (InvolvedParams > RunTimeChecksMaxParameters) {
1227 isl_set_free(Set);
1228 return -1;
1229 }
1230 }
1231
Johannes Doerfertb164c792014-09-18 11:17:17 +00001232 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1233 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1234
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001235 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1236 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1237
Johannes Doerfertb164c792014-09-18 11:17:17 +00001238 // Adjust the last dimension of the maximal access by one as we want to
1239 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1240 // we test during code generation might now point after the end of the
1241 // allocated array but we will never dereference it anyway.
1242 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1243 "Assumed at least one output dimension");
1244 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1245 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1246 OneAff = isl_aff_zero_on_domain(
1247 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1248 OneAff = isl_aff_add_constant_si(OneAff, 1);
1249 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1250 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1251
1252 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1253
1254 isl_set_free(Set);
1255 return 0;
1256}
1257
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001258static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1259 isl_set *Domain = MA->getStatement()->getDomain();
1260 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1261 return isl_set_reset_tuple_id(Domain);
1262}
1263
Johannes Doerfert9143d672014-09-27 11:02:39 +00001264bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001265 // To create sound alias checks we perform the following steps:
1266 // o) Use the alias analysis and an alias set tracker to build alias sets
1267 // for all memory accesses inside the SCoP.
1268 // o) For each alias set we then map the aliasing pointers back to the
1269 // memory accesses we know, thus obtain groups of memory accesses which
1270 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001271 // o) We divide each group based on the domains of the minimal/maximal
1272 // accesses. That means two minimal/maximal accesses are only in a group
1273 // if their access domains intersect, otherwise they are in different
1274 // ones.
Johannes Doerfert13771732014-10-01 12:40:46 +00001275 // o) We split groups such that they contain at most one read only base
1276 // address.
1277 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfertb164c792014-09-18 11:17:17 +00001278 // and maximal accesses to each array in this group.
1279 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1280
1281 AliasSetTracker AST(AA);
1282
1283 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001284 DenseSet<Value *> HasWriteAccess;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001285 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001286
1287 // Skip statements with an empty domain as they will never be executed.
1288 isl_set *StmtDomain = Stmt->getDomain();
1289 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1290 isl_set_free(StmtDomain);
1291 if (StmtDomainEmpty)
1292 continue;
1293
Johannes Doerfertb164c792014-09-18 11:17:17 +00001294 for (MemoryAccess *MA : *Stmt) {
1295 if (MA->isScalar())
1296 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001297 if (!MA->isRead())
1298 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001299 Instruction *Acc = MA->getAccessInstruction();
1300 PtrToAcc[getPointerOperand(*Acc)] = MA;
1301 AST.add(Acc);
1302 }
1303 }
1304
1305 SmallVector<AliasGroupTy, 4> AliasGroups;
1306 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001307 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001308 continue;
1309 AliasGroupTy AG;
1310 for (auto PR : AS)
1311 AG.push_back(PtrToAcc[PR.getValue()]);
1312 assert(AG.size() > 1 &&
1313 "Alias groups should contain at least two accesses");
1314 AliasGroups.push_back(std::move(AG));
1315 }
1316
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001317 // Split the alias groups based on their domain.
1318 for (unsigned u = 0; u < AliasGroups.size(); u++) {
1319 AliasGroupTy NewAG;
1320 AliasGroupTy &AG = AliasGroups[u];
1321 AliasGroupTy::iterator AGI = AG.begin();
1322 isl_set *AGDomain = getAccessDomain(*AGI);
1323 while (AGI != AG.end()) {
1324 MemoryAccess *MA = *AGI;
1325 isl_set *MADomain = getAccessDomain(MA);
1326 if (isl_set_is_disjoint(AGDomain, MADomain)) {
1327 NewAG.push_back(MA);
1328 AGI = AG.erase(AGI);
1329 isl_set_free(MADomain);
1330 } else {
1331 AGDomain = isl_set_union(AGDomain, MADomain);
1332 AGI++;
1333 }
1334 }
1335 if (NewAG.size() > 1)
1336 AliasGroups.push_back(std::move(NewAG));
1337 isl_set_free(AGDomain);
1338 }
1339
Johannes Doerfert13771732014-10-01 12:40:46 +00001340 DenseMap<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
1341 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
1342 for (AliasGroupTy &AG : AliasGroups) {
1343 NonReadOnlyBaseValues.clear();
1344 ReadOnlyPairs.clear();
1345
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001346 if (AG.size() < 2) {
1347 AG.clear();
1348 continue;
1349 }
1350
Johannes Doerfert13771732014-10-01 12:40:46 +00001351 for (auto II = AG.begin(); II != AG.end();) {
1352 Value *BaseAddr = (*II)->getBaseAddr();
1353 if (HasWriteAccess.count(BaseAddr)) {
1354 NonReadOnlyBaseValues.insert(BaseAddr);
1355 II++;
1356 } else {
1357 ReadOnlyPairs[BaseAddr].insert(*II);
1358 II = AG.erase(II);
1359 }
1360 }
1361
1362 // If we don't have read only pointers check if there are at least two
1363 // non read only pointers, otherwise clear the alias group.
1364 if (ReadOnlyPairs.empty()) {
1365 if (NonReadOnlyBaseValues.size() <= 1)
1366 AG.clear();
1367 continue;
1368 }
1369
1370 // If we don't have non read only pointers clear the alias group.
1371 if (NonReadOnlyBaseValues.empty()) {
1372 AG.clear();
1373 continue;
1374 }
1375
1376 // If we have both read only and non read only base pointers we combine
1377 // the non read only ones with exactly one read only one at a time into a
1378 // new alias group and clear the old alias group in the end.
1379 for (const auto &ReadOnlyPair : ReadOnlyPairs) {
1380 AliasGroupTy AGNonReadOnly = AG;
1381 for (MemoryAccess *MA : ReadOnlyPair.second)
1382 AGNonReadOnly.push_back(MA);
1383 AliasGroups.push_back(std::move(AGNonReadOnly));
1384 }
1385 AG.clear();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001386 }
1387
Johannes Doerfert9143d672014-09-27 11:02:39 +00001388 bool Valid = true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001389 for (AliasGroupTy &AG : AliasGroups) {
Johannes Doerfert13771732014-10-01 12:40:46 +00001390 if (AG.empty())
1391 continue;
1392
Johannes Doerfertb164c792014-09-18 11:17:17 +00001393 MinMaxVectorTy *MinMaxAccesses = new MinMaxVectorTy();
1394 MinMaxAccesses->reserve(AG.size());
1395
1396 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
1397 for (MemoryAccess *MA : AG)
1398 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
1399 Accesses = isl_union_map_intersect_domain(Accesses, getDomains());
1400
1401 isl_union_set *Locations = isl_union_map_range(Accesses);
1402 Locations = isl_union_set_intersect_params(Locations, getAssumedContext());
1403 Locations = isl_union_set_coalesce(Locations);
1404 Locations = isl_union_set_detect_equalities(Locations);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001405 Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
1406 MinMaxAccesses));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001407 isl_union_set_free(Locations);
Johannes Doerfertb164c792014-09-18 11:17:17 +00001408 MinMaxAliasGroups.push_back(MinMaxAccesses);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001409
1410 if (!Valid)
1411 break;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001412 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001413
1414 return Valid;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001415}
1416
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001417static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI) {
1418 unsigned MinLD = INT_MAX, MaxLD = 0;
1419 for (BasicBlock *BB : R.blocks()) {
1420 if (Loop *L = LI.getLoopFor(BB)) {
1421 unsigned LD = L->getLoopDepth();
1422 MinLD = std::min(MinLD, LD);
1423 MaxLD = std::max(MaxLD, LD);
1424 }
1425 }
1426
1427 // Handle the case that there is no loop in the SCoP first.
1428 if (MaxLD == 0)
1429 return 1;
1430
1431 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
1432 assert(MaxLD >= MinLD &&
1433 "Maximal loop depth was smaller than mininaml loop depth?");
1434 return MaxLD - MinLD + 1;
1435}
1436
Tobias Grosser0e27e242011-10-06 00:03:48 +00001437Scop::Scop(TempScop &tempScop, LoopInfo &LI, ScalarEvolution &ScalarEvolution,
1438 isl_ctx *Context)
Tobias Grosserabfbe632013-02-05 12:09:06 +00001439 : SE(&ScalarEvolution), R(tempScop.getMaxRegion()),
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001440 MaxLoopDepth(getMaxLoopDepthInRegion(tempScop.getMaxRegion(), LI)) {
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001441 IslCtx = Context;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001442 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001443
Tobias Grosserabfbe632013-02-05 12:09:06 +00001444 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001445 SmallVector<unsigned, 8> Scatter;
1446
1447 Scatter.assign(MaxLoopDepth + 1, 0);
1448
1449 // Build the iteration domain, access functions and scattering functions
1450 // traversing the region tree.
1451 buildScop(tempScop, getRegion(), NestLoops, Scatter, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00001452
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001453 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001454 addParameterBounds();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001455 simplifyAssumedContext();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001456
Tobias Grosser75805372011-04-29 06:27:02 +00001457 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1458}
1459
1460Scop::~Scop() {
1461 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001462 isl_set_free(AssumedContext);
Tobias Grosser75805372011-04-29 06:27:02 +00001463
1464 // Free the statements;
Tobias Grosser083d3d32014-06-28 08:59:45 +00001465 for (ScopStmt *Stmt : *this)
1466 delete Stmt;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001467
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001468 // Free the ScopArrayInfo objects.
1469 for (auto &ScopArrayInfoPair : ScopArrayInfoMap)
1470 delete ScopArrayInfoPair.second;
1471
Johannes Doerfertb164c792014-09-18 11:17:17 +00001472 // Free the alias groups
1473 for (MinMaxVectorTy *MinMaxAccesses : MinMaxAliasGroups) {
1474 for (MinMaxAccessTy &MMA : *MinMaxAccesses) {
1475 isl_pw_multi_aff_free(MMA.first);
1476 isl_pw_multi_aff_free(MMA.second);
1477 }
1478 delete MinMaxAccesses;
1479 }
Tobias Grosser75805372011-04-29 06:27:02 +00001480}
1481
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001482const ScopArrayInfo *
1483Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
1484 const SmallVector<const SCEV *, 4> &Sizes) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001485 const ScopArrayInfo *&SAI = ScopArrayInfoMap[BasePtr];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001486 if (!SAI)
1487 SAI = new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001488 return SAI;
1489}
1490
1491const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr) {
1492 const SCEV *PtrSCEV = SE->getSCEV(BasePtr);
1493 const SCEVUnknown *PtrBaseSCEV =
1494 cast<SCEVUnknown>(SE->getPointerBase(PtrSCEV));
1495 const ScopArrayInfo *SAI = ScopArrayInfoMap[PtrBaseSCEV->getValue()];
1496 assert(SAI && "No ScopArrayInfo available for this base pointer");
1497 return SAI;
1498}
1499
Tobias Grosser74394f02013-01-14 22:40:23 +00001500std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001501std::string Scop::getAssumedContextStr() const {
1502 return stringFromIslObj(AssumedContext);
1503}
Tobias Grosser75805372011-04-29 06:27:02 +00001504
1505std::string Scop::getNameStr() const {
1506 std::string ExitName, EntryName;
1507 raw_string_ostream ExitStr(ExitName);
1508 raw_string_ostream EntryStr(EntryName);
1509
Tobias Grosserf240b482014-01-09 10:42:15 +00001510 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001511 EntryStr.str();
1512
1513 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001514 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001515 ExitStr.str();
1516 } else
1517 ExitName = "FunctionExit";
1518
1519 return EntryName + "---" + ExitName;
1520}
1521
Tobias Grosser74394f02013-01-14 22:40:23 +00001522__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001523__isl_give isl_space *Scop::getParamSpace() const {
1524 return isl_set_get_space(this->Context);
1525}
1526
Tobias Grossere86109f2013-10-29 21:05:49 +00001527__isl_give isl_set *Scop::getAssumedContext() const {
1528 return isl_set_copy(AssumedContext);
1529}
1530
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001531void Scop::addAssumption(__isl_take isl_set *Set) {
1532 AssumedContext = isl_set_intersect(AssumedContext, Set);
1533}
1534
Tobias Grosser75805372011-04-29 06:27:02 +00001535void Scop::printContext(raw_ostream &OS) const {
1536 OS << "Context:\n";
1537
1538 if (!Context) {
1539 OS.indent(4) << "n/a\n\n";
1540 return;
1541 }
1542
1543 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001544
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001545 OS.indent(4) << "Assumed Context:\n";
1546 if (!AssumedContext) {
1547 OS.indent(4) << "n/a\n\n";
1548 return;
1549 }
1550
1551 OS.indent(4) << getAssumedContextStr() << "\n";
1552
Tobias Grosser083d3d32014-06-28 08:59:45 +00001553 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001554 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001555 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1556 }
Tobias Grosser75805372011-04-29 06:27:02 +00001557}
1558
Johannes Doerfertb164c792014-09-18 11:17:17 +00001559void Scop::printAliasAssumptions(raw_ostream &OS) const {
1560 OS.indent(4) << "Alias Groups (" << MinMaxAliasGroups.size() << "):\n";
1561 if (MinMaxAliasGroups.empty()) {
1562 OS.indent(8) << "n/a\n";
1563 return;
1564 }
1565 for (MinMaxVectorTy *MinMaxAccesses : MinMaxAliasGroups) {
1566 OS.indent(8) << "[[";
1567 for (MinMaxAccessTy &MinMacAccess : *MinMaxAccesses)
1568 OS << " <" << MinMacAccess.first << ", " << MinMacAccess.second << ">";
1569 OS << " ]]\n";
1570 }
1571}
1572
Tobias Grosser75805372011-04-29 06:27:02 +00001573void Scop::printStatements(raw_ostream &OS) const {
1574 OS << "Statements {\n";
1575
Tobias Grosser083d3d32014-06-28 08:59:45 +00001576 for (ScopStmt *Stmt : *this)
1577 OS.indent(4) << *Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001578
1579 OS.indent(4) << "}\n";
1580}
1581
Tobias Grosser75805372011-04-29 06:27:02 +00001582void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00001583 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
1584 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00001585 OS.indent(4) << "Region: " << getNameStr() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001586 printContext(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001587 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001588 printStatements(OS.indent(4));
1589}
1590
1591void Scop::dump() const { print(dbgs()); }
1592
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001593isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00001594
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001595__isl_give isl_union_set *Scop::getDomains() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001596 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001597
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001598 for (ScopStmt *Stmt : *this)
1599 Domain = isl_union_set_add_set(Domain, Stmt->getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001600
1601 return Domain;
1602}
1603
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001604__isl_give isl_union_map *Scop::getMustWrites() {
1605 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1606
1607 for (ScopStmt *Stmt : *this) {
1608 for (MemoryAccess *MA : *Stmt) {
1609 if (!MA->isMustWrite())
1610 continue;
1611
1612 isl_set *Domain = Stmt->getDomain();
1613 isl_map *AccessDomain = MA->getAccessRelation();
1614 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1615 Write = isl_union_map_add_map(Write, AccessDomain);
1616 }
1617 }
1618 return isl_union_map_coalesce(Write);
1619}
1620
1621__isl_give isl_union_map *Scop::getMayWrites() {
1622 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1623
1624 for (ScopStmt *Stmt : *this) {
1625 for (MemoryAccess *MA : *Stmt) {
1626 if (!MA->isMayWrite())
1627 continue;
1628
1629 isl_set *Domain = Stmt->getDomain();
1630 isl_map *AccessDomain = MA->getAccessRelation();
1631 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1632 Write = isl_union_map_add_map(Write, AccessDomain);
1633 }
1634 }
1635 return isl_union_map_coalesce(Write);
1636}
1637
Tobias Grosser37eb4222014-02-20 21:43:54 +00001638__isl_give isl_union_map *Scop::getWrites() {
1639 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1640
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001641 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001642 for (MemoryAccess *MA : *Stmt) {
1643 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001644 continue;
1645
1646 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001647 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001648 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1649 Write = isl_union_map_add_map(Write, AccessDomain);
1650 }
1651 }
1652 return isl_union_map_coalesce(Write);
1653}
1654
1655__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001656 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001657
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001658 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001659 for (MemoryAccess *MA : *Stmt) {
1660 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001661 continue;
1662
1663 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001664 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001665
1666 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1667 Read = isl_union_map_add_map(Read, AccessDomain);
1668 }
1669 }
1670 return isl_union_map_coalesce(Read);
1671}
1672
1673__isl_give isl_union_map *Scop::getSchedule() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001674 isl_union_map *Schedule = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001675
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001676 for (ScopStmt *Stmt : *this)
Tobias Grosser37eb4222014-02-20 21:43:54 +00001677 Schedule = isl_union_map_add_map(Schedule, Stmt->getScattering());
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001678
Tobias Grosser37eb4222014-02-20 21:43:54 +00001679 return isl_union_map_coalesce(Schedule);
1680}
1681
1682bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
1683 bool Changed = false;
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001684 for (ScopStmt *Stmt : *this) {
Tobias Grosser37eb4222014-02-20 21:43:54 +00001685 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt->getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001686 isl_union_set *NewStmtDomain = isl_union_set_intersect(
1687 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
1688
1689 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
1690 isl_union_set_free(StmtDomain);
1691 isl_union_set_free(NewStmtDomain);
1692 continue;
1693 }
1694
1695 Changed = true;
1696
1697 isl_union_set_free(StmtDomain);
1698 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
1699
1700 if (isl_union_set_is_empty(NewStmtDomain)) {
1701 Stmt->restrictDomain(isl_set_empty(Stmt->getDomainSpace()));
1702 isl_union_set_free(NewStmtDomain);
1703 } else
1704 Stmt->restrictDomain(isl_set_from_union_set(NewStmtDomain));
1705 }
1706 isl_union_set_free(Domain);
1707 return Changed;
1708}
1709
Tobias Grosser75805372011-04-29 06:27:02 +00001710ScalarEvolution *Scop::getSE() const { return SE; }
1711
1712bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
1713 if (tempScop.getAccessFunctions(BB))
1714 return false;
1715
1716 return true;
1717}
1718
Tobias Grosser74394f02013-01-14 22:40:23 +00001719void Scop::buildScop(TempScop &tempScop, const Region &CurRegion,
1720 SmallVectorImpl<Loop *> &NestLoops,
1721 SmallVectorImpl<unsigned> &Scatter, LoopInfo &LI) {
Tobias Grosser75805372011-04-29 06:27:02 +00001722 Loop *L = castToLoop(CurRegion, LI);
1723
1724 if (L)
1725 NestLoops.push_back(L);
1726
1727 unsigned loopDepth = NestLoops.size();
1728 assert(Scatter.size() > loopDepth && "Scatter not big enough!");
1729
1730 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00001731 E = CurRegion.element_end();
1732 I != E; ++I)
Tobias Grosser75805372011-04-29 06:27:02 +00001733 if (I->isSubRegion())
1734 buildScop(tempScop, *(I->getNodeAs<Region>()), NestLoops, Scatter, LI);
1735 else {
1736 BasicBlock *BB = I->getNodeAs<BasicBlock>();
1737
1738 if (isTrivialBB(BB, tempScop))
1739 continue;
1740
Johannes Doerfert7c494212014-10-31 23:13:39 +00001741 ScopStmt *Stmt =
1742 new ScopStmt(*this, tempScop, CurRegion, *BB, NestLoops, Scatter);
1743
1744 // Insert all statements into the statement map and the statement vector.
1745 StmtMap[BB] = Stmt;
1746 Stmts.push_back(Stmt);
Tobias Grosser75805372011-04-29 06:27:02 +00001747
1748 // Increasing the Scattering function is OK for the moment, because
1749 // we are using a depth first iterator and the program is well structured.
1750 ++Scatter[loopDepth];
1751 }
1752
1753 if (!L)
1754 return;
1755
1756 // Exiting a loop region.
1757 Scatter[loopDepth] = 0;
1758 NestLoops.pop_back();
Tobias Grosser74394f02013-01-14 22:40:23 +00001759 ++Scatter[loopDepth - 1];
Tobias Grosser75805372011-04-29 06:27:02 +00001760}
1761
Johannes Doerfert7c494212014-10-31 23:13:39 +00001762ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
1763 const auto &StmtMapIt = StmtMap.find(BB);
1764 if (StmtMapIt == StmtMap.end())
1765 return nullptr;
1766 return StmtMapIt->second;
1767}
1768
Tobias Grosser75805372011-04-29 06:27:02 +00001769//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00001770ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
1771 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00001772 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001773}
1774
1775ScopInfo::~ScopInfo() {
1776 clear();
1777 isl_ctx_free(ctx);
1778}
1779
Tobias Grosser75805372011-04-29 06:27:02 +00001780void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1781 AU.addRequired<LoopInfo>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001782 AU.addRequired<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001783 AU.addRequired<ScalarEvolution>();
1784 AU.addRequired<TempScopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001785 AU.addRequired<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00001786 AU.setPreservesAll();
1787}
1788
1789bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
1790 LoopInfo &LI = getAnalysis<LoopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001791 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00001792 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1793
1794 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop(R);
1795
1796 // This region is no Scop.
1797 if (!tempScop) {
Tobias Grosserc98a8fc2014-11-14 11:12:31 +00001798 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00001799 return false;
1800 }
1801
Tobias Grosserb76f38532011-08-20 11:11:25 +00001802 scop = new Scop(*tempScop, LI, SE, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001803
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00001804 if (!PollyUseRuntimeAliasChecks) {
1805 // Statistics.
1806 ++ScopFound;
1807 if (scop->getMaxLoopDepth() > 0)
1808 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001809 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00001810 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001811
Johannes Doerfert9143d672014-09-27 11:02:39 +00001812 // If a problem occurs while building the alias groups we need to delete
1813 // this SCoP and pretend it wasn't valid in the first place.
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00001814 if (scop->buildAliasGroups(AA)) {
1815 // Statistics.
1816 ++ScopFound;
1817 if (scop->getMaxLoopDepth() > 0)
1818 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001819 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00001820 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001821
1822 DEBUG(dbgs()
1823 << "\n\nNOTE: Run time checks for " << scop->getNameStr()
1824 << " could not be created as the number of parameters involved is too "
1825 "high. The SCoP will be "
1826 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust the "
1827 "maximal number of parameters but be advised that the compile time "
1828 "might increase exponentially.\n\n");
1829
1830 delete scop;
1831 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00001832 return false;
1833}
1834
1835char ScopInfo::ID = 0;
1836
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001837Pass *polly::createScopInfoPass() { return new ScopInfo(); }
1838
Tobias Grosser73600b82011-10-08 00:30:40 +00001839INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
1840 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001841 false);
Johannes Doerfertb164c792014-09-18 11:17:17 +00001842INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001843INITIALIZE_PASS_DEPENDENCY(LoopInfo);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001844INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001845INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1846INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Tobias Grosser73600b82011-10-08 00:30:40 +00001847INITIALIZE_PASS_END(ScopInfo, "polly-scops",
1848 "Polly - Create polyhedral description of Scops", false,
1849 false)