blob: 654a95c400d679db5c68c7638b02a2becc83c8ef [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
Tobias Grosser75805372011-04-29 06:27:02 +000020#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000021#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000022#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000023#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000024#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000025#include "polly/Support/ScopHelper.h"
Sebastian Pop27c10c62013-03-22 22:07:43 +000026#include "polly/TempScopInfo.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000027#include "llvm/ADT/MapVector.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000028#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000029#include "llvm/ADT/Statistic.h"
Johannes Doerfertecff11d2015-05-22 23:43:58 +000030#include "llvm/ADT/STLExtras.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000031#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000032#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000033#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser83628182013-05-07 08:11:54 +000034#include "llvm/Analysis/RegionIterator.h"
35#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000036#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000037#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000038#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000039#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000040#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000041#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000042#include "isl/printer.h"
43#include "isl/set.h"
44#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000045#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000046#include "isl/val.h"
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 Grosser71500722015-03-28 15:11:14 +000072static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
73 "polly-rtc-max-arrays-per-group",
74 cl::desc("The maximal number of arrays to compare in each alias group."),
75 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
76
Tobias Grosser0695ee42013-09-17 03:30:31 +000077/// Translate a 'const SCEV *' expression in an isl_pw_aff.
Tobias Grosserabfbe632013-02-05 12:09:06 +000078struct SCEVAffinator : public SCEVVisitor<SCEVAffinator, isl_pw_aff *> {
Tobias Grosser0695ee42013-09-17 03:30:31 +000079public:
Tobias Grosser0695ee42013-09-17 03:30:31 +000080 /// @brief Translate a 'const SCEV *' to an isl_pw_aff.
81 ///
82 /// @param Stmt The location at which the scalar evolution expression
83 /// is evaluated.
84 /// @param Expr The expression that is translated.
85 static __isl_give isl_pw_aff *getPwAff(ScopStmt *Stmt, const SCEV *Expr);
86
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000087private:
Tobias Grosser3cc99742012-06-06 16:33:15 +000088 isl_ctx *Ctx;
Tobias Grosserf5338802011-10-06 00:03:35 +000089 int NbLoopSpaces;
Tobias Grosser3cc99742012-06-06 16:33:15 +000090 const Scop *S;
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000091
Tobias Grosser0695ee42013-09-17 03:30:31 +000092 SCEVAffinator(const ScopStmt *Stmt);
93 int getLoopDepth(const Loop *L);
Tobias Grosser60b54f12011-11-08 15:41:28 +000094
Tobias Grosser0695ee42013-09-17 03:30:31 +000095 __isl_give isl_pw_aff *visit(const SCEV *Expr);
96 __isl_give isl_pw_aff *visitConstant(const SCEVConstant *Expr);
97 __isl_give isl_pw_aff *visitTruncateExpr(const SCEVTruncateExpr *Expr);
98 __isl_give isl_pw_aff *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr);
99 __isl_give isl_pw_aff *visitSignExtendExpr(const SCEVSignExtendExpr *Expr);
100 __isl_give isl_pw_aff *visitAddExpr(const SCEVAddExpr *Expr);
101 __isl_give isl_pw_aff *visitMulExpr(const SCEVMulExpr *Expr);
102 __isl_give isl_pw_aff *visitUDivExpr(const SCEVUDivExpr *Expr);
103 __isl_give isl_pw_aff *visitAddRecExpr(const SCEVAddRecExpr *Expr);
104 __isl_give isl_pw_aff *visitSMaxExpr(const SCEVSMaxExpr *Expr);
105 __isl_give isl_pw_aff *visitUMaxExpr(const SCEVUMaxExpr *Expr);
106 __isl_give isl_pw_aff *visitUnknown(const SCEVUnknown *Expr);
Johannes Doerfertb9d18882015-02-11 14:54:50 +0000107 __isl_give isl_pw_aff *visitSDivInstruction(Instruction *SDiv);
Tobias Grosser50165ff2015-06-24 04:13:29 +0000108 __isl_give isl_pw_aff *visitSRemInstruction(Instruction *SDiv);
Tobias Grosser60b54f12011-11-08 15:41:28 +0000109
Tobias Grosser0695ee42013-09-17 03:30:31 +0000110 friend struct SCEVVisitor<SCEVAffinator, isl_pw_aff *>;
111};
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000112
Tobias Grosser0695ee42013-09-17 03:30:31 +0000113SCEVAffinator::SCEVAffinator(const ScopStmt *Stmt)
114 : Ctx(Stmt->getIslCtx()), NbLoopSpaces(Stmt->getNumIterators()),
115 S(Stmt->getParent()) {}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000116
Tobias Grosser0695ee42013-09-17 03:30:31 +0000117__isl_give isl_pw_aff *SCEVAffinator::getPwAff(ScopStmt *Stmt,
118 const SCEV *Scev) {
119 Scop *S = Stmt->getParent();
120 const Region *Reg = &S->getRegion();
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000121
Tobias Grosser0695ee42013-09-17 03:30:31 +0000122 S->addParams(getParamsInAffineExpr(Reg, Scev, *S->getSE()));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000123
Tobias Grosser0695ee42013-09-17 03:30:31 +0000124 SCEVAffinator Affinator(Stmt);
125 return Affinator.visit(Scev);
126}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000127
Tobias Grosser0695ee42013-09-17 03:30:31 +0000128__isl_give isl_pw_aff *SCEVAffinator::visit(const SCEV *Expr) {
129 // In case the scev is a valid parameter, we do not further analyze this
130 // expression, but create a new parameter in the isl_pw_aff. This allows us
131 // to treat subexpressions that we cannot translate into an piecewise affine
132 // expression, as constant parameters of the piecewise affine expression.
133 if (isl_id *Id = S->getIdForParam(Expr)) {
134 isl_space *Space = isl_space_set_alloc(Ctx, 1, NbLoopSpaces);
135 Space = isl_space_set_dim_id(Space, isl_dim_param, 0, Id);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000136
Tobias Grosser0695ee42013-09-17 03:30:31 +0000137 isl_set *Domain = isl_set_universe(isl_space_copy(Space));
138 isl_aff *Affine = isl_aff_zero_on_domain(isl_local_space_from_space(Space));
139 Affine = isl_aff_add_coefficient_si(Affine, isl_dim_param, 0, 1);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000140
141 return isl_pw_aff_alloc(Domain, Affine);
142 }
143
Tobias Grosser0695ee42013-09-17 03:30:31 +0000144 return SCEVVisitor<SCEVAffinator, isl_pw_aff *>::visit(Expr);
145}
146
Tobias Grosser0d170132013-10-03 13:09:19 +0000147__isl_give isl_pw_aff *SCEVAffinator::visitConstant(const SCEVConstant *Expr) {
Tobias Grosser0695ee42013-09-17 03:30:31 +0000148 ConstantInt *Value = Expr->getValue();
149 isl_val *v;
150
151 // LLVM does not define if an integer value is interpreted as a signed or
152 // unsigned value. Hence, without further information, it is unknown how
153 // this value needs to be converted to GMP. At the moment, we only support
154 // signed operations. So we just interpret it as signed. Later, there are
155 // two options:
156 //
157 // 1. We always interpret any value as signed and convert the values on
158 // demand.
159 // 2. We pass down the signedness of the calculation and use it to interpret
160 // this constant correctly.
161 v = isl_valFromAPInt(Ctx, Value->getValue(), /* isSigned */ true);
162
163 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
Johannes Doerfert9c147372014-11-19 15:36:59 +0000164 isl_local_space *ls = isl_local_space_from_space(Space);
165 return isl_pw_aff_from_aff(isl_aff_val_on_domain(ls, v));
Tobias Grosser0695ee42013-09-17 03:30:31 +0000166}
167
168__isl_give isl_pw_aff *
169SCEVAffinator::visitTruncateExpr(const SCEVTruncateExpr *Expr) {
170 llvm_unreachable("SCEVTruncateExpr not yet supported");
171}
172
173__isl_give isl_pw_aff *
174SCEVAffinator::visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
175 llvm_unreachable("SCEVZeroExtendExpr not yet supported");
176}
177
178__isl_give isl_pw_aff *
179SCEVAffinator::visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
180 // Assuming the value is signed, a sign extension is basically a noop.
181 // TODO: Reconsider this as soon as we support unsigned values.
182 return visit(Expr->getOperand());
183}
184
185__isl_give isl_pw_aff *SCEVAffinator::visitAddExpr(const SCEVAddExpr *Expr) {
186 isl_pw_aff *Sum = visit(Expr->getOperand(0));
187
188 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
189 isl_pw_aff *NextSummand = visit(Expr->getOperand(i));
190 Sum = isl_pw_aff_add(Sum, NextSummand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000191 }
192
Tobias Grosser0695ee42013-09-17 03:30:31 +0000193 // TODO: Check for NSW and NUW.
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000194
Tobias Grosser0695ee42013-09-17 03:30:31 +0000195 return Sum;
196}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000197
Tobias Grosser0695ee42013-09-17 03:30:31 +0000198__isl_give isl_pw_aff *SCEVAffinator::visitMulExpr(const SCEVMulExpr *Expr) {
Johannes Doerfertbe409962015-03-29 20:45:09 +0000199 // Divide Expr into a constant part and the rest. Then visit both and multiply
200 // the result to obtain the representation for Expr. While the second part of
201 // ConstantAndLeftOverPair might still be a SCEVMulExpr we will not get to
202 // this point again. The reason is that if it is a multiplication it consists
203 // only of parameters and we will stop in the visit(const SCEV *) function and
204 // return the isl_pw_aff for that parameter.
205 auto ConstantAndLeftOverPair = extractConstantFactor(Expr, *S->getSE());
206 return isl_pw_aff_mul(visit(ConstantAndLeftOverPair.first),
207 visit(ConstantAndLeftOverPair.second));
Tobias Grosser0695ee42013-09-17 03:30:31 +0000208}
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
Johannes Doerfertd5d8f672015-04-26 19:55:21 +0000218 auto Flags = Expr->getNoWrapFlags();
219
Tobias Grosser0695ee42013-09-17 03:30:31 +0000220 // Directly generate isl_pw_aff for Expr if 'start' is zero.
221 if (Expr->getStart()->isZero()) {
222 assert(S->getRegion().contains(Expr->getLoop()) &&
223 "Scop does not contain the loop referenced in this AddRec");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000224
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000225 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser0695ee42013-09-17 03:30:31 +0000226 isl_pw_aff *Step = visit(Expr->getOperand(1));
227 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
228 isl_local_space *LocalSpace = isl_local_space_from_space(Space);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000229
Tobias Grosser0695ee42013-09-17 03:30:31 +0000230 int loopDimension = getLoopDepth(Expr->getLoop());
231
232 isl_aff *LAff = isl_aff_set_coefficient_si(
233 isl_aff_zero_on_domain(LocalSpace), isl_dim_in, loopDimension, 1);
234 isl_pw_aff *LPwAff = isl_pw_aff_from_aff(LAff);
235
236 // TODO: Do we need to check for NSW and NUW?
237 return isl_pw_aff_add(Start, isl_pw_aff_mul(Step, LPwAff));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000238 }
239
Tobias Grosser0695ee42013-09-17 03:30:31 +0000240 // Translate AddRecExpr from '{start, +, inc}' into 'start + {0, +, inc}'
241 // if 'start' is not zero.
Johannes Doerfertd5d8f672015-04-26 19:55:21 +0000242 // TODO: Using the original SCEV no-wrap flags is not always safe, however
243 // as our code generation is reordering the expression anyway it doesn't
244 // really matter.
Tobias Grosser0695ee42013-09-17 03:30:31 +0000245 ScalarEvolution &SE = *S->getSE();
Johannes Doerfertd5d8f672015-04-26 19:55:21 +0000246 const SCEV *ZeroStartExpr =
247 SE.getAddRecExpr(SE.getConstant(Expr->getStart()->getType(), 0),
248 Expr->getStepRecurrence(SE), Expr->getLoop(), Flags);
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
Johannes Doerfertb9d18882015-02-11 14:54:50 +0000271__isl_give isl_pw_aff *SCEVAffinator::visitSDivInstruction(Instruction *SDiv) {
272 assert(SDiv->getOpcode() == Instruction::SDiv && "Assumed SDiv instruction!");
273 auto *SE = S->getSE();
274
275 auto *Divisor = SDiv->getOperand(1);
276 auto *DivisorSCEV = SE->getSCEV(Divisor);
277 auto *DivisorPWA = visit(DivisorSCEV);
278 assert(isa<ConstantInt>(Divisor) &&
279 "SDiv is no parameter but has a non-constant RHS.");
280
281 auto *Dividend = SDiv->getOperand(0);
282 auto *DividendSCEV = SE->getSCEV(Dividend);
283 auto *DividendPWA = visit(DividendSCEV);
284 return isl_pw_aff_tdiv_q(DividendPWA, DivisorPWA);
285}
286
Tobias Grosser50165ff2015-06-24 04:13:29 +0000287__isl_give isl_pw_aff *SCEVAffinator::visitSRemInstruction(Instruction *SRem) {
288 assert(SRem->getOpcode() == Instruction::SRem && "Assumed SRem instruction!");
289 auto *SE = S->getSE();
290
291 auto *Divisor = dyn_cast<ConstantInt>(SRem->getOperand(1));
292 assert(Divisor && "SRem is no parameter but has a non-constant RHS.");
293 auto *DivisorVal = isl_valFromAPInt(Ctx, Divisor->getValue(),
294 /* isSigned */ true);
295
296 auto *Dividend = SRem->getOperand(0);
297 auto *DividendSCEV = SE->getSCEV(Dividend);
298 auto *DividendPWA = visit(DividendSCEV);
299
300 return isl_pw_aff_mod_val(DividendPWA, isl_val_abs(DivisorVal));
301}
302
Tobias Grosser0695ee42013-09-17 03:30:31 +0000303__isl_give isl_pw_aff *SCEVAffinator::visitUnknown(const SCEVUnknown *Expr) {
Johannes Doerfertb9d18882015-02-11 14:54:50 +0000304 if (Instruction *I = dyn_cast<Instruction>(Expr->getValue())) {
305 switch (I->getOpcode()) {
306 case Instruction::SDiv:
307 return visitSDivInstruction(I);
Tobias Grosser50165ff2015-06-24 04:13:29 +0000308 case Instruction::SRem:
309 return visitSRemInstruction(I);
Johannes Doerfertb9d18882015-02-11 14:54:50 +0000310 default:
311 break; // Fall through.
312 }
313 }
314
315 llvm_unreachable(
316 "Unknowns SCEV was neither parameter nor a valid instruction.");
Tobias Grosser0695ee42013-09-17 03:30:31 +0000317}
318
319int SCEVAffinator::getLoopDepth(const Loop *L) {
320 Loop *outerLoop = S->getRegion().outermostLoopInRegion(const_cast<Loop *>(L));
321 assert(outerLoop && "Scop does not contain this loop");
322 return L->getLoopDepth() - outerLoop->getLoopDepth();
323}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000324
Johannes Doerferte7044942015-02-24 11:58:30 +0000325/// @brief Add the bounds of @p Range to the set @p S for dimension @p dim.
326static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
327 const ConstantRange &Range,
328 int dim,
329 enum isl_dim_type type) {
330 isl_val *V;
331 isl_ctx *ctx = isl_set_get_ctx(S);
332
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000333 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
334 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000335 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000336 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
337
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000338 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000339 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000340 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000341 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000342 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
343
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000344 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000345 return isl_set_union(SLB, SUB);
346 else
347 return isl_set_intersect(SLB, SUB);
348}
349
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000350ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000351 const SmallVector<const SCEV *, 4> &DimensionSizes)
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000352 : BasePtr(BasePtr), ElementType(ElementType),
353 DimensionSizes(DimensionSizes) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000354 const std::string BasePtrName = getIslCompatibleName("MemRef_", BasePtr, "");
355 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
356}
357
358ScopArrayInfo::~ScopArrayInfo() { isl_id_free(Id); }
359
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000360std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
361
362int ScopArrayInfo::getElemSizeInBytes() const {
363 return ElementType->getPrimitiveSizeInBits() / 8;
364}
365
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000366isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
367
368void ScopArrayInfo::dump() const { print(errs()); }
369
370void ScopArrayInfo::print(raw_ostream &OS) const {
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000371 OS.indent(8) << *getElementType() << " " << getName() << "[*]";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000372 for (unsigned u = 0; u < getNumberOfDimensions(); u++)
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000373 OS << "[" << *DimensionSizes[u] << "]";
374 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000375}
376
377const ScopArrayInfo *
378ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
379 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
380 assert(Id && "Output dimension didn't have an ID");
381 return getFromId(Id);
382}
383
384const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
385 void *User = isl_id_get_user(Id);
386 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
387 isl_id_free(Id);
388 return SAI;
389}
390
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000391const std::string
392MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
393 switch (RT) {
394 case MemoryAccess::RT_NONE:
395 llvm_unreachable("Requested a reduction operator string for a memory "
396 "access which isn't a reduction");
397 case MemoryAccess::RT_ADD:
398 return "+";
399 case MemoryAccess::RT_MUL:
400 return "*";
401 case MemoryAccess::RT_BOR:
402 return "|";
403 case MemoryAccess::RT_BXOR:
404 return "^";
405 case MemoryAccess::RT_BAND:
406 return "&";
407 }
408 llvm_unreachable("Unknown reduction type");
409 return "";
410}
411
Johannes Doerfertf6183392014-07-01 20:52:51 +0000412/// @brief Return the reduction type for a given binary operator
413static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
414 const Instruction *Load) {
415 if (!BinOp)
416 return MemoryAccess::RT_NONE;
417 switch (BinOp->getOpcode()) {
418 case Instruction::FAdd:
419 if (!BinOp->hasUnsafeAlgebra())
420 return MemoryAccess::RT_NONE;
421 // Fall through
422 case Instruction::Add:
423 return MemoryAccess::RT_ADD;
424 case Instruction::Or:
425 return MemoryAccess::RT_BOR;
426 case Instruction::Xor:
427 return MemoryAccess::RT_BXOR;
428 case Instruction::And:
429 return MemoryAccess::RT_BAND;
430 case Instruction::FMul:
431 if (!BinOp->hasUnsafeAlgebra())
432 return MemoryAccess::RT_NONE;
433 // Fall through
434 case Instruction::Mul:
435 if (DisableMultiplicativeReductions)
436 return MemoryAccess::RT_NONE;
437 return MemoryAccess::RT_MUL;
438 default:
439 return MemoryAccess::RT_NONE;
440 }
441}
Tobias Grosser75805372011-04-29 06:27:02 +0000442//===----------------------------------------------------------------------===//
443
444MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000445 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000446 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000447 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000448}
449
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000450static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
451 switch (Access.getType()) {
452 case IRAccess::READ:
453 return MemoryAccess::READ;
454 case IRAccess::MUST_WRITE:
455 return MemoryAccess::MUST_WRITE;
456 case IRAccess::MAY_WRITE:
457 return MemoryAccess::MAY_WRITE;
458 }
459 llvm_unreachable("Unknown IRAccess type!");
460}
461
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000462const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
463 isl_id *ArrayId = getArrayId();
464 void *User = isl_id_get_user(ArrayId);
465 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
466 isl_id_free(ArrayId);
467 return SAI;
468}
469
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000470__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000471 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
472}
473
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000474__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
475 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000476 isl_map *Schedule, *ScheduledAccRel;
477 isl_union_set *UDomain;
478
479 UDomain = isl_union_set_from_set(getStatement()->getDomain());
480 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
481 Schedule = isl_map_from_union_map(USchedule);
482 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
483 return isl_pw_multi_aff_from_map(ScheduledAccRel);
484}
485
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000486__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000487 return isl_map_copy(AccessRelation);
488}
489
Johannes Doerferta99130f2014-10-13 12:58:03 +0000490std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000491 return stringFromIslObj(AccessRelation);
492}
493
Johannes Doerferta99130f2014-10-13 12:58:03 +0000494__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000495 return isl_map_get_space(AccessRelation);
496}
497
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000498__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000499 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000500}
501
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000502__isl_give isl_basic_map *
503MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000504 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000505 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000506
Tobias Grosser084d8f72012-05-29 09:29:44 +0000507 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000508 isl_basic_set_universe(Statement->getDomainSpace()),
509 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000510}
511
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000512// Formalize no out-of-bound access assumption
513//
514// When delinearizing array accesses we optimistically assume that the
515// delinearized accesses do not access out of bound locations (the subscript
516// expression of each array evaluates for each statement instance that is
517// executed to a value that is larger than zero and strictly smaller than the
518// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000519// dimension for which we do not need to assume any upper bound. At this point
520// we formalize this assumption to ensure that at code generation time the
521// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000522//
523// To find the set of constraints necessary to avoid out of bound accesses, we
524// first build the set of data locations that are not within array bounds. We
525// then apply the reverse access relation to obtain the set of iterations that
526// may contain invalid accesses and reduce this set of iterations to the ones
527// that are actually executed by intersecting them with the domain of the
528// statement. If we now project out all loop dimensions, we obtain a set of
529// parameters that may cause statement instances to be executed that may
530// possibly yield out of bound memory accesses. The complement of these
531// constraints is the set of constraints that needs to be assumed to ensure such
532// statement instances are never executed.
533void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000534 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000535 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000536 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000537 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
538 isl_pw_aff *Var =
539 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
540 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
541
542 isl_set *DimOutside;
543
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000544 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
545 isl_pw_aff *SizeE = SCEVAffinator::getPwAff(Statement, Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000546
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000547 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
548 Statement->getNumIterators());
549 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
550 isl_space_dim(Space, isl_dim_set));
551 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
552 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000553
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000554 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000555
556 Outside = isl_set_union(Outside, DimOutside);
557 }
558
559 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
560 Outside = isl_set_intersect(Outside, Statement->getDomain());
561 Outside = isl_set_params(Outside);
562 Outside = isl_set_complement(Outside);
563 Statement->getParent()->addAssumption(Outside);
564 isl_space_free(Space);
565}
566
Johannes Doerferte7044942015-02-24 11:58:30 +0000567void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
568 ScalarEvolution *SE = Statement->getParent()->getSE();
569
570 Value *Ptr = getPointerOperand(*getAccessInstruction());
571 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
572 return;
573
574 auto *PtrSCEV = SE->getSCEV(Ptr);
575 if (isa<SCEVCouldNotCompute>(PtrSCEV))
576 return;
577
578 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
579 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
580 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
581
582 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
583 if (Range.isFullSet())
584 return;
585
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000586 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000587 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000588 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
589 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
590
591 auto Min = LB.sdiv(APInt(BW, ElementSize));
592 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000593
594 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
595 AccessRange =
596 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
597 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
598}
599
Tobias Grosser619190d2015-03-30 17:22:28 +0000600__isl_give isl_map *MemoryAccess::foldAccess(const IRAccess &Access,
601 __isl_take isl_map *AccessRelation,
602 ScopStmt *Statement) {
603 int Size = Access.Subscripts.size();
604
605 for (int i = Size - 2; i >= 0; --i) {
606 isl_space *Space;
607 isl_map *MapOne, *MapTwo;
608 isl_pw_aff *DimSize = SCEVAffinator::getPwAff(Statement, Access.Sizes[i]);
609
610 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
611 isl_pw_aff_free(DimSize);
612 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
613
614 Space = isl_map_get_space(AccessRelation);
615 Space = isl_space_map_from_set(isl_space_range(Space));
616 Space = isl_space_align_params(Space, SpaceSize);
617
618 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
619 isl_id_free(ParamId);
620
621 MapOne = isl_map_universe(isl_space_copy(Space));
622 for (int j = 0; j < Size; ++j)
623 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
624 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
625
626 MapTwo = isl_map_universe(isl_space_copy(Space));
627 for (int j = 0; j < Size; ++j)
628 if (j < i || j > i + 1)
629 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
630
631 isl_local_space *LS = isl_local_space_from_space(Space);
632 isl_constraint *C;
633 C = isl_equality_alloc(isl_local_space_copy(LS));
634 C = isl_constraint_set_constant_si(C, -1);
635 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
636 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
637 MapTwo = isl_map_add_constraint(MapTwo, C);
638 C = isl_equality_alloc(LS);
639 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
640 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
641 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
642 MapTwo = isl_map_add_constraint(MapTwo, C);
643 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
644
645 MapOne = isl_map_union(MapOne, MapTwo);
646 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
647 }
648 return AccessRelation;
649}
650
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000651MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000652 ScopStmt *Statement, const ScopArrayInfo *SAI,
653 int Identifier)
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000654 : AccType(getMemoryAccessType(Access)), Statement(Statement), Inst(AccInst),
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000655 newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000656
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000657 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000658 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000659 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000660
661 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000662
Tobias Grossere29d31c2015-05-15 12:24:09 +0000663 auto IdName = "__polly_array_ref_ " + std::to_string(Identifier);
664 Id = isl_id_alloc(Ctx, IdName.c_str(), nullptr);
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000665
Tobias Grossera1879642011-12-20 10:43:14 +0000666 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000667 // We overapproximate non-affine accesses with a possible access to the
668 // whole array. For read accesses it does not make a difference, if an
669 // access must or may happen. However, for write accesses it is important to
670 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000671 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000672 AccessRelation =
673 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000674
675 computeBoundsOnAccessRelation(Access.getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000676 return;
677 }
678
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000679 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000680 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000681
Tobias Grosser79baa212014-04-10 08:38:02 +0000682 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Sebastian Pop18016682014-04-08 21:20:44 +0000683 isl_pw_aff *Affine =
684 SCEVAffinator::getPwAff(Statement, Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000685
Sebastian Pop422e33f2014-06-03 18:16:31 +0000686 if (Size == 1) {
687 // For the non delinearized arrays, divide the access function of the last
688 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000689 //
690 // A stride one array access in C expressed as A[i] is expressed in
691 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
692 // two subsequent values of 'i' index two values that are stored next to
693 // each other in memory. By this division we make this characteristic
694 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000695 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000696 Affine = isl_pw_aff_scale_down_val(Affine, v);
697 }
698
699 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
700
Tobias Grosser79baa212014-04-10 08:38:02 +0000701 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000702 }
703
Tobias Grosser619190d2015-03-30 17:22:28 +0000704 AccessRelation = foldAccess(Access, AccessRelation, Statement);
705
Tobias Grosser79baa212014-04-10 08:38:02 +0000706 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000707 AccessRelation = isl_map_set_tuple_id(
708 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000709 AccessRelation =
710 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
711
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000712 assumeNoOutOfBound(Access);
Tobias Grosseraa660a92015-03-30 00:07:50 +0000713 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000714 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000715}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000716
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000717void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000718 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000719 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000720}
721
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000722const std::string MemoryAccess::getReductionOperatorStr() const {
723 return MemoryAccess::getReductionOperatorStr(getReductionType());
724}
725
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000726__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
727
Johannes Doerfertf6183392014-07-01 20:52:51 +0000728raw_ostream &polly::operator<<(raw_ostream &OS,
729 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000730 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000731 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000732 else
733 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000734 return OS;
735}
736
Tobias Grosser75805372011-04-29 06:27:02 +0000737void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000738 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000739 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000740 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000741 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000742 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000743 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000744 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000745 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000746 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000747 break;
748 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000749 OS << "[Reduction Type: " << getReductionType() << "] ";
750 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000751 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000752}
753
Tobias Grosser74394f02013-01-14 22:40:23 +0000754void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000755
756// Create a map in the size of the provided set domain, that maps from the
757// one element of the provided set domain to another element of the provided
758// set domain.
759// The mapping is limited to all points that are equal in all but the last
760// dimension and for which the last dimension of the input is strict smaller
761// than the last dimension of the output.
762//
763// getEqualAndLarger(set[i0, i1, ..., iX]):
764//
765// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
766// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
767//
Tobias Grosserf5338802011-10-06 00:03:35 +0000768static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000769 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000770 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000771 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000772
773 // Set all but the last dimension to be equal for the input and output
774 //
775 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
776 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000777 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000778 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000779
780 // Set the last dimension of the input to be strict smaller than the
781 // last dimension of the output.
782 //
783 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000784 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
785 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000786 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000787}
788
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000789__isl_give isl_set *
790MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000791 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000792 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000793 isl_space *Space = isl_space_range(isl_map_get_space(S));
794 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000795
Sebastian Popa00a0292012-12-18 07:46:06 +0000796 S = isl_map_reverse(S);
797 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000798
Sebastian Popa00a0292012-12-18 07:46:06 +0000799 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
800 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
801 NextScatt = isl_map_apply_domain(NextScatt, S);
802 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000803
Sebastian Popa00a0292012-12-18 07:46:06 +0000804 isl_set *Deltas = isl_map_deltas(NextScatt);
805 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000806}
807
Sebastian Popa00a0292012-12-18 07:46:06 +0000808bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000809 int StrideWidth) const {
810 isl_set *Stride, *StrideX;
811 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000812
Sebastian Popa00a0292012-12-18 07:46:06 +0000813 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000814 StrideX = isl_set_universe(isl_set_get_space(Stride));
815 StrideX = isl_set_fix_si(StrideX, isl_dim_set, 0, StrideWidth);
816 IsStrideX = isl_set_is_equal(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000817
Tobias Grosser28dd4862012-01-24 16:42:16 +0000818 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000819 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000820
Tobias Grosser28dd4862012-01-24 16:42:16 +0000821 return IsStrideX;
822}
823
Sebastian Popa00a0292012-12-18 07:46:06 +0000824bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
825 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000826}
827
Tobias Grosser79baa212014-04-10 08:38:02 +0000828bool MemoryAccess::isScalar() const {
829 return isl_map_n_out(AccessRelation) == 0;
830}
831
Sebastian Popa00a0292012-12-18 07:46:06 +0000832bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
833 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000834}
835
Tobias Grosser5d453812011-10-06 00:04:11 +0000836void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000837 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000838 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000839}
Tobias Grosser75805372011-04-29 06:27:02 +0000840
841//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000842
Tobias Grosser54839312015-04-21 11:37:25 +0000843isl_map *ScopStmt::getSchedule() const { return isl_map_copy(Schedule); }
Tobias Grossercf3942d2011-10-06 00:04:05 +0000844
Tobias Grosser37eb4222014-02-20 21:43:54 +0000845void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
846 assert(isl_set_is_subset(NewDomain, Domain) &&
847 "New domain is not a subset of old domain!");
848 isl_set_free(Domain);
849 Domain = NewDomain;
Tobias Grosser54839312015-04-21 11:37:25 +0000850 Schedule = isl_map_intersect_domain(Schedule, isl_set_copy(Domain));
Tobias Grosser37eb4222014-02-20 21:43:54 +0000851}
852
Tobias Grosser54839312015-04-21 11:37:25 +0000853void ScopStmt::setSchedule(__isl_take isl_map *NewSchedule) {
854 assert(NewSchedule && "New schedule is nullptr");
855 isl_map_free(Schedule);
856 Schedule = NewSchedule;
Tobias Grosserb76f38532011-08-20 11:11:25 +0000857}
858
Tobias Grosser54839312015-04-21 11:37:25 +0000859void ScopStmt::buildSchedule(SmallVectorImpl<unsigned> &ScheduleVec) {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000860 unsigned NbIterators = getNumIterators();
Tobias Grosser54839312015-04-21 11:37:25 +0000861 unsigned NbScheduleDims = Parent.getMaxLoopDepth() * 2 + 1;
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000862
Tobias Grosser54839312015-04-21 11:37:25 +0000863 isl_space *Space = isl_space_set_alloc(getIslCtx(), 0, NbScheduleDims);
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000864
Tobias Grosser54839312015-04-21 11:37:25 +0000865 Schedule = isl_map_from_domain_and_range(isl_set_universe(getDomainSpace()),
Tobias Grosser654af8f2015-04-21 11:42:01 +0000866 isl_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000867
868 // Loop dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000869 for (unsigned i = 0; i < NbIterators; ++i)
Tobias Grosser654af8f2015-04-21 11:42:01 +0000870 Schedule = isl_map_equate(Schedule, isl_dim_out, 2 * i + 1, isl_dim_in, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000871
872 // Constant dimensions
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000873 for (unsigned i = 0; i < NbIterators + 1; ++i)
Tobias Grosser54839312015-04-21 11:37:25 +0000874 Schedule = isl_map_fix_si(Schedule, isl_dim_out, 2 * i, ScheduleVec[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000875
Tobias Grosser54839312015-04-21 11:37:25 +0000876 // Fill schedule dimensions.
877 for (unsigned i = 2 * NbIterators + 1; i < NbScheduleDims; ++i)
878 Schedule = isl_map_fix_si(Schedule, isl_dim_out, i, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000879
Tobias Grosser54839312015-04-21 11:37:25 +0000880 Schedule = isl_map_align_params(Schedule, Parent.getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000881}
882
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000883void ScopStmt::buildAccesses(TempScop &tempScop, BasicBlock *Block,
884 bool isApproximated) {
885 AccFuncSetType *AFS = tempScop.getAccessFunctions(Block);
886 if (!AFS)
887 return;
888
889 for (auto &AccessPair : *AFS) {
890 IRAccess &Access = AccessPair.first;
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000891 Instruction *AccessInst = AccessPair.second;
892
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000893 Type *ElementType = getAccessInstType(AccessInst);
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000894 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000895 Access.getBase(), ElementType, Access.Sizes);
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000896
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000897 if (isApproximated && Access.isWrite())
898 Access.setMayWrite();
899
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000900 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
901 if (!MAL)
902 MAL = new MemoryAccessList();
903 MAL->emplace_front(Access, AccessInst, this, SAI, MemAccs.size());
904 MemAccs.push_back(&MAL->front());
Tobias Grosser75805372011-04-29 06:27:02 +0000905 }
906}
907
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000908void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000909 for (MemoryAccess *MA : *this)
910 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000911
912 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser54839312015-04-21 11:37:25 +0000913 Schedule = isl_map_align_params(Schedule, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000914}
915
Tobias Grosser65b00582011-11-08 15:41:19 +0000916__isl_give isl_set *ScopStmt::buildConditionSet(const Comparison &Comp) {
Tobias Grossera601fbd2011-11-09 22:34:44 +0000917 isl_pw_aff *L = SCEVAffinator::getPwAff(this, Comp.getLHS());
918 isl_pw_aff *R = SCEVAffinator::getPwAff(this, Comp.getRHS());
Tobias Grosser75805372011-04-29 06:27:02 +0000919
Tobias Grosserd2795d02011-08-18 07:51:40 +0000920 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000921 case ICmpInst::ICMP_EQ:
Tobias Grosser048c8792011-10-23 20:59:20 +0000922 return isl_pw_aff_eq_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000923 case ICmpInst::ICMP_NE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000924 return isl_pw_aff_ne_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000925 case ICmpInst::ICMP_SLT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000926 return isl_pw_aff_lt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000927 case ICmpInst::ICMP_SLE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000928 return isl_pw_aff_le_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000929 case ICmpInst::ICMP_SGT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000930 return isl_pw_aff_gt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000931 case ICmpInst::ICMP_SGE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000932 return isl_pw_aff_ge_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000933 case ICmpInst::ICMP_ULT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000934 return isl_pw_aff_lt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000935 case ICmpInst::ICMP_UGT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000936 return isl_pw_aff_gt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000937 case ICmpInst::ICMP_ULE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000938 return isl_pw_aff_le_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000939 case ICmpInst::ICMP_UGE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000940 return isl_pw_aff_ge_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000941 default:
942 llvm_unreachable("Non integer predicate not supported");
943 }
Tobias Grosser75805372011-04-29 06:27:02 +0000944}
945
Tobias Grossere19661e2011-10-07 08:46:57 +0000946__isl_give isl_set *ScopStmt::addLoopBoundsToDomain(__isl_take isl_set *Domain,
Tobias Grosser60b54f12011-11-08 15:41:28 +0000947 TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000948 isl_space *Space;
949 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000950
Tobias Grossere19661e2011-10-07 08:46:57 +0000951 Space = isl_set_get_space(Domain);
952 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000953
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000954 ScalarEvolution *SE = getParent()->getSE();
Tobias Grosser75805372011-04-29 06:27:02 +0000955 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000956 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000957 isl_pw_aff *IV =
958 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000959
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000960 // 0 <= IV.
961 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
962 Domain = isl_set_intersect(Domain, LowerBound);
963
964 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000965 const Loop *L = getLoopForDimension(i);
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000966 const SCEV *LatchExecutions = SE->getBackedgeTakenCount(L);
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000967 isl_pw_aff *UpperBound = SCEVAffinator::getPwAff(this, LatchExecutions);
968 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
Tobias Grosser75805372011-04-29 06:27:02 +0000969 Domain = isl_set_intersect(Domain, UpperBoundSet);
970 }
971
Tobias Grosserf5338802011-10-06 00:03:35 +0000972 isl_local_space_free(LocalSpace);
Tobias Grossere19661e2011-10-07 08:46:57 +0000973 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000974}
975
Tobias Grossere602a072013-05-07 07:30:56 +0000976__isl_give isl_set *ScopStmt::addConditionsToDomain(__isl_take isl_set *Domain,
977 TempScop &tempScop,
978 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000979 const Region *TopRegion = tempScop.getMaxRegion().getParent(),
Tobias Grosserd7e58642013-04-10 06:55:45 +0000980 *CurrentRegion = &CurRegion;
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000981 const BasicBlock *BranchingBB = BB ? BB : R->getEntry();
Tobias Grosser75805372011-04-29 06:27:02 +0000982
Tobias Grosser75805372011-04-29 06:27:02 +0000983 do {
Tobias Grossere19661e2011-10-07 08:46:57 +0000984 if (BranchingBB != CurrentRegion->getEntry()) {
985 if (const BBCond *Condition = tempScop.getBBCond(BranchingBB))
Tobias Grosser083d3d32014-06-28 08:59:45 +0000986 for (const auto &C : *Condition) {
987 isl_set *ConditionSet = buildConditionSet(C);
Tobias Grossere19661e2011-10-07 08:46:57 +0000988 Domain = isl_set_intersect(Domain, ConditionSet);
Tobias Grosser75805372011-04-29 06:27:02 +0000989 }
990 }
Tobias Grossere19661e2011-10-07 08:46:57 +0000991 BranchingBB = CurrentRegion->getEntry();
992 CurrentRegion = CurrentRegion->getParent();
993 } while (TopRegion != CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000994
Tobias Grossere19661e2011-10-07 08:46:57 +0000995 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000996}
997
Tobias Grossere602a072013-05-07 07:30:56 +0000998__isl_give isl_set *ScopStmt::buildDomain(TempScop &tempScop,
999 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +00001000 isl_space *Space;
1001 isl_set *Domain;
Tobias Grosser084d8f72012-05-29 09:29:44 +00001002 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001003
1004 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
1005
Tobias Grosser084d8f72012-05-29 09:29:44 +00001006 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1007
Tobias Grossere19661e2011-10-07 08:46:57 +00001008 Domain = isl_set_universe(Space);
Tobias Grossere19661e2011-10-07 08:46:57 +00001009 Domain = addLoopBoundsToDomain(Domain, tempScop);
1010 Domain = addConditionsToDomain(Domain, tempScop, CurRegion);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001011 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grossere19661e2011-10-07 08:46:57 +00001012
1013 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +00001014}
1015
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001016void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
1017 int Dimension = 0;
1018 isl_ctx *Ctx = Parent.getIslCtx();
1019 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1020 Type *Ty = GEP->getPointerOperandType();
1021 ScalarEvolution &SE = *Parent.getSE();
1022
1023 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
1024 Dimension = 1;
1025 Ty = PtrTy->getElementType();
1026 }
1027
1028 while (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
1029 unsigned int Operand = 1 + Dimension;
1030
1031 if (GEP->getNumOperands() <= Operand)
1032 break;
1033
1034 const SCEV *Expr = SE.getSCEV(GEP->getOperand(Operand));
1035
1036 if (isAffineExpr(&Parent.getRegion(), Expr, SE)) {
1037 isl_pw_aff *AccessOffset = SCEVAffinator::getPwAff(this, Expr);
1038 AccessOffset =
1039 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
1040
1041 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1042 isl_local_space_copy(LSpace),
1043 isl_val_int_from_si(Ctx, ArrayTy->getNumElements())));
1044
1045 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1046 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1047 OutOfBound = isl_set_params(OutOfBound);
1048 isl_set *InBound = isl_set_complement(OutOfBound);
1049 isl_set *Executed = isl_set_params(getDomain());
1050
1051 // A => B == !A or B
1052 isl_set *InBoundIfExecuted =
1053 isl_set_union(isl_set_complement(Executed), InBound);
1054
1055 Parent.addAssumption(InBoundIfExecuted);
1056 }
1057
1058 Dimension += 1;
1059 Ty = ArrayTy->getElementType();
1060 }
1061
1062 isl_local_space_free(LSpace);
1063}
1064
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001065void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1066 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001067 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1068 deriveAssumptionsFromGEP(GEP);
1069}
1070
Tobias Grosser74394f02013-01-14 22:40:23 +00001071ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001072 Region &R, SmallVectorImpl<Loop *> &Nest,
Tobias Grosser54839312015-04-21 11:37:25 +00001073 SmallVectorImpl<unsigned> &ScheduleVec)
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001074 : Parent(parent), BB(nullptr), R(&R), Build(nullptr),
1075 NestLoops(Nest.size()) {
1076 // Setup the induction variables.
1077 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
1078 NestLoops[i] = Nest[i];
1079
1080 BaseName = getIslCompatibleName("Stmt_(", R.getNameStr(), ")");
1081
1082 Domain = buildDomain(tempScop, CurRegion);
Tobias Grosser54839312015-04-21 11:37:25 +00001083 buildSchedule(ScheduleVec);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001084
1085 BasicBlock *EntryBB = R.getEntry();
1086 for (BasicBlock *Block : R.blocks()) {
1087 buildAccesses(tempScop, Block, Block != EntryBB);
1088 deriveAssumptions(Block);
1089 }
1090 checkForReductions();
1091}
1092
1093ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Sebastian Pop860e0212013-02-15 21:26:44 +00001094 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest,
Tobias Grosser54839312015-04-21 11:37:25 +00001095 SmallVectorImpl<unsigned> &ScheduleVec)
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001096 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr),
1097 NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +00001098 // Setup the induction variables.
Tobias Grosser683b8e42014-11-30 14:33:31 +00001099 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
Sebastian Pop860e0212013-02-15 21:26:44 +00001100 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +00001101
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001102 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +00001103
Tobias Grossere19661e2011-10-07 08:46:57 +00001104 Domain = buildDomain(tempScop, CurRegion);
Tobias Grosser54839312015-04-21 11:37:25 +00001105 buildSchedule(ScheduleVec);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001106 buildAccesses(tempScop, BB);
1107 deriveAssumptions(BB);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001108 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001109}
1110
Johannes Doerferte58a0122014-06-27 20:31:28 +00001111/// @brief Collect loads which might form a reduction chain with @p StoreMA
1112///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001113/// Check if the stored value for @p StoreMA is a binary operator with one or
1114/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001115/// used only once (by @p StoreMA) and its load operands are also used only
1116/// once, we have found a possible reduction chain. It starts at an operand
1117/// load and includes the binary operator and @p StoreMA.
1118///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001119/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001120/// escape this block or into any other store except @p StoreMA.
1121void ScopStmt::collectCandiateReductionLoads(
1122 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1123 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1124 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001125 return;
1126
1127 // Skip if there is not one binary operator between the load and the store
1128 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001129 if (!BinOp)
1130 return;
1131
1132 // Skip if the binary operators has multiple uses
1133 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001134 return;
1135
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001136 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001137 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1138 return;
1139
Johannes Doerfert9890a052014-07-01 00:32:29 +00001140 // Skip if the binary operator is outside the current SCoP
1141 if (BinOp->getParent() != Store->getParent())
1142 return;
1143
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001144 // Skip if it is a multiplicative reduction and we disabled them
1145 if (DisableMultiplicativeReductions &&
1146 (BinOp->getOpcode() == Instruction::Mul ||
1147 BinOp->getOpcode() == Instruction::FMul))
1148 return;
1149
Johannes Doerferte58a0122014-06-27 20:31:28 +00001150 // Check the binary operator operands for a candidate load
1151 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1152 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1153 if (!PossibleLoad0 && !PossibleLoad1)
1154 return;
1155
1156 // A load is only a candidate if it cannot escape (thus has only this use)
1157 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001158 if (PossibleLoad0->getParent() == Store->getParent())
1159 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001160 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001161 if (PossibleLoad1->getParent() == Store->getParent())
1162 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001163}
1164
1165/// @brief Check for reductions in this ScopStmt
1166///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001167/// Iterate over all store memory accesses and check for valid binary reduction
1168/// like chains. For all candidates we check if they have the same base address
1169/// and there are no other accesses which overlap with them. The base address
1170/// check rules out impossible reductions candidates early. The overlap check,
1171/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001172/// guarantees that none of the intermediate results will escape during
1173/// execution of the loop nest. We basically check here that no other memory
1174/// access can access the same memory as the potential reduction.
1175void ScopStmt::checkForReductions() {
1176 SmallVector<MemoryAccess *, 2> Loads;
1177 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1178
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001179 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001180 // stores and collecting possible reduction loads.
1181 for (MemoryAccess *StoreMA : MemAccs) {
1182 if (StoreMA->isRead())
1183 continue;
1184
1185 Loads.clear();
1186 collectCandiateReductionLoads(StoreMA, Loads);
1187 for (MemoryAccess *LoadMA : Loads)
1188 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1189 }
1190
1191 // Then check each possible candidate pair.
1192 for (const auto &CandidatePair : Candidates) {
1193 bool Valid = true;
1194 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1195 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1196
1197 // Skip those with obviously unequal base addresses.
1198 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1199 isl_map_free(LoadAccs);
1200 isl_map_free(StoreAccs);
1201 continue;
1202 }
1203
1204 // And check if the remaining for overlap with other memory accesses.
1205 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1206 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1207 isl_set *AllAccs = isl_map_range(AllAccsRel);
1208
1209 for (MemoryAccess *MA : MemAccs) {
1210 if (MA == CandidatePair.first || MA == CandidatePair.second)
1211 continue;
1212
1213 isl_map *AccRel =
1214 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1215 isl_set *Accs = isl_map_range(AccRel);
1216
1217 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1218 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1219 Valid = Valid && isl_set_is_empty(OverlapAccs);
1220 isl_set_free(OverlapAccs);
1221 }
1222 }
1223
1224 isl_set_free(AllAccs);
1225 if (!Valid)
1226 continue;
1227
Johannes Doerfertf6183392014-07-01 20:52:51 +00001228 const LoadInst *Load =
1229 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1230 MemoryAccess::ReductionType RT =
1231 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1232
Johannes Doerferte58a0122014-06-27 20:31:28 +00001233 // If no overlapping access was found we mark the load and store as
1234 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001235 CandidatePair.first->markAsReductionLike(RT);
1236 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001237 }
Tobias Grosser75805372011-04-29 06:27:02 +00001238}
1239
Tobias Grosser74394f02013-01-14 22:40:23 +00001240std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001241
Tobias Grosser54839312015-04-21 11:37:25 +00001242std::string ScopStmt::getScheduleStr() const {
1243 return stringFromIslObj(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00001244}
1245
Tobias Grosser74394f02013-01-14 22:40:23 +00001246unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001247
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001248unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001249
Tobias Grosser54839312015-04-21 11:37:25 +00001250unsigned ScopStmt::getNumSchedule() const {
1251 return isl_map_dim(Schedule, isl_dim_out);
Tobias Grosser75805372011-04-29 06:27:02 +00001252}
1253
1254const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1255
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001256const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001257 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001258}
1259
Tobias Grosser74394f02013-01-14 22:40:23 +00001260isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001261
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001262__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001263
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001264__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001265 return isl_set_get_space(Domain);
1266}
1267
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001268__isl_give isl_id *ScopStmt::getDomainId() const {
1269 return isl_set_get_tuple_id(Domain);
1270}
Tobias Grossercd95b772012-08-30 11:49:38 +00001271
Tobias Grosser75805372011-04-29 06:27:02 +00001272ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001273 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001274 isl_set_free(Domain);
Tobias Grosser54839312015-04-21 11:37:25 +00001275 isl_map_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00001276}
1277
1278void ScopStmt::print(raw_ostream &OS) const {
1279 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001280 OS.indent(12) << "Domain :=\n";
1281
1282 if (Domain) {
1283 OS.indent(16) << getDomainStr() << ";\n";
1284 } else
1285 OS.indent(16) << "n/a\n";
1286
Tobias Grosser54839312015-04-21 11:37:25 +00001287 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001288
1289 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001290 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001291 } else
1292 OS.indent(16) << "n/a\n";
1293
Tobias Grosser083d3d32014-06-28 08:59:45 +00001294 for (MemoryAccess *Access : MemAccs)
1295 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001296}
1297
1298void ScopStmt::dump() const { print(dbgs()); }
1299
1300//===----------------------------------------------------------------------===//
1301/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001302
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001303void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001304 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1305 isl_set_free(Context);
1306 Context = NewContext;
1307}
1308
Tobias Grosserabfbe632013-02-05 12:09:06 +00001309void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001310 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001311 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001312 if (ParameterIds.find(Parameter) != ParameterIds.end())
1313 continue;
1314
1315 int dimension = Parameters.size();
1316
1317 Parameters.push_back(Parameter);
1318 ParameterIds[Parameter] = dimension;
1319 }
1320}
1321
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001322__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1323 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001324
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001325 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001326 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001327
Tobias Grosser8f99c162011-11-15 11:38:55 +00001328 std::string ParameterName;
1329
1330 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1331 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001332 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001333 }
1334
1335 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001336 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001337
Tobias Grosser20532b82014-04-11 17:56:49 +00001338 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1339 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001340}
Tobias Grosser75805372011-04-29 06:27:02 +00001341
Tobias Grosser6be480c2011-11-08 15:41:13 +00001342void Scop::buildContext() {
1343 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001344 Context = isl_set_universe(isl_space_copy(Space));
1345 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001346}
1347
Tobias Grosser18daaca2012-05-22 10:47:27 +00001348void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001349 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001350 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001351
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001352 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001353
Johannes Doerferte7044942015-02-24 11:58:30 +00001354 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001355 }
1356}
1357
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001358void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001359 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001360 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001361
Tobias Grosser083d3d32014-06-28 08:59:45 +00001362 for (const auto &ParamID : ParameterIds) {
1363 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001364 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001365 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001366 }
1367
1368 // Align the parameters of all data structures to the model.
1369 Context = isl_set_align_params(Context, Space);
1370
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001371 for (ScopStmt &Stmt : *this)
1372 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001373}
1374
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001375void Scop::simplifyAssumedContext() {
1376 // The parameter constraints of the iteration domains give us a set of
1377 // constraints that need to hold for all cases where at least a single
1378 // statement iteration is executed in the whole scop. We now simplify the
1379 // assumed context under the assumption that such constraints hold and at
1380 // least a single statement iteration is executed. For cases where no
1381 // statement instances are executed, the assumptions we have taken about
1382 // the executed code do not matter and can be changed.
1383 //
1384 // WARNING: This only holds if the assumptions we have taken do not reduce
1385 // the set of statement instances that are executed. Otherwise we
1386 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001387 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001388 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001389 // performed. In such a case, modifying the run-time conditions and
1390 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001391 // to not be executed.
1392 //
1393 // Example:
1394 //
1395 // When delinearizing the following code:
1396 //
1397 // for (long i = 0; i < 100; i++)
1398 // for (long j = 0; j < m; j++)
1399 // A[i+p][j] = 1.0;
1400 //
1401 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001402 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001403 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1404 AssumedContext =
1405 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001406 AssumedContext = isl_set_gist_params(AssumedContext, getContext());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001407}
1408
Johannes Doerfertb164c792014-09-18 11:17:17 +00001409/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001410static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001411 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1412 isl_pw_multi_aff *MinPMA, *MaxPMA;
1413 isl_pw_aff *LastDimAff;
1414 isl_aff *OneAff;
1415 unsigned Pos;
1416
Johannes Doerfert9143d672014-09-27 11:02:39 +00001417 // Restrict the number of parameters involved in the access as the lexmin/
1418 // lexmax computation will take too long if this number is high.
1419 //
1420 // Experiments with a simple test case using an i7 4800MQ:
1421 //
1422 // #Parameters involved | Time (in sec)
1423 // 6 | 0.01
1424 // 7 | 0.04
1425 // 8 | 0.12
1426 // 9 | 0.40
1427 // 10 | 1.54
1428 // 11 | 6.78
1429 // 12 | 30.38
1430 //
1431 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1432 unsigned InvolvedParams = 0;
1433 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1434 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1435 InvolvedParams++;
1436
1437 if (InvolvedParams > RunTimeChecksMaxParameters) {
1438 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001439 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001440 }
1441 }
1442
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001443 Set = isl_set_remove_divs(Set);
1444
Johannes Doerfertb164c792014-09-18 11:17:17 +00001445 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1446 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1447
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001448 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1449 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1450
Johannes Doerfertb164c792014-09-18 11:17:17 +00001451 // Adjust the last dimension of the maximal access by one as we want to
1452 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1453 // we test during code generation might now point after the end of the
1454 // allocated array but we will never dereference it anyway.
1455 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1456 "Assumed at least one output dimension");
1457 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1458 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1459 OneAff = isl_aff_zero_on_domain(
1460 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1461 OneAff = isl_aff_add_constant_si(OneAff, 1);
1462 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1463 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1464
1465 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1466
1467 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001468 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001469}
1470
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001471static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1472 isl_set *Domain = MA->getStatement()->getDomain();
1473 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1474 return isl_set_reset_tuple_id(Domain);
1475}
1476
Johannes Doerfert9143d672014-09-27 11:02:39 +00001477bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001478 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001479 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001480 // for all memory accesses inside the SCoP.
1481 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001482 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001483 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001484 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001485 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001486 // if their access domains intersect, otherwise they are in different
1487 // ones.
Johannes Doerfert13771732014-10-01 12:40:46 +00001488 // o) We split groups such that they contain at most one read only base
1489 // address.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001490 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfertb164c792014-09-18 11:17:17 +00001491 // and maximal accesses to each array in this group.
1492 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1493
1494 AliasSetTracker AST(AA);
1495
1496 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001497 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001498 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001499
1500 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001501 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001502 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1503 isl_set_free(StmtDomain);
1504 if (StmtDomainEmpty)
1505 continue;
1506
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001507 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001508 if (MA->isScalar())
1509 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001510 if (!MA->isRead())
1511 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001512 Instruction *Acc = MA->getAccessInstruction();
1513 PtrToAcc[getPointerOperand(*Acc)] = MA;
1514 AST.add(Acc);
1515 }
1516 }
1517
1518 SmallVector<AliasGroupTy, 4> AliasGroups;
1519 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001520 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001521 continue;
1522 AliasGroupTy AG;
1523 for (auto PR : AS)
1524 AG.push_back(PtrToAcc[PR.getValue()]);
1525 assert(AG.size() > 1 &&
1526 "Alias groups should contain at least two accesses");
1527 AliasGroups.push_back(std::move(AG));
1528 }
1529
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001530 // Split the alias groups based on their domain.
1531 for (unsigned u = 0; u < AliasGroups.size(); u++) {
1532 AliasGroupTy NewAG;
1533 AliasGroupTy &AG = AliasGroups[u];
1534 AliasGroupTy::iterator AGI = AG.begin();
1535 isl_set *AGDomain = getAccessDomain(*AGI);
1536 while (AGI != AG.end()) {
1537 MemoryAccess *MA = *AGI;
1538 isl_set *MADomain = getAccessDomain(MA);
1539 if (isl_set_is_disjoint(AGDomain, MADomain)) {
1540 NewAG.push_back(MA);
1541 AGI = AG.erase(AGI);
1542 isl_set_free(MADomain);
1543 } else {
1544 AGDomain = isl_set_union(AGDomain, MADomain);
1545 AGI++;
1546 }
1547 }
1548 if (NewAG.size() > 1)
1549 AliasGroups.push_back(std::move(NewAG));
1550 isl_set_free(AGDomain);
1551 }
1552
Tobias Grosserf4c24b22015-04-05 13:11:54 +00001553 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00001554 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
1555 for (AliasGroupTy &AG : AliasGroups) {
1556 NonReadOnlyBaseValues.clear();
1557 ReadOnlyPairs.clear();
1558
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001559 if (AG.size() < 2) {
1560 AG.clear();
1561 continue;
1562 }
1563
Johannes Doerfert13771732014-10-01 12:40:46 +00001564 for (auto II = AG.begin(); II != AG.end();) {
1565 Value *BaseAddr = (*II)->getBaseAddr();
1566 if (HasWriteAccess.count(BaseAddr)) {
1567 NonReadOnlyBaseValues.insert(BaseAddr);
1568 II++;
1569 } else {
1570 ReadOnlyPairs[BaseAddr].insert(*II);
1571 II = AG.erase(II);
1572 }
1573 }
1574
1575 // If we don't have read only pointers check if there are at least two
1576 // non read only pointers, otherwise clear the alias group.
1577 if (ReadOnlyPairs.empty()) {
1578 if (NonReadOnlyBaseValues.size() <= 1)
1579 AG.clear();
1580 continue;
1581 }
1582
1583 // If we don't have non read only pointers clear the alias group.
1584 if (NonReadOnlyBaseValues.empty()) {
1585 AG.clear();
1586 continue;
1587 }
1588
1589 // If we have both read only and non read only base pointers we combine
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001590 // the non read only ones with exactly one read only one at a time into a
Johannes Doerfert13771732014-10-01 12:40:46 +00001591 // new alias group and clear the old alias group in the end.
1592 for (const auto &ReadOnlyPair : ReadOnlyPairs) {
1593 AliasGroupTy AGNonReadOnly = AG;
1594 for (MemoryAccess *MA : ReadOnlyPair.second)
1595 AGNonReadOnly.push_back(MA);
1596 AliasGroups.push_back(std::move(AGNonReadOnly));
1597 }
1598 AG.clear();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001599 }
1600
1601 for (AliasGroupTy &AG : AliasGroups) {
Johannes Doerfert13771732014-10-01 12:40:46 +00001602 if (AG.empty())
1603 continue;
1604
Johannes Doerfertb164c792014-09-18 11:17:17 +00001605 MinMaxVectorTy *MinMaxAccesses = new MinMaxVectorTy();
1606 MinMaxAccesses->reserve(AG.size());
1607
1608 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
1609 for (MemoryAccess *MA : AG)
1610 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
1611 Accesses = isl_union_map_intersect_domain(Accesses, getDomains());
1612
1613 isl_union_set *Locations = isl_union_map_range(Accesses);
1614 Locations = isl_union_set_intersect_params(Locations, getAssumedContext());
1615 Locations = isl_union_set_coalesce(Locations);
1616 Locations = isl_union_set_detect_equalities(Locations);
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001617 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
1618 MinMaxAccesses));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001619 isl_union_set_free(Locations);
Johannes Doerfertb164c792014-09-18 11:17:17 +00001620 MinMaxAliasGroups.push_back(MinMaxAccesses);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001621
1622 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001623 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001624 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001625
Tobias Grosser71500722015-03-28 15:11:14 +00001626 // Bail out if the number of values we need to compare is too large.
1627 // This is important as the number of comparisions grows quadratically with
1628 // the number of values we need to compare.
1629 for (const auto *Values : MinMaxAliasGroups)
1630 if (Values->size() > RunTimeChecksMaxArraysPerGroup)
1631 return false;
1632
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001633 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001634}
1635
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001636static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
1637 ScopDetection &SD) {
1638
1639 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
1640
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001641 unsigned MinLD = INT_MAX, MaxLD = 0;
1642 for (BasicBlock *BB : R.blocks()) {
1643 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00001644 if (!R.contains(L))
1645 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001646 if (BoxedLoops && BoxedLoops->count(L))
1647 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001648 unsigned LD = L->getLoopDepth();
1649 MinLD = std::min(MinLD, LD);
1650 MaxLD = std::max(MaxLD, LD);
1651 }
1652 }
1653
1654 // Handle the case that there is no loop in the SCoP first.
1655 if (MaxLD == 0)
1656 return 1;
1657
1658 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
1659 assert(MaxLD >= MinLD &&
1660 "Maximal loop depth was smaller than mininaml loop depth?");
1661 return MaxLD - MinLD + 1;
1662}
1663
Tobias Grosser3f296192015-01-01 23:01:11 +00001664void Scop::dropConstantScheduleDims() {
1665 isl_union_map *FullSchedule = getSchedule();
1666
1667 if (isl_union_map_n_map(FullSchedule) == 0) {
1668 isl_union_map_free(FullSchedule);
1669 return;
1670 }
1671
1672 isl_set *ScheduleSpace =
1673 isl_set_from_union_set(isl_union_map_range(FullSchedule));
1674 isl_map *DropDimMap = isl_set_identity(isl_set_copy(ScheduleSpace));
1675
1676 int NumDimsDropped = 0;
Johannes Doerfert3f21e272015-03-04 22:23:21 +00001677 for (unsigned i = 0; i < isl_set_dim(ScheduleSpace, isl_dim_set); i += 2) {
1678 isl_val *FixedVal =
1679 isl_set_plain_get_val_if_fixed(ScheduleSpace, isl_dim_set, i);
1680 if (isl_val_is_int(FixedVal)) {
1681 DropDimMap =
1682 isl_map_project_out(DropDimMap, isl_dim_out, i - NumDimsDropped, 1);
1683 NumDimsDropped++;
Tobias Grosser3f296192015-01-01 23:01:11 +00001684 }
Johannes Doerfert3f21e272015-03-04 22:23:21 +00001685 isl_val_free(FixedVal);
1686 }
Tobias Grosser3f296192015-01-01 23:01:11 +00001687
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001688 for (ScopStmt &Stmt : *this) {
1689 isl_map *Schedule = Stmt.getSchedule();
Tobias Grosser3f296192015-01-01 23:01:11 +00001690 Schedule = isl_map_apply_range(Schedule, isl_map_copy(DropDimMap));
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001691 Stmt.setSchedule(Schedule);
Tobias Grosser3f296192015-01-01 23:01:11 +00001692 }
1693 isl_set_free(ScheduleSpace);
1694 isl_map_free(DropDimMap);
1695}
1696
Tobias Grosser0e27e242011-10-06 00:03:48 +00001697Scop::Scop(TempScop &tempScop, LoopInfo &LI, ScalarEvolution &ScalarEvolution,
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001698 ScopDetection &SD, isl_ctx *Context)
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001699 : SE(&ScalarEvolution), R(tempScop.getMaxRegion()), IsOptimized(false),
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001700 MaxLoopDepth(getMaxLoopDepthInRegion(tempScop.getMaxRegion(), LI, SD)) {
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001701 IslCtx = Context;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001702
Tobias Grosser6be480c2011-11-08 15:41:13 +00001703 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001704
Tobias Grosserabfbe632013-02-05 12:09:06 +00001705 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser54839312015-04-21 11:37:25 +00001706 SmallVector<unsigned, 8> Schedule;
Tobias Grosser75805372011-04-29 06:27:02 +00001707
Tobias Grosser54839312015-04-21 11:37:25 +00001708 Schedule.assign(MaxLoopDepth + 1, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001709
Tobias Grosser54839312015-04-21 11:37:25 +00001710 // Build the iteration domain, access functions and schedule functions
Tobias Grosser75805372011-04-29 06:27:02 +00001711 // traversing the region tree.
Tobias Grosser54839312015-04-21 11:37:25 +00001712 buildScop(tempScop, getRegion(), NestLoops, Schedule, LI, SD);
Tobias Grosser75805372011-04-29 06:27:02 +00001713
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001714 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001715 addParameterBounds();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001716 simplifyAssumedContext();
Tobias Grosser3f296192015-01-01 23:01:11 +00001717 dropConstantScheduleDims();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001718
Tobias Grosser75805372011-04-29 06:27:02 +00001719 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1720}
1721
1722Scop::~Scop() {
1723 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001724 isl_set_free(AssumedContext);
Tobias Grosser75805372011-04-29 06:27:02 +00001725
Johannes Doerfertb164c792014-09-18 11:17:17 +00001726 // Free the alias groups
1727 for (MinMaxVectorTy *MinMaxAccesses : MinMaxAliasGroups) {
1728 for (MinMaxAccessTy &MMA : *MinMaxAccesses) {
1729 isl_pw_multi_aff_free(MMA.first);
1730 isl_pw_multi_aff_free(MMA.second);
1731 }
1732 delete MinMaxAccesses;
1733 }
Tobias Grosser75805372011-04-29 06:27:02 +00001734}
1735
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001736const ScopArrayInfo *
1737Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
1738 const SmallVector<const SCEV *, 4> &Sizes) {
Tobias Grosserab671442015-05-23 05:58:27 +00001739 auto &SAI = ScopArrayInfoMap[BasePtr];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001740 if (!SAI)
Tobias Grosserab671442015-05-23 05:58:27 +00001741 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes));
1742 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001743}
1744
1745const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr) {
Tobias Grosser2d7611f2015-05-23 05:58:30 +00001746 const ScopArrayInfo *SAI = ScopArrayInfoMap[BasePtr].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001747 assert(SAI && "No ScopArrayInfo available for this base pointer");
1748 return SAI;
1749}
1750
Tobias Grosser74394f02013-01-14 22:40:23 +00001751std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001752std::string Scop::getAssumedContextStr() const {
1753 return stringFromIslObj(AssumedContext);
1754}
Tobias Grosser75805372011-04-29 06:27:02 +00001755
1756std::string Scop::getNameStr() const {
1757 std::string ExitName, EntryName;
1758 raw_string_ostream ExitStr(ExitName);
1759 raw_string_ostream EntryStr(EntryName);
1760
Tobias Grosserf240b482014-01-09 10:42:15 +00001761 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001762 EntryStr.str();
1763
1764 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001765 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001766 ExitStr.str();
1767 } else
1768 ExitName = "FunctionExit";
1769
1770 return EntryName + "---" + ExitName;
1771}
1772
Tobias Grosser74394f02013-01-14 22:40:23 +00001773__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001774__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001775 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00001776}
1777
Tobias Grossere86109f2013-10-29 21:05:49 +00001778__isl_give isl_set *Scop::getAssumedContext() const {
1779 return isl_set_copy(AssumedContext);
1780}
1781
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001782void Scop::addAssumption(__isl_take isl_set *Set) {
1783 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001784 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001785}
1786
Tobias Grosser75805372011-04-29 06:27:02 +00001787void Scop::printContext(raw_ostream &OS) const {
1788 OS << "Context:\n";
1789
1790 if (!Context) {
1791 OS.indent(4) << "n/a\n\n";
1792 return;
1793 }
1794
1795 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001796
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001797 OS.indent(4) << "Assumed Context:\n";
1798 if (!AssumedContext) {
1799 OS.indent(4) << "n/a\n\n";
1800 return;
1801 }
1802
1803 OS.indent(4) << getAssumedContextStr() << "\n";
1804
Tobias Grosser083d3d32014-06-28 08:59:45 +00001805 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001806 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001807 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1808 }
Tobias Grosser75805372011-04-29 06:27:02 +00001809}
1810
Johannes Doerfertb164c792014-09-18 11:17:17 +00001811void Scop::printAliasAssumptions(raw_ostream &OS) const {
1812 OS.indent(4) << "Alias Groups (" << MinMaxAliasGroups.size() << "):\n";
1813 if (MinMaxAliasGroups.empty()) {
1814 OS.indent(8) << "n/a\n";
1815 return;
1816 }
1817 for (MinMaxVectorTy *MinMaxAccesses : MinMaxAliasGroups) {
1818 OS.indent(8) << "[[";
1819 for (MinMaxAccessTy &MinMacAccess : *MinMaxAccesses)
1820 OS << " <" << MinMacAccess.first << ", " << MinMacAccess.second << ">";
1821 OS << " ]]\n";
1822 }
1823}
1824
Tobias Grosser75805372011-04-29 06:27:02 +00001825void Scop::printStatements(raw_ostream &OS) const {
1826 OS << "Statements {\n";
1827
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001828 for (const ScopStmt &Stmt : *this)
1829 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001830
1831 OS.indent(4) << "}\n";
1832}
1833
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001834void Scop::printArrayInfo(raw_ostream &OS) const {
1835 OS << "Arrays {\n";
1836
Tobias Grosserab671442015-05-23 05:58:27 +00001837 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001838 Array.second->print(OS);
1839
1840 OS.indent(4) << "}\n";
1841}
1842
Tobias Grosser75805372011-04-29 06:27:02 +00001843void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00001844 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
1845 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00001846 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00001847 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001848 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001849 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001850 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001851 printStatements(OS.indent(4));
1852}
1853
1854void Scop::dump() const { print(dbgs()); }
1855
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001856isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00001857
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001858__isl_give isl_union_set *Scop::getDomains() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001859 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001860
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001861 for (ScopStmt &Stmt : *this)
1862 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001863
1864 return Domain;
1865}
1866
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001867__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001868 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001869
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001870 for (ScopStmt &Stmt : *this) {
1871 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001872 if (!MA->isMustWrite())
1873 continue;
1874
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001875 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001876 isl_map *AccessDomain = MA->getAccessRelation();
1877 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1878 Write = isl_union_map_add_map(Write, AccessDomain);
1879 }
1880 }
1881 return isl_union_map_coalesce(Write);
1882}
1883
1884__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001885 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001886
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001887 for (ScopStmt &Stmt : *this) {
1888 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001889 if (!MA->isMayWrite())
1890 continue;
1891
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001892 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001893 isl_map *AccessDomain = MA->getAccessRelation();
1894 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1895 Write = isl_union_map_add_map(Write, AccessDomain);
1896 }
1897 }
1898 return isl_union_map_coalesce(Write);
1899}
1900
Tobias Grosser37eb4222014-02-20 21:43:54 +00001901__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001902 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001903
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001904 for (ScopStmt &Stmt : *this) {
1905 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001906 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001907 continue;
1908
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001909 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001910 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001911 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1912 Write = isl_union_map_add_map(Write, AccessDomain);
1913 }
1914 }
1915 return isl_union_map_coalesce(Write);
1916}
1917
1918__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001919 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001920
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001921 for (ScopStmt &Stmt : *this) {
1922 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001923 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001924 continue;
1925
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001926 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001927 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001928
1929 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1930 Read = isl_union_map_add_map(Read, AccessDomain);
1931 }
1932 }
1933 return isl_union_map_coalesce(Read);
1934}
1935
1936__isl_give isl_union_map *Scop::getSchedule() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001937 isl_union_map *Schedule = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001938
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001939 for (ScopStmt &Stmt : *this)
1940 Schedule = isl_union_map_add_map(Schedule, Stmt.getSchedule());
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001941
Tobias Grosser37eb4222014-02-20 21:43:54 +00001942 return isl_union_map_coalesce(Schedule);
1943}
1944
1945bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
1946 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001947 for (ScopStmt &Stmt : *this) {
1948 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001949 isl_union_set *NewStmtDomain = isl_union_set_intersect(
1950 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
1951
1952 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
1953 isl_union_set_free(StmtDomain);
1954 isl_union_set_free(NewStmtDomain);
1955 continue;
1956 }
1957
1958 Changed = true;
1959
1960 isl_union_set_free(StmtDomain);
1961 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
1962
1963 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001964 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00001965 isl_union_set_free(NewStmtDomain);
1966 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001967 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00001968 }
1969 isl_union_set_free(Domain);
1970 return Changed;
1971}
1972
Tobias Grosser75805372011-04-29 06:27:02 +00001973ScalarEvolution *Scop::getSE() const { return SE; }
1974
1975bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
1976 if (tempScop.getAccessFunctions(BB))
1977 return false;
1978
1979 return true;
1980}
1981
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001982void Scop::addScopStmt(BasicBlock *BB, Region *R, TempScop &tempScop,
1983 const Region &CurRegion,
1984 SmallVectorImpl<Loop *> &NestLoops,
Tobias Grosser54839312015-04-21 11:37:25 +00001985 SmallVectorImpl<unsigned> &ScheduleVec) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001986 if (BB) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001987 Stmts.emplace_back(*this, tempScop, CurRegion, *BB, NestLoops, ScheduleVec);
1988 StmtMap[BB] = &Stmts.back();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001989 } else {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001990 assert(R && "Either basic block or a region expected.");
1991 Stmts.emplace_back(*this, tempScop, CurRegion, *R, NestLoops, ScheduleVec);
1992 auto *Ptr = &Stmts.back();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001993 for (BasicBlock *BB : R->blocks())
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001994 StmtMap[BB] = Ptr;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001995 }
1996
Tobias Grosser54839312015-04-21 11:37:25 +00001997 // Increasing the Schedule function is OK for the moment, because
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001998 // we are using a depth first iterator and the program is well structured.
Tobias Grosser54839312015-04-21 11:37:25 +00001999 ++ScheduleVec[NestLoops.size()];
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002000}
2001
Tobias Grosser74394f02013-01-14 22:40:23 +00002002void Scop::buildScop(TempScop &tempScop, const Region &CurRegion,
2003 SmallVectorImpl<Loop *> &NestLoops,
Tobias Grosser54839312015-04-21 11:37:25 +00002004 SmallVectorImpl<unsigned> &ScheduleVec, LoopInfo &LI,
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002005 ScopDetection &SD) {
2006 if (SD.isNonAffineSubRegion(&CurRegion, &getRegion()))
2007 return addScopStmt(nullptr, const_cast<Region *>(&CurRegion), tempScop,
Tobias Grosser54839312015-04-21 11:37:25 +00002008 CurRegion, NestLoops, ScheduleVec);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002009
Tobias Grosser75805372011-04-29 06:27:02 +00002010 Loop *L = castToLoop(CurRegion, LI);
2011
2012 if (L)
2013 NestLoops.push_back(L);
2014
2015 unsigned loopDepth = NestLoops.size();
Tobias Grosser54839312015-04-21 11:37:25 +00002016 assert(ScheduleVec.size() > loopDepth && "Schedule not big enough!");
Tobias Grosser75805372011-04-29 06:27:02 +00002017
2018 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00002019 E = CurRegion.element_end();
2020 I != E; ++I)
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002021 if (I->isSubRegion()) {
Tobias Grosser654af8f2015-04-21 11:42:01 +00002022 buildScop(tempScop, *I->getNodeAs<Region>(), NestLoops, ScheduleVec, LI,
2023 SD);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002024 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00002025 BasicBlock *BB = I->getNodeAs<BasicBlock>();
2026
2027 if (isTrivialBB(BB, tempScop))
2028 continue;
2029
Tobias Grosser54839312015-04-21 11:37:25 +00002030 addScopStmt(BB, nullptr, tempScop, CurRegion, NestLoops, ScheduleVec);
Tobias Grosser75805372011-04-29 06:27:02 +00002031 }
2032
2033 if (!L)
2034 return;
2035
2036 // Exiting a loop region.
Tobias Grosser54839312015-04-21 11:37:25 +00002037 ScheduleVec[loopDepth] = 0;
Tobias Grosser75805372011-04-29 06:27:02 +00002038 NestLoops.pop_back();
Tobias Grosser54839312015-04-21 11:37:25 +00002039 ++ScheduleVec[loopDepth - 1];
Tobias Grosser75805372011-04-29 06:27:02 +00002040}
2041
Johannes Doerfert7c494212014-10-31 23:13:39 +00002042ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00002043 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00002044 if (StmtMapIt == StmtMap.end())
2045 return nullptr;
2046 return StmtMapIt->second;
2047}
2048
Tobias Grosser75805372011-04-29 06:27:02 +00002049//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00002050ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
2051 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00002052 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00002053}
2054
2055ScopInfo::~ScopInfo() {
2056 clear();
2057 isl_ctx_free(ctx);
2058}
2059
Tobias Grosser75805372011-04-29 06:27:02 +00002060void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00002061 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00002062 AU.addRequired<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00002063 AU.addRequired<ScalarEvolution>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002064 AU.addRequired<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00002065 AU.addRequired<TempScopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002066 AU.addRequired<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00002067 AU.setPreservesAll();
2068}
2069
2070bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Chandler Carruthf5579872015-01-17 14:16:56 +00002071 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002072 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002073 ScopDetection &SD = getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00002074 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
2075
2076 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop(R);
2077
2078 // This region is no Scop.
2079 if (!tempScop) {
Tobias Grosserc98a8fc2014-11-14 11:12:31 +00002080 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002081 return false;
2082 }
2083
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002084 scop = new Scop(*tempScop, LI, SE, SD, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00002085
Tobias Grosserd6a50b32015-05-30 06:26:21 +00002086 DEBUG(scop->print(dbgs()));
2087
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002088 if (!PollyUseRuntimeAliasChecks) {
2089 // Statistics.
2090 ++ScopFound;
2091 if (scop->getMaxLoopDepth() > 0)
2092 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002093 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002094 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002095
Johannes Doerfert9143d672014-09-27 11:02:39 +00002096 // If a problem occurs while building the alias groups we need to delete
2097 // this SCoP and pretend it wasn't valid in the first place.
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002098 if (scop->buildAliasGroups(AA)) {
2099 // Statistics.
2100 ++ScopFound;
2101 if (scop->getMaxLoopDepth() > 0)
2102 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002103 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002104 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002105
2106 DEBUG(dbgs()
2107 << "\n\nNOTE: Run time checks for " << scop->getNameStr()
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002108 << " could not be created as the number of parameters involved is too "
Johannes Doerfert9143d672014-09-27 11:02:39 +00002109 "high. The SCoP will be "
2110 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust the "
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002111 "maximal number of parameters but be advised that the compile time "
Johannes Doerfert9143d672014-09-27 11:02:39 +00002112 "might increase exponentially.\n\n");
2113
2114 delete scop;
2115 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002116 return false;
2117}
2118
2119char ScopInfo::ID = 0;
2120
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002121Pass *polly::createScopInfoPass() { return new ScopInfo(); }
2122
Tobias Grosser73600b82011-10-08 00:30:40 +00002123INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
2124 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002125 false);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002126INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Chandler Carruthf5579872015-01-17 14:16:56 +00002127INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00002128INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002129INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002130INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002131INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Tobias Grosser73600b82011-10-08 00:30:40 +00002132INITIALIZE_PASS_END(ScopInfo, "polly-scops",
2133 "Polly - Create polyhedral description of Scops", false,
2134 false)