blob: e8a382219bd6d40bade652b76a3d299f0f5aaf66 [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//
15// This represantation is shared among several tools in the polyhedral
16// 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);
157 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(Space));
158 isl_aff *Affine = isl_aff_zero_on_domain(ls);
159 isl_set *Domain = isl_set_universe(Space);
160
161 Affine = isl_aff_add_constant_val(Affine, v);
162
163 return isl_pw_aff_alloc(Domain, Affine);
164}
165
166__isl_give isl_pw_aff *
167SCEVAffinator::visitTruncateExpr(const SCEVTruncateExpr *Expr) {
168 llvm_unreachable("SCEVTruncateExpr not yet supported");
169}
170
171__isl_give isl_pw_aff *
172SCEVAffinator::visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
173 llvm_unreachable("SCEVZeroExtendExpr not yet supported");
174}
175
176__isl_give isl_pw_aff *
177SCEVAffinator::visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
178 // Assuming the value is signed, a sign extension is basically a noop.
179 // TODO: Reconsider this as soon as we support unsigned values.
180 return visit(Expr->getOperand());
181}
182
183__isl_give isl_pw_aff *SCEVAffinator::visitAddExpr(const SCEVAddExpr *Expr) {
184 isl_pw_aff *Sum = visit(Expr->getOperand(0));
185
186 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
187 isl_pw_aff *NextSummand = visit(Expr->getOperand(i));
188 Sum = isl_pw_aff_add(Sum, NextSummand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000189 }
190
Tobias Grosser0695ee42013-09-17 03:30:31 +0000191 // TODO: Check for NSW and NUW.
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000192
Tobias Grosser0695ee42013-09-17 03:30:31 +0000193 return Sum;
194}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000195
Tobias Grosser0695ee42013-09-17 03:30:31 +0000196__isl_give isl_pw_aff *SCEVAffinator::visitMulExpr(const SCEVMulExpr *Expr) {
197 isl_pw_aff *Product = visit(Expr->getOperand(0));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000198
Tobias Grosser0695ee42013-09-17 03:30:31 +0000199 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
200 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
201
202 if (!isl_pw_aff_is_cst(Product) && !isl_pw_aff_is_cst(NextOperand)) {
203 isl_pw_aff_free(Product);
204 isl_pw_aff_free(NextOperand);
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000205 return nullptr;
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000206 }
207
Tobias Grosser0695ee42013-09-17 03:30:31 +0000208 Product = isl_pw_aff_mul(Product, NextOperand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000209 }
210
Tobias Grosser0695ee42013-09-17 03:30:31 +0000211 // TODO: Check for NSW and NUW.
212 return Product;
213}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000214
Tobias Grosser0695ee42013-09-17 03:30:31 +0000215__isl_give isl_pw_aff *SCEVAffinator::visitUDivExpr(const SCEVUDivExpr *Expr) {
216 llvm_unreachable("SCEVUDivExpr not yet supported");
217}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000218
Tobias Grosser0695ee42013-09-17 03:30:31 +0000219__isl_give isl_pw_aff *
220SCEVAffinator::visitAddRecExpr(const SCEVAddRecExpr *Expr) {
221 assert(Expr->isAffine() && "Only affine AddRecurrences allowed");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000222
Tobias Grosser0695ee42013-09-17 03:30:31 +0000223 // Directly generate isl_pw_aff for Expr if 'start' is zero.
224 if (Expr->getStart()->isZero()) {
225 assert(S->getRegion().contains(Expr->getLoop()) &&
226 "Scop does not contain the loop referenced in this AddRec");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000227
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000228 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser0695ee42013-09-17 03:30:31 +0000229 isl_pw_aff *Step = visit(Expr->getOperand(1));
230 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
231 isl_local_space *LocalSpace = isl_local_space_from_space(Space);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000232
Tobias Grosser0695ee42013-09-17 03:30:31 +0000233 int loopDimension = getLoopDepth(Expr->getLoop());
234
235 isl_aff *LAff = isl_aff_set_coefficient_si(
236 isl_aff_zero_on_domain(LocalSpace), isl_dim_in, loopDimension, 1);
237 isl_pw_aff *LPwAff = isl_pw_aff_from_aff(LAff);
238
239 // TODO: Do we need to check for NSW and NUW?
240 return isl_pw_aff_add(Start, isl_pw_aff_mul(Step, LPwAff));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000241 }
242
Tobias Grosser0695ee42013-09-17 03:30:31 +0000243 // Translate AddRecExpr from '{start, +, inc}' into 'start + {0, +, inc}'
244 // if 'start' is not zero.
245 ScalarEvolution &SE = *S->getSE();
246 const SCEV *ZeroStartExpr = SE.getAddRecExpr(
247 SE.getConstant(Expr->getStart()->getType(), 0),
248 Expr->getStepRecurrence(SE), Expr->getLoop(), SCEV::FlagAnyWrap);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000249
Tobias Grosser0695ee42013-09-17 03:30:31 +0000250 isl_pw_aff *ZeroStartResult = visit(ZeroStartExpr);
251 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000252
Tobias Grosser0695ee42013-09-17 03:30:31 +0000253 return isl_pw_aff_add(ZeroStartResult, Start);
254}
255
256__isl_give isl_pw_aff *SCEVAffinator::visitSMaxExpr(const SCEVSMaxExpr *Expr) {
257 isl_pw_aff *Max = visit(Expr->getOperand(0));
258
259 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
260 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
261 Max = isl_pw_aff_max(Max, NextOperand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000262 }
263
Tobias Grosser0695ee42013-09-17 03:30:31 +0000264 return Max;
265}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000266
Tobias Grosser0695ee42013-09-17 03:30:31 +0000267__isl_give isl_pw_aff *SCEVAffinator::visitUMaxExpr(const SCEVUMaxExpr *Expr) {
268 llvm_unreachable("SCEVUMaxExpr not yet supported");
269}
270
271__isl_give isl_pw_aff *SCEVAffinator::visitUnknown(const SCEVUnknown *Expr) {
Tobias Grosserf4daf342014-08-16 09:08:55 +0000272 llvm_unreachable("Unknowns are always parameters");
Tobias Grosser0695ee42013-09-17 03:30:31 +0000273}
274
275int SCEVAffinator::getLoopDepth(const Loop *L) {
276 Loop *outerLoop = S->getRegion().outermostLoopInRegion(const_cast<Loop *>(L));
277 assert(outerLoop && "Scop does not contain this loop");
278 return L->getLoopDepth() - outerLoop->getLoopDepth();
279}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000280
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000281ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *AccessType, isl_ctx *Ctx,
282 const SmallVector<const SCEV *, 4> &DimensionSizes)
283 : BasePtr(BasePtr), AccessType(AccessType), DimensionSizes(DimensionSizes) {
284 const std::string BasePtrName = getIslCompatibleName("MemRef_", BasePtr, "");
285 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
286}
287
288ScopArrayInfo::~ScopArrayInfo() { isl_id_free(Id); }
289
290isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
291
292void ScopArrayInfo::dump() const { print(errs()); }
293
294void ScopArrayInfo::print(raw_ostream &OS) const {
295 OS << "ScopArrayInfo:\n";
296 OS << " Base: " << *getBasePtr() << "\n";
297 OS << " Type: " << *getType() << "\n";
298 OS << " Dimension Sizes:\n";
299 for (unsigned u = 0; u < getNumberOfDimensions(); u++)
300 OS << " " << u << ") " << *DimensionSizes[u] << "\n";
301 OS << "\n";
302}
303
304const ScopArrayInfo *
305ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
306 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
307 assert(Id && "Output dimension didn't have an ID");
308 return getFromId(Id);
309}
310
311const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
312 void *User = isl_id_get_user(Id);
313 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
314 isl_id_free(Id);
315 return SAI;
316}
317
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000318const std::string
319MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
320 switch (RT) {
321 case MemoryAccess::RT_NONE:
322 llvm_unreachable("Requested a reduction operator string for a memory "
323 "access which isn't a reduction");
324 case MemoryAccess::RT_ADD:
325 return "+";
326 case MemoryAccess::RT_MUL:
327 return "*";
328 case MemoryAccess::RT_BOR:
329 return "|";
330 case MemoryAccess::RT_BXOR:
331 return "^";
332 case MemoryAccess::RT_BAND:
333 return "&";
334 }
335 llvm_unreachable("Unknown reduction type");
336 return "";
337}
338
Johannes Doerfertf6183392014-07-01 20:52:51 +0000339/// @brief Return the reduction type for a given binary operator
340static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
341 const Instruction *Load) {
342 if (!BinOp)
343 return MemoryAccess::RT_NONE;
344 switch (BinOp->getOpcode()) {
345 case Instruction::FAdd:
346 if (!BinOp->hasUnsafeAlgebra())
347 return MemoryAccess::RT_NONE;
348 // Fall through
349 case Instruction::Add:
350 return MemoryAccess::RT_ADD;
351 case Instruction::Or:
352 return MemoryAccess::RT_BOR;
353 case Instruction::Xor:
354 return MemoryAccess::RT_BXOR;
355 case Instruction::And:
356 return MemoryAccess::RT_BAND;
357 case Instruction::FMul:
358 if (!BinOp->hasUnsafeAlgebra())
359 return MemoryAccess::RT_NONE;
360 // Fall through
361 case Instruction::Mul:
362 if (DisableMultiplicativeReductions)
363 return MemoryAccess::RT_NONE;
364 return MemoryAccess::RT_MUL;
365 default:
366 return MemoryAccess::RT_NONE;
367 }
368}
Tobias Grosser75805372011-04-29 06:27:02 +0000369//===----------------------------------------------------------------------===//
370
371MemoryAccess::~MemoryAccess() {
Tobias Grosser54a86e62011-08-18 06:31:46 +0000372 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000373 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000374}
375
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000376static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
377 switch (Access.getType()) {
378 case IRAccess::READ:
379 return MemoryAccess::READ;
380 case IRAccess::MUST_WRITE:
381 return MemoryAccess::MUST_WRITE;
382 case IRAccess::MAY_WRITE:
383 return MemoryAccess::MAY_WRITE;
384 }
385 llvm_unreachable("Unknown IRAccess type!");
386}
387
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000388const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
389 isl_id *ArrayId = getArrayId();
390 void *User = isl_id_get_user(ArrayId);
391 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
392 isl_id_free(ArrayId);
393 return SAI;
394}
395
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000396isl_id *MemoryAccess::getArrayId() const {
397 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
398}
399
Tobias Grosser5d453812011-10-06 00:04:11 +0000400isl_map *MemoryAccess::getAccessRelation() const {
401 return isl_map_copy(AccessRelation);
402}
403
404std::string MemoryAccess::getAccessRelationStr() const {
405 return stringFromIslObj(AccessRelation);
406}
407
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000408__isl_give isl_space *MemoryAccess::getAccessRelationSpace() const {
409 return isl_map_get_space(AccessRelation);
410}
411
Tobias Grosser5d453812011-10-06 00:04:11 +0000412isl_map *MemoryAccess::getNewAccessRelation() const {
413 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000414}
415
416isl_basic_map *MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000417 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000418 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000419
Tobias Grosser084d8f72012-05-29 09:29:44 +0000420 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000421 isl_basic_set_universe(Statement->getDomainSpace()),
422 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000423}
424
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000425// Formalize no out-of-bound access assumption
426//
427// When delinearizing array accesses we optimistically assume that the
428// delinearized accesses do not access out of bound locations (the subscript
429// expression of each array evaluates for each statement instance that is
430// executed to a value that is larger than zero and strictly smaller than the
431// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000432// dimension for which we do not need to assume any upper bound. At this point
433// we formalize this assumption to ensure that at code generation time the
434// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000435//
436// To find the set of constraints necessary to avoid out of bound accesses, we
437// first build the set of data locations that are not within array bounds. We
438// then apply the reverse access relation to obtain the set of iterations that
439// may contain invalid accesses and reduce this set of iterations to the ones
440// that are actually executed by intersecting them with the domain of the
441// statement. If we now project out all loop dimensions, we obtain a set of
442// parameters that may cause statement instances to be executed that may
443// possibly yield out of bound memory accesses. The complement of these
444// constraints is the set of constraints that needs to be assumed to ensure such
445// statement instances are never executed.
446void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
447 isl_space *Space = isl_space_range(getAccessRelationSpace());
448 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000449 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000450 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
451 isl_pw_aff *Var =
452 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
453 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
454
455 isl_set *DimOutside;
456
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000457 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
458 isl_pw_aff *SizeE = SCEVAffinator::getPwAff(Statement, Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000459
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000460 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
461 Statement->getNumIterators());
462 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
463 isl_space_dim(Space, isl_dim_set));
464 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
465 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000466
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000467 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000468
469 Outside = isl_set_union(Outside, DimOutside);
470 }
471
472 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
473 Outside = isl_set_intersect(Outside, Statement->getDomain());
474 Outside = isl_set_params(Outside);
475 Outside = isl_set_complement(Outside);
476 Statement->getParent()->addAssumption(Outside);
477 isl_space_free(Space);
478}
479
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000480MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000481 ScopStmt *Statement, const ScopArrayInfo *SAI)
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000482 : Type(getMemoryAccessType(Access)), Statement(Statement), Inst(AccInst),
483 newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000484
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000485 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000486 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000487 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000488
489 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000490
Tobias Grossera1879642011-12-20 10:43:14 +0000491 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000492 // We overapproximate non-affine accesses with a possible access to the
493 // whole array. For read accesses it does not make a difference, if an
494 // access must or may happen. However, for write accesses it is important to
495 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000496 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000497 AccessRelation =
498 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000499 return;
500 }
501
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000502 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000503 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000504
Tobias Grosser79baa212014-04-10 08:38:02 +0000505 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Sebastian Pop18016682014-04-08 21:20:44 +0000506 isl_pw_aff *Affine =
507 SCEVAffinator::getPwAff(Statement, Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000508
Sebastian Pop422e33f2014-06-03 18:16:31 +0000509 if (Size == 1) {
510 // For the non delinearized arrays, divide the access function of the last
511 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000512 //
513 // A stride one array access in C expressed as A[i] is expressed in
514 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
515 // two subsequent values of 'i' index two values that are stored next to
516 // each other in memory. By this division we make this characteristic
517 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000518 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000519 Affine = isl_pw_aff_scale_down_val(Affine, v);
520 }
521
522 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
523
Tobias Grosser79baa212014-04-10 08:38:02 +0000524 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000525 }
526
Tobias Grosser79baa212014-04-10 08:38:02 +0000527 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000528 AccessRelation = isl_map_set_tuple_id(
529 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000530 AccessRelation =
531 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
532
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000533 assumeNoOutOfBound(Access);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000534 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000535}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000536
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000537void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000538 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000539 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000540}
541
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000542const std::string MemoryAccess::getReductionOperatorStr() const {
543 return MemoryAccess::getReductionOperatorStr(getReductionType());
544}
545
Johannes Doerfertf6183392014-07-01 20:52:51 +0000546raw_ostream &polly::operator<<(raw_ostream &OS,
547 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000548 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000549 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000550 else
551 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000552 return OS;
553}
554
Tobias Grosser75805372011-04-29 06:27:02 +0000555void MemoryAccess::print(raw_ostream &OS) const {
Tobias Grosser4f967492013-06-23 05:21:18 +0000556 switch (Type) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000557 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000558 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000559 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000560 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000561 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000562 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000563 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000564 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000565 break;
566 }
Johannes Doerfertf6183392014-07-01 20:52:51 +0000567 OS << "[Reduction Type: " << getReductionType() << "]\n";
Tobias Grosser5d453812011-10-06 00:04:11 +0000568 OS.indent(16) << getAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000569}
570
Tobias Grosser74394f02013-01-14 22:40:23 +0000571void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000572
573// Create a map in the size of the provided set domain, that maps from the
574// one element of the provided set domain to another element of the provided
575// set domain.
576// The mapping is limited to all points that are equal in all but the last
577// dimension and for which the last dimension of the input is strict smaller
578// than the last dimension of the output.
579//
580// getEqualAndLarger(set[i0, i1, ..., iX]):
581//
582// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
583// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
584//
Tobias Grosserf5338802011-10-06 00:03:35 +0000585static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000586 isl_space *Space = isl_space_map_from_set(setDomain);
587 isl_map *Map = isl_map_universe(isl_space_copy(Space));
588 isl_local_space *MapLocalSpace = isl_local_space_from_space(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000589 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000590
591 // Set all but the last dimension to be equal for the input and output
592 //
593 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
594 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000595 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000596 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000597
598 // Set the last dimension of the input to be strict smaller than the
599 // last dimension of the output.
600 //
601 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
602 //
Tobias Grosseredab1352013-06-21 06:41:31 +0000603 isl_val *v;
604 isl_ctx *Ctx = isl_map_get_ctx(Map);
Tobias Grosserf5338802011-10-06 00:03:35 +0000605 isl_constraint *c = isl_inequality_alloc(isl_local_space_copy(MapLocalSpace));
Tobias Grosseredab1352013-06-21 06:41:31 +0000606 v = isl_val_int_from_si(Ctx, -1);
607 c = isl_constraint_set_coefficient_val(c, isl_dim_in, lastDimension, v);
608 v = isl_val_int_from_si(Ctx, 1);
609 c = isl_constraint_set_coefficient_val(c, isl_dim_out, lastDimension, v);
610 v = isl_val_int_from_si(Ctx, -1);
611 c = isl_constraint_set_constant_val(c, v);
Tobias Grosser75805372011-04-29 06:27:02 +0000612
Tobias Grosserc327932c2012-02-01 14:23:36 +0000613 Map = isl_map_add_constraint(Map, c);
Tobias Grosser75805372011-04-29 06:27:02 +0000614
Tobias Grosser23b36662011-10-17 08:32:36 +0000615 isl_local_space_free(MapLocalSpace);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000616 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000617}
618
Sebastian Popa00a0292012-12-18 07:46:06 +0000619isl_set *MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000620 isl_map *S = const_cast<isl_map *>(Schedule);
Sebastian Popa00a0292012-12-18 07:46:06 +0000621 isl_map *AccessRelation = getAccessRelation();
622 isl_space *Space = isl_space_range(isl_map_get_space(S));
623 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000624
Sebastian Popa00a0292012-12-18 07:46:06 +0000625 S = isl_map_reverse(S);
626 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000627
Sebastian Popa00a0292012-12-18 07:46:06 +0000628 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
629 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
630 NextScatt = isl_map_apply_domain(NextScatt, S);
631 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000632
Sebastian Popa00a0292012-12-18 07:46:06 +0000633 isl_set *Deltas = isl_map_deltas(NextScatt);
634 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000635}
636
Sebastian Popa00a0292012-12-18 07:46:06 +0000637bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000638 int StrideWidth) const {
639 isl_set *Stride, *StrideX;
640 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000641
Sebastian Popa00a0292012-12-18 07:46:06 +0000642 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000643 StrideX = isl_set_universe(isl_set_get_space(Stride));
644 StrideX = isl_set_fix_si(StrideX, isl_dim_set, 0, StrideWidth);
645 IsStrideX = isl_set_is_equal(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000646
Tobias Grosser28dd4862012-01-24 16:42:16 +0000647 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000648 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000649
Tobias Grosser28dd4862012-01-24 16:42:16 +0000650 return IsStrideX;
651}
652
Sebastian Popa00a0292012-12-18 07:46:06 +0000653bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
654 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000655}
656
Tobias Grosser79baa212014-04-10 08:38:02 +0000657bool MemoryAccess::isScalar() const {
658 return isl_map_n_out(AccessRelation) == 0;
659}
660
Sebastian Popa00a0292012-12-18 07:46:06 +0000661bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
662 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000663}
664
Tobias Grosser5d453812011-10-06 00:04:11 +0000665void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000666 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000667 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000668}
Tobias Grosser75805372011-04-29 06:27:02 +0000669
670//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000671
Tobias Grosser74394f02013-01-14 22:40:23 +0000672isl_map *ScopStmt::getScattering() const { return isl_map_copy(Scattering); }
Tobias Grossercf3942d2011-10-06 00:04:05 +0000673
Tobias Grosser37eb4222014-02-20 21:43:54 +0000674void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
675 assert(isl_set_is_subset(NewDomain, Domain) &&
676 "New domain is not a subset of old domain!");
677 isl_set_free(Domain);
678 Domain = NewDomain;
679 Scattering = isl_map_intersect_domain(Scattering, isl_set_copy(Domain));
680}
681
Tobias Grossercf3942d2011-10-06 00:04:05 +0000682void ScopStmt::setScattering(isl_map *NewScattering) {
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000683 assert(NewScattering && "New scattering is nullptr");
Tobias Grosserb76f38532011-08-20 11:11:25 +0000684 isl_map_free(Scattering);
Tobias Grossercf3942d2011-10-06 00:04:05 +0000685 Scattering = NewScattering;
Tobias Grosserb76f38532011-08-20 11:11:25 +0000686}
687
Tobias Grosser75805372011-04-29 06:27:02 +0000688void ScopStmt::buildScattering(SmallVectorImpl<unsigned> &Scatter) {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000689 unsigned NbIterators = getNumIterators();
690 unsigned NbScatteringDims = Parent.getMaxLoopDepth() * 2 + 1;
691
Tobias Grosser084d8f72012-05-29 09:29:44 +0000692 isl_space *Space = isl_space_set_alloc(getIslCtx(), 0, NbScatteringDims);
Tobias Grosserf5338802011-10-06 00:03:35 +0000693 Space = isl_space_set_tuple_name(Space, isl_dim_out, "scattering");
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000694
Tobias Grosser084d8f72012-05-29 09:29:44 +0000695 Scattering = isl_map_from_domain_and_range(isl_set_universe(getDomainSpace()),
696 isl_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000697
698 // Loop dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000699 for (unsigned i = 0; i < NbIterators; ++i)
Tobias Grosserabfbe632013-02-05 12:09:06 +0000700 Scattering =
701 isl_map_equate(Scattering, isl_dim_out, 2 * i + 1, isl_dim_in, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000702
703 // Constant dimensions
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000704 for (unsigned i = 0; i < NbIterators + 1; ++i)
705 Scattering = isl_map_fix_si(Scattering, isl_dim_out, 2 * i, Scatter[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000706
707 // Fill scattering dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000708 for (unsigned i = 2 * NbIterators + 1; i < NbScatteringDims; ++i)
709 Scattering = isl_map_fix_si(Scattering, isl_dim_out, i, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000710
Tobias Grosser37487052011-10-06 00:03:42 +0000711 Scattering = isl_map_align_params(Scattering, Parent.getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000712}
713
714void ScopStmt::buildAccesses(TempScop &tempScop, const Region &CurRegion) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000715 for (const auto &AccessPair : *tempScop.getAccessFunctions(BB)) {
716 const IRAccess &Access = AccessPair.first;
717 Instruction *AccessInst = AccessPair.second;
718
719 const ScopArrayInfo *SAI =
720 getParent()->getOrCreateScopArrayInfo(Access, AccessInst);
721 MemAccs.push_back(new MemoryAccess(Access, AccessInst, this, SAI));
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000722
723 // We do not track locations for scalar memory accesses at the moment.
724 //
725 // We do not have a use for this information at the moment. If we need this
726 // at some point, the "instruction -> access" mapping needs to be enhanced
727 // as a single instruction could then possibly perform multiple accesses.
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000728 if (!Access.isScalar()) {
729 assert(!InstructionToAccess.count(AccessInst) &&
Tobias Grosser3fc91542014-02-20 21:43:45 +0000730 "Unexpected 1-to-N mapping on instruction to access map!");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000731 InstructionToAccess[AccessInst] = MemAccs.back();
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000732 }
Tobias Grosser75805372011-04-29 06:27:02 +0000733 }
734}
735
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000736void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000737 for (MemoryAccess *MA : *this)
738 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000739
740 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
741 Scattering = isl_map_align_params(Scattering, Parent.getParamSpace());
742}
743
Tobias Grosser65b00582011-11-08 15:41:19 +0000744__isl_give isl_set *ScopStmt::buildConditionSet(const Comparison &Comp) {
Tobias Grossera601fbd2011-11-09 22:34:44 +0000745 isl_pw_aff *L = SCEVAffinator::getPwAff(this, Comp.getLHS());
746 isl_pw_aff *R = SCEVAffinator::getPwAff(this, Comp.getRHS());
Tobias Grosser75805372011-04-29 06:27:02 +0000747
Tobias Grosserd2795d02011-08-18 07:51:40 +0000748 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000749 case ICmpInst::ICMP_EQ:
Tobias Grosser048c8792011-10-23 20:59:20 +0000750 return isl_pw_aff_eq_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000751 case ICmpInst::ICMP_NE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000752 return isl_pw_aff_ne_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000753 case ICmpInst::ICMP_SLT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000754 return isl_pw_aff_lt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000755 case ICmpInst::ICMP_SLE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000756 return isl_pw_aff_le_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000757 case ICmpInst::ICMP_SGT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000758 return isl_pw_aff_gt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000759 case ICmpInst::ICMP_SGE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000760 return isl_pw_aff_ge_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000761 case ICmpInst::ICMP_ULT:
762 case ICmpInst::ICMP_UGT:
763 case ICmpInst::ICMP_ULE:
Tobias Grosser75805372011-04-29 06:27:02 +0000764 case ICmpInst::ICMP_UGE:
Tobias Grosserd2795d02011-08-18 07:51:40 +0000765 llvm_unreachable("Unsigned comparisons not yet supported");
Tobias Grosser75805372011-04-29 06:27:02 +0000766 default:
767 llvm_unreachable("Non integer predicate not supported");
768 }
Tobias Grosser75805372011-04-29 06:27:02 +0000769}
770
Tobias Grossere19661e2011-10-07 08:46:57 +0000771__isl_give isl_set *ScopStmt::addLoopBoundsToDomain(__isl_take isl_set *Domain,
Tobias Grosser60b54f12011-11-08 15:41:28 +0000772 TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000773 isl_space *Space;
774 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000775
Tobias Grossere19661e2011-10-07 08:46:57 +0000776 Space = isl_set_get_space(Domain);
777 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000778
Tobias Grosser75805372011-04-29 06:27:02 +0000779 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000780 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000781 isl_pw_aff *IV =
782 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000783
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000784 // 0 <= IV.
785 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
786 Domain = isl_set_intersect(Domain, LowerBound);
787
788 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000789 const Loop *L = getLoopForDimension(i);
Tobias Grosser1179afa2011-11-02 21:37:51 +0000790 const SCEV *LatchExecutions = tempScop.getLoopBound(L);
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000791 isl_pw_aff *UpperBound = SCEVAffinator::getPwAff(this, LatchExecutions);
792 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
Tobias Grosser75805372011-04-29 06:27:02 +0000793 Domain = isl_set_intersect(Domain, UpperBoundSet);
794 }
795
Tobias Grosserf5338802011-10-06 00:03:35 +0000796 isl_local_space_free(LocalSpace);
Tobias Grossere19661e2011-10-07 08:46:57 +0000797 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000798}
799
Tobias Grossere602a072013-05-07 07:30:56 +0000800__isl_give isl_set *ScopStmt::addConditionsToDomain(__isl_take isl_set *Domain,
801 TempScop &tempScop,
802 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000803 const Region *TopRegion = tempScop.getMaxRegion().getParent(),
Tobias Grosserd7e58642013-04-10 06:55:45 +0000804 *CurrentRegion = &CurRegion;
Tobias Grossere19661e2011-10-07 08:46:57 +0000805 const BasicBlock *BranchingBB = BB;
Tobias Grosser75805372011-04-29 06:27:02 +0000806
Tobias Grosser75805372011-04-29 06:27:02 +0000807 do {
Tobias Grossere19661e2011-10-07 08:46:57 +0000808 if (BranchingBB != CurrentRegion->getEntry()) {
809 if (const BBCond *Condition = tempScop.getBBCond(BranchingBB))
Tobias Grosser083d3d32014-06-28 08:59:45 +0000810 for (const auto &C : *Condition) {
811 isl_set *ConditionSet = buildConditionSet(C);
Tobias Grossere19661e2011-10-07 08:46:57 +0000812 Domain = isl_set_intersect(Domain, ConditionSet);
Tobias Grosser75805372011-04-29 06:27:02 +0000813 }
814 }
Tobias Grossere19661e2011-10-07 08:46:57 +0000815 BranchingBB = CurrentRegion->getEntry();
816 CurrentRegion = CurrentRegion->getParent();
817 } while (TopRegion != CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000818
Tobias Grossere19661e2011-10-07 08:46:57 +0000819 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000820}
821
Tobias Grossere602a072013-05-07 07:30:56 +0000822__isl_give isl_set *ScopStmt::buildDomain(TempScop &tempScop,
823 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000824 isl_space *Space;
825 isl_set *Domain;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000826 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000827
828 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
829
Tobias Grosser084d8f72012-05-29 09:29:44 +0000830 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
831
Tobias Grossere19661e2011-10-07 08:46:57 +0000832 Domain = isl_set_universe(Space);
Tobias Grossere19661e2011-10-07 08:46:57 +0000833 Domain = addLoopBoundsToDomain(Domain, tempScop);
834 Domain = addConditionsToDomain(Domain, tempScop, CurRegion);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000835 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grossere19661e2011-10-07 08:46:57 +0000836
837 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000838}
839
Tobias Grosser74394f02013-01-14 22:40:23 +0000840ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Sebastian Pop860e0212013-02-15 21:26:44 +0000841 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest,
Tobias Grosser75805372011-04-29 06:27:02 +0000842 SmallVectorImpl<unsigned> &Scatter)
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000843 : Parent(parent), BB(&bb), IVS(Nest.size()), NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000844 // Setup the induction variables.
Sebastian Pop860e0212013-02-15 21:26:44 +0000845 for (unsigned i = 0, e = Nest.size(); i < e; ++i) {
Sebastian Pop27c10c62013-03-22 22:07:43 +0000846 if (!SCEVCodegen) {
847 PHINode *PN = Nest[i]->getCanonicalInductionVariable();
848 assert(PN && "Non canonical IV in Scop!");
Tobias Grosser826b2af2013-03-21 16:14:50 +0000849 IVS[i] = PN;
Sebastian Pop27c10c62013-03-22 22:07:43 +0000850 }
Sebastian Pop860e0212013-02-15 21:26:44 +0000851 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +0000852 }
853
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000854 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +0000855
Tobias Grossere19661e2011-10-07 08:46:57 +0000856 Domain = buildDomain(tempScop, CurRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000857 buildScattering(Scatter);
858 buildAccesses(tempScop, CurRegion);
Johannes Doerferte58a0122014-06-27 20:31:28 +0000859 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000860}
861
Johannes Doerferte58a0122014-06-27 20:31:28 +0000862/// @brief Collect loads which might form a reduction chain with @p StoreMA
863///
864/// Check if the stored value for @p StoreMA is a binary operator with one or
865/// two loads as operands. If the binary operand is commutative & associative,
866/// used only once (by @p StoreMA) and its load operands are also used only
867/// once, we have found a possible reduction chain. It starts at an operand
868/// load and includes the binary operator and @p StoreMA.
869///
870/// Note: We allow only one use to ensure the load and binary operator cannot
871/// escape this block or into any other store except @p StoreMA.
872void ScopStmt::collectCandiateReductionLoads(
873 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
874 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
875 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000876 return;
877
878 // Skip if there is not one binary operator between the load and the store
879 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +0000880 if (!BinOp)
881 return;
882
883 // Skip if the binary operators has multiple uses
884 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000885 return;
886
887 // Skip if the opcode of the binary operator is not commutative/associative
888 if (!BinOp->isCommutative() || !BinOp->isAssociative())
889 return;
890
Johannes Doerfert9890a052014-07-01 00:32:29 +0000891 // Skip if the binary operator is outside the current SCoP
892 if (BinOp->getParent() != Store->getParent())
893 return;
894
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000895 // Skip if it is a multiplicative reduction and we disabled them
896 if (DisableMultiplicativeReductions &&
897 (BinOp->getOpcode() == Instruction::Mul ||
898 BinOp->getOpcode() == Instruction::FMul))
899 return;
900
Johannes Doerferte58a0122014-06-27 20:31:28 +0000901 // Check the binary operator operands for a candidate load
902 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
903 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
904 if (!PossibleLoad0 && !PossibleLoad1)
905 return;
906
907 // A load is only a candidate if it cannot escape (thus has only this use)
908 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000909 if (PossibleLoad0->getParent() == Store->getParent())
910 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000911 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000912 if (PossibleLoad1->getParent() == Store->getParent())
913 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000914}
915
916/// @brief Check for reductions in this ScopStmt
917///
918/// Iterate over all store memory accesses and check for valid binary reduction
919/// like chains. For all candidates we check if they have the same base address
920/// and there are no other accesses which overlap with them. The base address
921/// check rules out impossible reductions candidates early. The overlap check,
922/// together with the "only one user" check in collectCandiateReductionLoads,
923/// guarantees that none of the intermediate results will escape during
924/// execution of the loop nest. We basically check here that no other memory
925/// access can access the same memory as the potential reduction.
926void ScopStmt::checkForReductions() {
927 SmallVector<MemoryAccess *, 2> Loads;
928 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
929
930 // First collect candidate load-store reduction chains by iterating over all
931 // stores and collecting possible reduction loads.
932 for (MemoryAccess *StoreMA : MemAccs) {
933 if (StoreMA->isRead())
934 continue;
935
936 Loads.clear();
937 collectCandiateReductionLoads(StoreMA, Loads);
938 for (MemoryAccess *LoadMA : Loads)
939 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
940 }
941
942 // Then check each possible candidate pair.
943 for (const auto &CandidatePair : Candidates) {
944 bool Valid = true;
945 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
946 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
947
948 // Skip those with obviously unequal base addresses.
949 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
950 isl_map_free(LoadAccs);
951 isl_map_free(StoreAccs);
952 continue;
953 }
954
955 // And check if the remaining for overlap with other memory accesses.
956 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
957 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
958 isl_set *AllAccs = isl_map_range(AllAccsRel);
959
960 for (MemoryAccess *MA : MemAccs) {
961 if (MA == CandidatePair.first || MA == CandidatePair.second)
962 continue;
963
964 isl_map *AccRel =
965 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
966 isl_set *Accs = isl_map_range(AccRel);
967
968 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
969 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
970 Valid = Valid && isl_set_is_empty(OverlapAccs);
971 isl_set_free(OverlapAccs);
972 }
973 }
974
975 isl_set_free(AllAccs);
976 if (!Valid)
977 continue;
978
Johannes Doerfertf6183392014-07-01 20:52:51 +0000979 const LoadInst *Load =
980 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
981 MemoryAccess::ReductionType RT =
982 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
983
Johannes Doerferte58a0122014-06-27 20:31:28 +0000984 // If no overlapping access was found we mark the load and store as
985 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000986 CandidatePair.first->markAsReductionLike(RT);
987 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +0000988 }
Tobias Grosser75805372011-04-29 06:27:02 +0000989}
990
Tobias Grosser74394f02013-01-14 22:40:23 +0000991std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +0000992
993std::string ScopStmt::getScatteringStr() const {
Tobias Grossercf3942d2011-10-06 00:04:05 +0000994 return stringFromIslObj(Scattering);
Tobias Grosser75805372011-04-29 06:27:02 +0000995}
996
Tobias Grosser74394f02013-01-14 22:40:23 +0000997unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +0000998
999unsigned ScopStmt::getNumIterators() const {
1000 // The final read has one dimension with one element.
1001 if (!BB)
1002 return 1;
1003
Sebastian Pop860e0212013-02-15 21:26:44 +00001004 return NestLoops.size();
Tobias Grosser75805372011-04-29 06:27:02 +00001005}
1006
1007unsigned ScopStmt::getNumScattering() const {
1008 return isl_map_dim(Scattering, isl_dim_out);
1009}
1010
1011const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1012
Tobias Grosserabfbe632013-02-05 12:09:06 +00001013const PHINode *
1014ScopStmt::getInductionVariableForDimension(unsigned Dimension) const {
Sebastian Popf30d3b22013-02-15 21:26:48 +00001015 return IVS[Dimension];
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001016}
1017
1018const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001019 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001020}
1021
Tobias Grosser74394f02013-01-14 22:40:23 +00001022isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001023
Tobias Grosser74394f02013-01-14 22:40:23 +00001024isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001025
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001026isl_space *ScopStmt::getDomainSpace() const {
1027 return isl_set_get_space(Domain);
1028}
1029
Tobias Grosser74394f02013-01-14 22:40:23 +00001030isl_id *ScopStmt::getDomainId() const { return isl_set_get_tuple_id(Domain); }
Tobias Grossercd95b772012-08-30 11:49:38 +00001031
Tobias Grosser75805372011-04-29 06:27:02 +00001032ScopStmt::~ScopStmt() {
1033 while (!MemAccs.empty()) {
1034 delete MemAccs.back();
1035 MemAccs.pop_back();
1036 }
1037
1038 isl_set_free(Domain);
1039 isl_map_free(Scattering);
1040}
1041
1042void ScopStmt::print(raw_ostream &OS) const {
1043 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001044 OS.indent(12) << "Domain :=\n";
1045
1046 if (Domain) {
1047 OS.indent(16) << getDomainStr() << ";\n";
1048 } else
1049 OS.indent(16) << "n/a\n";
1050
1051 OS.indent(12) << "Scattering :=\n";
1052
1053 if (Domain) {
1054 OS.indent(16) << getScatteringStr() << ";\n";
1055 } else
1056 OS.indent(16) << "n/a\n";
1057
Tobias Grosser083d3d32014-06-28 08:59:45 +00001058 for (MemoryAccess *Access : MemAccs)
1059 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001060}
1061
1062void ScopStmt::dump() const { print(dbgs()); }
1063
1064//===----------------------------------------------------------------------===//
1065/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001066
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001067void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001068 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1069 isl_set_free(Context);
1070 Context = NewContext;
1071}
1072
Tobias Grosserabfbe632013-02-05 12:09:06 +00001073void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001074 for (const SCEV *Parameter : NewParameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001075 if (ParameterIds.find(Parameter) != ParameterIds.end())
1076 continue;
1077
1078 int dimension = Parameters.size();
1079
1080 Parameters.push_back(Parameter);
1081 ParameterIds[Parameter] = dimension;
1082 }
1083}
1084
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001085__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1086 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001087
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001088 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001089 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001090
Tobias Grosser8f99c162011-11-15 11:38:55 +00001091 std::string ParameterName;
1092
1093 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1094 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001095 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001096 }
1097
1098 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001099 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001100
Tobias Grosser20532b82014-04-11 17:56:49 +00001101 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1102 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001103}
Tobias Grosser75805372011-04-29 06:27:02 +00001104
Tobias Grosser6be480c2011-11-08 15:41:13 +00001105void Scop::buildContext() {
1106 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001107 Context = isl_set_universe(isl_space_copy(Space));
1108 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001109}
1110
Tobias Grosser18daaca2012-05-22 10:47:27 +00001111void Scop::addParameterBounds() {
1112 for (unsigned i = 0; i < isl_set_dim(Context, isl_dim_param); ++i) {
Tobias Grosseredab1352013-06-21 06:41:31 +00001113 isl_val *V;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001114 isl_id *Id;
1115 const SCEV *Scev;
1116 const IntegerType *T;
1117
1118 Id = isl_set_get_dim_id(Context, isl_dim_param, i);
Tobias Grosserabfbe632013-02-05 12:09:06 +00001119 Scev = (const SCEV *)isl_id_get_user(Id);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001120 T = dyn_cast<IntegerType>(Scev->getType());
1121 isl_id_free(Id);
1122
1123 assert(T && "Not an integer type");
1124 int Width = T->getBitWidth();
1125
Tobias Grosseredab1352013-06-21 06:41:31 +00001126 V = isl_val_int_from_si(IslCtx, Width - 1);
1127 V = isl_val_2exp(V);
1128 V = isl_val_neg(V);
1129 Context = isl_set_lower_bound_val(Context, isl_dim_param, i, V);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001130
Tobias Grosseredab1352013-06-21 06:41:31 +00001131 V = isl_val_int_from_si(IslCtx, Width - 1);
1132 V = isl_val_2exp(V);
1133 V = isl_val_sub_ui(V, 1);
1134 Context = isl_set_upper_bound_val(Context, isl_dim_param, i, V);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001135 }
1136}
1137
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001138void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001139 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001140 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001141
Tobias Grosser083d3d32014-06-28 08:59:45 +00001142 for (const auto &ParamID : ParameterIds) {
1143 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001144 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001145 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001146 }
1147
1148 // Align the parameters of all data structures to the model.
1149 Context = isl_set_align_params(Context, Space);
1150
Tobias Grosser083d3d32014-06-28 08:59:45 +00001151 for (ScopStmt *Stmt : *this)
1152 Stmt->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001153}
1154
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001155void Scop::simplifyAssumedContext() {
1156 // The parameter constraints of the iteration domains give us a set of
1157 // constraints that need to hold for all cases where at least a single
1158 // statement iteration is executed in the whole scop. We now simplify the
1159 // assumed context under the assumption that such constraints hold and at
1160 // least a single statement iteration is executed. For cases where no
1161 // statement instances are executed, the assumptions we have taken about
1162 // the executed code do not matter and can be changed.
1163 //
1164 // WARNING: This only holds if the assumptions we have taken do not reduce
1165 // the set of statement instances that are executed. Otherwise we
1166 // may run into a case where the iteration domains suggest that
1167 // for a certain set of parameter constraints no code is executed,
1168 // but in the original program some computation would have been
1169 // performed. In such a case, modifying the run-time conditions and
1170 // possibly influencing the run-time check may cause certain scops
1171 // to not be executed.
1172 //
1173 // Example:
1174 //
1175 // When delinearizing the following code:
1176 //
1177 // for (long i = 0; i < 100; i++)
1178 // for (long j = 0; j < m; j++)
1179 // A[i+p][j] = 1.0;
1180 //
1181 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
1182 // otherwise we would access out of bound data. Now, knowing that code is
1183 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1184 AssumedContext =
1185 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
1186}
1187
Johannes Doerfertb164c792014-09-18 11:17:17 +00001188/// @brief Add the minimal/maximal access in @p Set to @p User.
1189static int buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
1190 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1191 isl_pw_multi_aff *MinPMA, *MaxPMA;
1192 isl_pw_aff *LastDimAff;
1193 isl_aff *OneAff;
1194 unsigned Pos;
1195
Johannes Doerfert9143d672014-09-27 11:02:39 +00001196 // Restrict the number of parameters involved in the access as the lexmin/
1197 // lexmax computation will take too long if this number is high.
1198 //
1199 // Experiments with a simple test case using an i7 4800MQ:
1200 //
1201 // #Parameters involved | Time (in sec)
1202 // 6 | 0.01
1203 // 7 | 0.04
1204 // 8 | 0.12
1205 // 9 | 0.40
1206 // 10 | 1.54
1207 // 11 | 6.78
1208 // 12 | 30.38
1209 //
1210 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1211 unsigned InvolvedParams = 0;
1212 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1213 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1214 InvolvedParams++;
1215
1216 if (InvolvedParams > RunTimeChecksMaxParameters) {
1217 isl_set_free(Set);
1218 return -1;
1219 }
1220 }
1221
Johannes Doerfertb164c792014-09-18 11:17:17 +00001222 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1223 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1224
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001225 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1226 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1227
Johannes Doerfertb164c792014-09-18 11:17:17 +00001228 // Adjust the last dimension of the maximal access by one as we want to
1229 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1230 // we test during code generation might now point after the end of the
1231 // allocated array but we will never dereference it anyway.
1232 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1233 "Assumed at least one output dimension");
1234 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1235 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1236 OneAff = isl_aff_zero_on_domain(
1237 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1238 OneAff = isl_aff_add_constant_si(OneAff, 1);
1239 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1240 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1241
1242 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1243
1244 isl_set_free(Set);
1245 return 0;
1246}
1247
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001248static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1249 isl_set *Domain = MA->getStatement()->getDomain();
1250 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1251 return isl_set_reset_tuple_id(Domain);
1252}
1253
Johannes Doerfert9143d672014-09-27 11:02:39 +00001254bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001255 // To create sound alias checks we perform the following steps:
1256 // o) Use the alias analysis and an alias set tracker to build alias sets
1257 // for all memory accesses inside the SCoP.
1258 // o) For each alias set we then map the aliasing pointers back to the
1259 // memory accesses we know, thus obtain groups of memory accesses which
1260 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001261 // o) We divide each group based on the domains of the minimal/maximal
1262 // accesses. That means two minimal/maximal accesses are only in a group
1263 // if their access domains intersect, otherwise they are in different
1264 // ones.
Johannes Doerfert13771732014-10-01 12:40:46 +00001265 // o) We split groups such that they contain at most one read only base
1266 // address.
1267 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfertb164c792014-09-18 11:17:17 +00001268 // and maximal accesses to each array in this group.
1269 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1270
1271 AliasSetTracker AST(AA);
1272
1273 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001274 DenseSet<Value *> HasWriteAccess;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001275 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001276
1277 // Skip statements with an empty domain as they will never be executed.
1278 isl_set *StmtDomain = Stmt->getDomain();
1279 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1280 isl_set_free(StmtDomain);
1281 if (StmtDomainEmpty)
1282 continue;
1283
Johannes Doerfertb164c792014-09-18 11:17:17 +00001284 for (MemoryAccess *MA : *Stmt) {
1285 if (MA->isScalar())
1286 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001287 if (!MA->isRead())
1288 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001289 Instruction *Acc = MA->getAccessInstruction();
1290 PtrToAcc[getPointerOperand(*Acc)] = MA;
1291 AST.add(Acc);
1292 }
1293 }
1294
1295 SmallVector<AliasGroupTy, 4> AliasGroups;
1296 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001297 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001298 continue;
1299 AliasGroupTy AG;
1300 for (auto PR : AS)
1301 AG.push_back(PtrToAcc[PR.getValue()]);
1302 assert(AG.size() > 1 &&
1303 "Alias groups should contain at least two accesses");
1304 AliasGroups.push_back(std::move(AG));
1305 }
1306
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001307 // Split the alias groups based on their domain.
1308 for (unsigned u = 0; u < AliasGroups.size(); u++) {
1309 AliasGroupTy NewAG;
1310 AliasGroupTy &AG = AliasGroups[u];
1311 AliasGroupTy::iterator AGI = AG.begin();
1312 isl_set *AGDomain = getAccessDomain(*AGI);
1313 while (AGI != AG.end()) {
1314 MemoryAccess *MA = *AGI;
1315 isl_set *MADomain = getAccessDomain(MA);
1316 if (isl_set_is_disjoint(AGDomain, MADomain)) {
1317 NewAG.push_back(MA);
1318 AGI = AG.erase(AGI);
1319 isl_set_free(MADomain);
1320 } else {
1321 AGDomain = isl_set_union(AGDomain, MADomain);
1322 AGI++;
1323 }
1324 }
1325 if (NewAG.size() > 1)
1326 AliasGroups.push_back(std::move(NewAG));
1327 isl_set_free(AGDomain);
1328 }
1329
Johannes Doerfert13771732014-10-01 12:40:46 +00001330 DenseMap<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
1331 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
1332 for (AliasGroupTy &AG : AliasGroups) {
1333 NonReadOnlyBaseValues.clear();
1334 ReadOnlyPairs.clear();
1335
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001336 if (AG.size() < 2) {
1337 AG.clear();
1338 continue;
1339 }
1340
Johannes Doerfert13771732014-10-01 12:40:46 +00001341 for (auto II = AG.begin(); II != AG.end();) {
1342 Value *BaseAddr = (*II)->getBaseAddr();
1343 if (HasWriteAccess.count(BaseAddr)) {
1344 NonReadOnlyBaseValues.insert(BaseAddr);
1345 II++;
1346 } else {
1347 ReadOnlyPairs[BaseAddr].insert(*II);
1348 II = AG.erase(II);
1349 }
1350 }
1351
1352 // If we don't have read only pointers check if there are at least two
1353 // non read only pointers, otherwise clear the alias group.
1354 if (ReadOnlyPairs.empty()) {
1355 if (NonReadOnlyBaseValues.size() <= 1)
1356 AG.clear();
1357 continue;
1358 }
1359
1360 // If we don't have non read only pointers clear the alias group.
1361 if (NonReadOnlyBaseValues.empty()) {
1362 AG.clear();
1363 continue;
1364 }
1365
1366 // If we have both read only and non read only base pointers we combine
1367 // the non read only ones with exactly one read only one at a time into a
1368 // new alias group and clear the old alias group in the end.
1369 for (const auto &ReadOnlyPair : ReadOnlyPairs) {
1370 AliasGroupTy AGNonReadOnly = AG;
1371 for (MemoryAccess *MA : ReadOnlyPair.second)
1372 AGNonReadOnly.push_back(MA);
1373 AliasGroups.push_back(std::move(AGNonReadOnly));
1374 }
1375 AG.clear();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001376 }
1377
Johannes Doerfert9143d672014-09-27 11:02:39 +00001378 bool Valid = true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001379 for (AliasGroupTy &AG : AliasGroups) {
Johannes Doerfert13771732014-10-01 12:40:46 +00001380 if (AG.empty())
1381 continue;
1382
Johannes Doerfertb164c792014-09-18 11:17:17 +00001383 MinMaxVectorTy *MinMaxAccesses = new MinMaxVectorTy();
1384 MinMaxAccesses->reserve(AG.size());
1385
1386 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
1387 for (MemoryAccess *MA : AG)
1388 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
1389 Accesses = isl_union_map_intersect_domain(Accesses, getDomains());
1390
1391 isl_union_set *Locations = isl_union_map_range(Accesses);
1392 Locations = isl_union_set_intersect_params(Locations, getAssumedContext());
1393 Locations = isl_union_set_coalesce(Locations);
1394 Locations = isl_union_set_detect_equalities(Locations);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001395 Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
1396 MinMaxAccesses));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001397 isl_union_set_free(Locations);
Johannes Doerfertb164c792014-09-18 11:17:17 +00001398 MinMaxAliasGroups.push_back(MinMaxAccesses);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001399
1400 if (!Valid)
1401 break;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001402 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001403
1404 return Valid;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001405}
1406
Tobias Grosser0e27e242011-10-06 00:03:48 +00001407Scop::Scop(TempScop &tempScop, LoopInfo &LI, ScalarEvolution &ScalarEvolution,
1408 isl_ctx *Context)
Tobias Grosserabfbe632013-02-05 12:09:06 +00001409 : SE(&ScalarEvolution), R(tempScop.getMaxRegion()),
1410 MaxLoopDepth(tempScop.getMaxLoopDepth()) {
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001411 IslCtx = Context;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001412 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001413
Tobias Grosserabfbe632013-02-05 12:09:06 +00001414 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001415 SmallVector<unsigned, 8> Scatter;
1416
1417 Scatter.assign(MaxLoopDepth + 1, 0);
1418
1419 // Build the iteration domain, access functions and scattering functions
1420 // traversing the region tree.
1421 buildScop(tempScop, getRegion(), NestLoops, Scatter, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00001422
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001423 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001424 addParameterBounds();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001425 simplifyAssumedContext();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001426
Tobias Grosser75805372011-04-29 06:27:02 +00001427 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1428}
1429
1430Scop::~Scop() {
1431 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001432 isl_set_free(AssumedContext);
Tobias Grosser75805372011-04-29 06:27:02 +00001433
1434 // Free the statements;
Tobias Grosser083d3d32014-06-28 08:59:45 +00001435 for (ScopStmt *Stmt : *this)
1436 delete Stmt;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001437
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001438 // Free the ScopArrayInfo objects.
1439 for (auto &ScopArrayInfoPair : ScopArrayInfoMap)
1440 delete ScopArrayInfoPair.second;
1441
Johannes Doerfertb164c792014-09-18 11:17:17 +00001442 // Free the alias groups
1443 for (MinMaxVectorTy *MinMaxAccesses : MinMaxAliasGroups) {
1444 for (MinMaxAccessTy &MMA : *MinMaxAccesses) {
1445 isl_pw_multi_aff_free(MMA.first);
1446 isl_pw_multi_aff_free(MMA.second);
1447 }
1448 delete MinMaxAccesses;
1449 }
Tobias Grosser75805372011-04-29 06:27:02 +00001450}
1451
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001452const ScopArrayInfo *Scop::getOrCreateScopArrayInfo(const IRAccess &Access,
1453 Instruction *AccessInst) {
1454 Value *BasePtr = Access.getBase();
1455 const ScopArrayInfo *&SAI = ScopArrayInfoMap[BasePtr];
1456 if (!SAI) {
1457 Type *AccessType = getPointerOperand(*AccessInst)->getType();
1458 SAI = new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Access.Sizes);
1459 }
1460 return SAI;
1461}
1462
1463const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr) {
1464 const SCEV *PtrSCEV = SE->getSCEV(BasePtr);
1465 const SCEVUnknown *PtrBaseSCEV =
1466 cast<SCEVUnknown>(SE->getPointerBase(PtrSCEV));
1467 const ScopArrayInfo *SAI = ScopArrayInfoMap[PtrBaseSCEV->getValue()];
1468 assert(SAI && "No ScopArrayInfo available for this base pointer");
1469 return SAI;
1470}
1471
Tobias Grosser74394f02013-01-14 22:40:23 +00001472std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001473std::string Scop::getAssumedContextStr() const {
1474 return stringFromIslObj(AssumedContext);
1475}
Tobias Grosser75805372011-04-29 06:27:02 +00001476
1477std::string Scop::getNameStr() const {
1478 std::string ExitName, EntryName;
1479 raw_string_ostream ExitStr(ExitName);
1480 raw_string_ostream EntryStr(EntryName);
1481
Tobias Grosserf240b482014-01-09 10:42:15 +00001482 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001483 EntryStr.str();
1484
1485 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001486 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001487 ExitStr.str();
1488 } else
1489 ExitName = "FunctionExit";
1490
1491 return EntryName + "---" + ExitName;
1492}
1493
Tobias Grosser74394f02013-01-14 22:40:23 +00001494__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001495__isl_give isl_space *Scop::getParamSpace() const {
1496 return isl_set_get_space(this->Context);
1497}
1498
Tobias Grossere86109f2013-10-29 21:05:49 +00001499__isl_give isl_set *Scop::getAssumedContext() const {
1500 return isl_set_copy(AssumedContext);
1501}
1502
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001503void Scop::addAssumption(__isl_take isl_set *Set) {
1504 AssumedContext = isl_set_intersect(AssumedContext, Set);
1505}
1506
Tobias Grosser75805372011-04-29 06:27:02 +00001507void Scop::printContext(raw_ostream &OS) const {
1508 OS << "Context:\n";
1509
1510 if (!Context) {
1511 OS.indent(4) << "n/a\n\n";
1512 return;
1513 }
1514
1515 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001516
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001517 OS.indent(4) << "Assumed Context:\n";
1518 if (!AssumedContext) {
1519 OS.indent(4) << "n/a\n\n";
1520 return;
1521 }
1522
1523 OS.indent(4) << getAssumedContextStr() << "\n";
1524
Tobias Grosser083d3d32014-06-28 08:59:45 +00001525 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001526 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001527 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1528 }
Tobias Grosser75805372011-04-29 06:27:02 +00001529}
1530
Johannes Doerfertb164c792014-09-18 11:17:17 +00001531void Scop::printAliasAssumptions(raw_ostream &OS) const {
1532 OS.indent(4) << "Alias Groups (" << MinMaxAliasGroups.size() << "):\n";
1533 if (MinMaxAliasGroups.empty()) {
1534 OS.indent(8) << "n/a\n";
1535 return;
1536 }
1537 for (MinMaxVectorTy *MinMaxAccesses : MinMaxAliasGroups) {
1538 OS.indent(8) << "[[";
1539 for (MinMaxAccessTy &MinMacAccess : *MinMaxAccesses)
1540 OS << " <" << MinMacAccess.first << ", " << MinMacAccess.second << ">";
1541 OS << " ]]\n";
1542 }
1543}
1544
Tobias Grosser75805372011-04-29 06:27:02 +00001545void Scop::printStatements(raw_ostream &OS) const {
1546 OS << "Statements {\n";
1547
Tobias Grosser083d3d32014-06-28 08:59:45 +00001548 for (ScopStmt *Stmt : *this)
1549 OS.indent(4) << *Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001550
1551 OS.indent(4) << "}\n";
1552}
1553
Tobias Grosser75805372011-04-29 06:27:02 +00001554void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00001555 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
1556 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00001557 OS.indent(4) << "Region: " << getNameStr() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001558 printContext(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001559 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001560 printStatements(OS.indent(4));
1561}
1562
1563void Scop::dump() const { print(dbgs()); }
1564
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001565isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00001566
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001567__isl_give isl_union_set *Scop::getDomains() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001568 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001569
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001570 for (ScopStmt *Stmt : *this)
1571 Domain = isl_union_set_add_set(Domain, Stmt->getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001572
1573 return Domain;
1574}
1575
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001576__isl_give isl_union_map *Scop::getMustWrites() {
1577 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1578
1579 for (ScopStmt *Stmt : *this) {
1580 for (MemoryAccess *MA : *Stmt) {
1581 if (!MA->isMustWrite())
1582 continue;
1583
1584 isl_set *Domain = Stmt->getDomain();
1585 isl_map *AccessDomain = MA->getAccessRelation();
1586 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1587 Write = isl_union_map_add_map(Write, AccessDomain);
1588 }
1589 }
1590 return isl_union_map_coalesce(Write);
1591}
1592
1593__isl_give isl_union_map *Scop::getMayWrites() {
1594 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1595
1596 for (ScopStmt *Stmt : *this) {
1597 for (MemoryAccess *MA : *Stmt) {
1598 if (!MA->isMayWrite())
1599 continue;
1600
1601 isl_set *Domain = Stmt->getDomain();
1602 isl_map *AccessDomain = MA->getAccessRelation();
1603 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1604 Write = isl_union_map_add_map(Write, AccessDomain);
1605 }
1606 }
1607 return isl_union_map_coalesce(Write);
1608}
1609
Tobias Grosser37eb4222014-02-20 21:43:54 +00001610__isl_give isl_union_map *Scop::getWrites() {
1611 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1612
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001613 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001614 for (MemoryAccess *MA : *Stmt) {
1615 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001616 continue;
1617
1618 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001619 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001620 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1621 Write = isl_union_map_add_map(Write, AccessDomain);
1622 }
1623 }
1624 return isl_union_map_coalesce(Write);
1625}
1626
1627__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001628 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001629
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001630 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001631 for (MemoryAccess *MA : *Stmt) {
1632 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001633 continue;
1634
1635 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001636 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001637
1638 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1639 Read = isl_union_map_add_map(Read, AccessDomain);
1640 }
1641 }
1642 return isl_union_map_coalesce(Read);
1643}
1644
1645__isl_give isl_union_map *Scop::getSchedule() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001646 isl_union_map *Schedule = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001647
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001648 for (ScopStmt *Stmt : *this)
Tobias Grosser37eb4222014-02-20 21:43:54 +00001649 Schedule = isl_union_map_add_map(Schedule, Stmt->getScattering());
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001650
Tobias Grosser37eb4222014-02-20 21:43:54 +00001651 return isl_union_map_coalesce(Schedule);
1652}
1653
1654bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
1655 bool Changed = false;
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001656 for (ScopStmt *Stmt : *this) {
Tobias Grosser37eb4222014-02-20 21:43:54 +00001657 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt->getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001658 isl_union_set *NewStmtDomain = isl_union_set_intersect(
1659 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
1660
1661 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
1662 isl_union_set_free(StmtDomain);
1663 isl_union_set_free(NewStmtDomain);
1664 continue;
1665 }
1666
1667 Changed = true;
1668
1669 isl_union_set_free(StmtDomain);
1670 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
1671
1672 if (isl_union_set_is_empty(NewStmtDomain)) {
1673 Stmt->restrictDomain(isl_set_empty(Stmt->getDomainSpace()));
1674 isl_union_set_free(NewStmtDomain);
1675 } else
1676 Stmt->restrictDomain(isl_set_from_union_set(NewStmtDomain));
1677 }
1678 isl_union_set_free(Domain);
1679 return Changed;
1680}
1681
Tobias Grosser75805372011-04-29 06:27:02 +00001682ScalarEvolution *Scop::getSE() const { return SE; }
1683
1684bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
1685 if (tempScop.getAccessFunctions(BB))
1686 return false;
1687
1688 return true;
1689}
1690
Tobias Grosser74394f02013-01-14 22:40:23 +00001691void Scop::buildScop(TempScop &tempScop, const Region &CurRegion,
1692 SmallVectorImpl<Loop *> &NestLoops,
1693 SmallVectorImpl<unsigned> &Scatter, LoopInfo &LI) {
Tobias Grosser75805372011-04-29 06:27:02 +00001694 Loop *L = castToLoop(CurRegion, LI);
1695
1696 if (L)
1697 NestLoops.push_back(L);
1698
1699 unsigned loopDepth = NestLoops.size();
1700 assert(Scatter.size() > loopDepth && "Scatter not big enough!");
1701
1702 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00001703 E = CurRegion.element_end();
1704 I != E; ++I)
Tobias Grosser75805372011-04-29 06:27:02 +00001705 if (I->isSubRegion())
1706 buildScop(tempScop, *(I->getNodeAs<Region>()), NestLoops, Scatter, LI);
1707 else {
1708 BasicBlock *BB = I->getNodeAs<BasicBlock>();
1709
1710 if (isTrivialBB(BB, tempScop))
1711 continue;
1712
Tobias Grosserabfbe632013-02-05 12:09:06 +00001713 Stmts.push_back(
1714 new ScopStmt(*this, tempScop, CurRegion, *BB, NestLoops, Scatter));
Tobias Grosser75805372011-04-29 06:27:02 +00001715
1716 // Increasing the Scattering function is OK for the moment, because
1717 // we are using a depth first iterator and the program is well structured.
1718 ++Scatter[loopDepth];
1719 }
1720
1721 if (!L)
1722 return;
1723
1724 // Exiting a loop region.
1725 Scatter[loopDepth] = 0;
1726 NestLoops.pop_back();
Tobias Grosser74394f02013-01-14 22:40:23 +00001727 ++Scatter[loopDepth - 1];
Tobias Grosser75805372011-04-29 06:27:02 +00001728}
1729
1730//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00001731ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
1732 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00001733 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001734}
1735
1736ScopInfo::~ScopInfo() {
1737 clear();
1738 isl_ctx_free(ctx);
1739}
1740
Tobias Grosser75805372011-04-29 06:27:02 +00001741void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1742 AU.addRequired<LoopInfo>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001743 AU.addRequired<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001744 AU.addRequired<ScalarEvolution>();
1745 AU.addRequired<TempScopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001746 AU.addRequired<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00001747 AU.setPreservesAll();
1748}
1749
1750bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
1751 LoopInfo &LI = getAnalysis<LoopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001752 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00001753 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1754
1755 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop(R);
1756
1757 // This region is no Scop.
1758 if (!tempScop) {
1759 scop = 0;
1760 return false;
1761 }
1762
1763 // Statistics.
1764 ++ScopFound;
Tobias Grosser74394f02013-01-14 22:40:23 +00001765 if (tempScop->getMaxLoopDepth() > 0)
1766 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00001767
Tobias Grosserb76f38532011-08-20 11:11:25 +00001768 scop = new Scop(*tempScop, LI, SE, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001769
Johannes Doerfert9143d672014-09-27 11:02:39 +00001770 if (!PollyUseRuntimeAliasChecks)
1771 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001772
Johannes Doerfert9143d672014-09-27 11:02:39 +00001773 // If a problem occurs while building the alias groups we need to delete
1774 // this SCoP and pretend it wasn't valid in the first place.
1775 if (scop->buildAliasGroups(AA))
1776 return false;
1777
1778 --ScopFound;
1779 if (tempScop->getMaxLoopDepth() > 0)
1780 --RichScopFound;
1781
1782 DEBUG(dbgs()
1783 << "\n\nNOTE: Run time checks for " << scop->getNameStr()
1784 << " could not be created as the number of parameters involved is too "
1785 "high. The SCoP will be "
1786 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust the "
1787 "maximal number of parameters but be advised that the compile time "
1788 "might increase exponentially.\n\n");
1789
1790 delete scop;
1791 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00001792 return false;
1793}
1794
1795char ScopInfo::ID = 0;
1796
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001797Pass *polly::createScopInfoPass() { return new ScopInfo(); }
1798
Tobias Grosser73600b82011-10-08 00:30:40 +00001799INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
1800 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001801 false);
Johannes Doerfertb164c792014-09-18 11:17:17 +00001802INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001803INITIALIZE_PASS_DEPENDENCY(LoopInfo);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001804INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001805INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1806INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Tobias Grosser73600b82011-10-08 00:30:40 +00001807INITIALIZE_PASS_END(ScopInfo, "polly-scops",
1808 "Polly - Create polyhedral description of Scops", false,
1809 false)