blob: 071e40c3c90daa68aff42b078179d46e2f5ac978 [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"
Hongbin Zheng86a37742012-04-25 08:01:38 +000030#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000031#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000032#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser83628182013-05-07 08:11:54 +000033#include "llvm/Analysis/RegionIterator.h"
34#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000035#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000036#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000037#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000038#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000039#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000040#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000041#include "isl/printer.h"
42#include "isl/set.h"
43#include "isl/union_map.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000044#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000045#include <sstream>
46#include <string>
47#include <vector>
48
49using namespace llvm;
50using namespace polly;
51
Chandler Carruth95fef942014-04-22 03:30:19 +000052#define DEBUG_TYPE "polly-scops"
53
Tobias Grosser74394f02013-01-14 22:40:23 +000054STATISTIC(ScopFound, "Number of valid Scops");
55STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000056
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000057// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000058// operations can overflow easily. Additive reductions and bit operations
59// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000060static cl::opt<bool> DisableMultiplicativeReductions(
61 "polly-disable-multiplicative-reductions",
62 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
63 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000064
Johannes Doerfert9143d672014-09-27 11:02:39 +000065static cl::opt<unsigned> RunTimeChecksMaxParameters(
66 "polly-rtc-max-parameters",
67 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
68 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
69
Tobias Grosser71500722015-03-28 15:11:14 +000070static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
71 "polly-rtc-max-arrays-per-group",
72 cl::desc("The maximal number of arrays to compare in each alias group."),
73 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
74
Tobias Grosser0695ee42013-09-17 03:30:31 +000075/// Translate a 'const SCEV *' expression in an isl_pw_aff.
Tobias Grosserabfbe632013-02-05 12:09:06 +000076struct SCEVAffinator : public SCEVVisitor<SCEVAffinator, isl_pw_aff *> {
Tobias Grosser0695ee42013-09-17 03:30:31 +000077public:
Tobias Grosser0695ee42013-09-17 03:30:31 +000078 /// @brief Translate a 'const SCEV *' to an isl_pw_aff.
79 ///
80 /// @param Stmt The location at which the scalar evolution expression
81 /// is evaluated.
82 /// @param Expr The expression that is translated.
83 static __isl_give isl_pw_aff *getPwAff(ScopStmt *Stmt, const SCEV *Expr);
84
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000085private:
Tobias Grosser3cc99742012-06-06 16:33:15 +000086 isl_ctx *Ctx;
Tobias Grosserf5338802011-10-06 00:03:35 +000087 int NbLoopSpaces;
Tobias Grosser3cc99742012-06-06 16:33:15 +000088 const Scop *S;
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000089
Tobias Grosser0695ee42013-09-17 03:30:31 +000090 SCEVAffinator(const ScopStmt *Stmt);
91 int getLoopDepth(const Loop *L);
Tobias Grosser60b54f12011-11-08 15:41:28 +000092
Tobias Grosser0695ee42013-09-17 03:30:31 +000093 __isl_give isl_pw_aff *visit(const SCEV *Expr);
94 __isl_give isl_pw_aff *visitConstant(const SCEVConstant *Expr);
95 __isl_give isl_pw_aff *visitTruncateExpr(const SCEVTruncateExpr *Expr);
96 __isl_give isl_pw_aff *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr);
97 __isl_give isl_pw_aff *visitSignExtendExpr(const SCEVSignExtendExpr *Expr);
98 __isl_give isl_pw_aff *visitAddExpr(const SCEVAddExpr *Expr);
99 __isl_give isl_pw_aff *visitMulExpr(const SCEVMulExpr *Expr);
100 __isl_give isl_pw_aff *visitUDivExpr(const SCEVUDivExpr *Expr);
101 __isl_give isl_pw_aff *visitAddRecExpr(const SCEVAddRecExpr *Expr);
102 __isl_give isl_pw_aff *visitSMaxExpr(const SCEVSMaxExpr *Expr);
103 __isl_give isl_pw_aff *visitUMaxExpr(const SCEVUMaxExpr *Expr);
104 __isl_give isl_pw_aff *visitUnknown(const SCEVUnknown *Expr);
Johannes Doerfertb9d18882015-02-11 14:54:50 +0000105 __isl_give isl_pw_aff *visitSDivInstruction(Instruction *SDiv);
Tobias Grosser60b54f12011-11-08 15:41:28 +0000106
Tobias Grosser0695ee42013-09-17 03:30:31 +0000107 friend struct SCEVVisitor<SCEVAffinator, isl_pw_aff *>;
108};
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000109
Tobias Grosser0695ee42013-09-17 03:30:31 +0000110SCEVAffinator::SCEVAffinator(const ScopStmt *Stmt)
111 : Ctx(Stmt->getIslCtx()), NbLoopSpaces(Stmt->getNumIterators()),
112 S(Stmt->getParent()) {}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000113
Tobias Grosser0695ee42013-09-17 03:30:31 +0000114__isl_give isl_pw_aff *SCEVAffinator::getPwAff(ScopStmt *Stmt,
115 const SCEV *Scev) {
116 Scop *S = Stmt->getParent();
117 const Region *Reg = &S->getRegion();
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000118
Tobias Grosser0695ee42013-09-17 03:30:31 +0000119 S->addParams(getParamsInAffineExpr(Reg, Scev, *S->getSE()));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000120
Tobias Grosser0695ee42013-09-17 03:30:31 +0000121 SCEVAffinator Affinator(Stmt);
122 return Affinator.visit(Scev);
123}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000124
Tobias Grosser0695ee42013-09-17 03:30:31 +0000125__isl_give isl_pw_aff *SCEVAffinator::visit(const SCEV *Expr) {
126 // In case the scev is a valid parameter, we do not further analyze this
127 // expression, but create a new parameter in the isl_pw_aff. This allows us
128 // to treat subexpressions that we cannot translate into an piecewise affine
129 // expression, as constant parameters of the piecewise affine expression.
130 if (isl_id *Id = S->getIdForParam(Expr)) {
131 isl_space *Space = isl_space_set_alloc(Ctx, 1, NbLoopSpaces);
132 Space = isl_space_set_dim_id(Space, isl_dim_param, 0, Id);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000133
Tobias Grosser0695ee42013-09-17 03:30:31 +0000134 isl_set *Domain = isl_set_universe(isl_space_copy(Space));
135 isl_aff *Affine = isl_aff_zero_on_domain(isl_local_space_from_space(Space));
136 Affine = isl_aff_add_coefficient_si(Affine, isl_dim_param, 0, 1);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000137
138 return isl_pw_aff_alloc(Domain, Affine);
139 }
140
Tobias Grosser0695ee42013-09-17 03:30:31 +0000141 return SCEVVisitor<SCEVAffinator, isl_pw_aff *>::visit(Expr);
142}
143
Tobias Grosser0d170132013-10-03 13:09:19 +0000144__isl_give isl_pw_aff *SCEVAffinator::visitConstant(const SCEVConstant *Expr) {
Tobias Grosser0695ee42013-09-17 03:30:31 +0000145 ConstantInt *Value = Expr->getValue();
146 isl_val *v;
147
148 // LLVM does not define if an integer value is interpreted as a signed or
149 // unsigned value. Hence, without further information, it is unknown how
150 // this value needs to be converted to GMP. At the moment, we only support
151 // signed operations. So we just interpret it as signed. Later, there are
152 // two options:
153 //
154 // 1. We always interpret any value as signed and convert the values on
155 // demand.
156 // 2. We pass down the signedness of the calculation and use it to interpret
157 // this constant correctly.
158 v = isl_valFromAPInt(Ctx, Value->getValue(), /* isSigned */ true);
159
160 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
Johannes Doerfert9c147372014-11-19 15:36:59 +0000161 isl_local_space *ls = isl_local_space_from_space(Space);
162 return isl_pw_aff_from_aff(isl_aff_val_on_domain(ls, v));
Tobias Grosser0695ee42013-09-17 03:30:31 +0000163}
164
165__isl_give isl_pw_aff *
166SCEVAffinator::visitTruncateExpr(const SCEVTruncateExpr *Expr) {
167 llvm_unreachable("SCEVTruncateExpr not yet supported");
168}
169
170__isl_give isl_pw_aff *
171SCEVAffinator::visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
172 llvm_unreachable("SCEVZeroExtendExpr not yet supported");
173}
174
175__isl_give isl_pw_aff *
176SCEVAffinator::visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
177 // Assuming the value is signed, a sign extension is basically a noop.
178 // TODO: Reconsider this as soon as we support unsigned values.
179 return visit(Expr->getOperand());
180}
181
182__isl_give isl_pw_aff *SCEVAffinator::visitAddExpr(const SCEVAddExpr *Expr) {
183 isl_pw_aff *Sum = visit(Expr->getOperand(0));
184
185 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
186 isl_pw_aff *NextSummand = visit(Expr->getOperand(i));
187 Sum = isl_pw_aff_add(Sum, NextSummand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000188 }
189
Tobias Grosser0695ee42013-09-17 03:30:31 +0000190 // TODO: Check for NSW and NUW.
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000191
Tobias Grosser0695ee42013-09-17 03:30:31 +0000192 return Sum;
193}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000194
Tobias Grosser0695ee42013-09-17 03:30:31 +0000195__isl_give isl_pw_aff *SCEVAffinator::visitMulExpr(const SCEVMulExpr *Expr) {
Johannes Doerfertbe409962015-03-29 20:45:09 +0000196 // Divide Expr into a constant part and the rest. Then visit both and multiply
197 // the result to obtain the representation for Expr. While the second part of
198 // ConstantAndLeftOverPair might still be a SCEVMulExpr we will not get to
199 // this point again. The reason is that if it is a multiplication it consists
200 // only of parameters and we will stop in the visit(const SCEV *) function and
201 // return the isl_pw_aff for that parameter.
202 auto ConstantAndLeftOverPair = extractConstantFactor(Expr, *S->getSE());
203 return isl_pw_aff_mul(visit(ConstantAndLeftOverPair.first),
204 visit(ConstantAndLeftOverPair.second));
Tobias Grosser0695ee42013-09-17 03:30:31 +0000205}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000206
Tobias Grosser0695ee42013-09-17 03:30:31 +0000207__isl_give isl_pw_aff *SCEVAffinator::visitUDivExpr(const SCEVUDivExpr *Expr) {
208 llvm_unreachable("SCEVUDivExpr not yet supported");
209}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000210
Tobias Grosser0695ee42013-09-17 03:30:31 +0000211__isl_give isl_pw_aff *
212SCEVAffinator::visitAddRecExpr(const SCEVAddRecExpr *Expr) {
213 assert(Expr->isAffine() && "Only affine AddRecurrences allowed");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000214
Johannes Doerfertd5d8f672015-04-26 19:55:21 +0000215 auto Flags = Expr->getNoWrapFlags();
216
Tobias Grosser0695ee42013-09-17 03:30:31 +0000217 // Directly generate isl_pw_aff for Expr if 'start' is zero.
218 if (Expr->getStart()->isZero()) {
219 assert(S->getRegion().contains(Expr->getLoop()) &&
220 "Scop does not contain the loop referenced in this AddRec");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000221
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000222 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser0695ee42013-09-17 03:30:31 +0000223 isl_pw_aff *Step = visit(Expr->getOperand(1));
224 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
225 isl_local_space *LocalSpace = isl_local_space_from_space(Space);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000226
Tobias Grosser0695ee42013-09-17 03:30:31 +0000227 int loopDimension = getLoopDepth(Expr->getLoop());
228
229 isl_aff *LAff = isl_aff_set_coefficient_si(
230 isl_aff_zero_on_domain(LocalSpace), isl_dim_in, loopDimension, 1);
231 isl_pw_aff *LPwAff = isl_pw_aff_from_aff(LAff);
232
233 // TODO: Do we need to check for NSW and NUW?
234 return isl_pw_aff_add(Start, isl_pw_aff_mul(Step, LPwAff));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000235 }
236
Tobias Grosser0695ee42013-09-17 03:30:31 +0000237 // Translate AddRecExpr from '{start, +, inc}' into 'start + {0, +, inc}'
238 // if 'start' is not zero.
Johannes Doerfertd5d8f672015-04-26 19:55:21 +0000239 // TODO: Using the original SCEV no-wrap flags is not always safe, however
240 // as our code generation is reordering the expression anyway it doesn't
241 // really matter.
Tobias Grosser0695ee42013-09-17 03:30:31 +0000242 ScalarEvolution &SE = *S->getSE();
Johannes Doerfertd5d8f672015-04-26 19:55:21 +0000243 const SCEV *ZeroStartExpr =
244 SE.getAddRecExpr(SE.getConstant(Expr->getStart()->getType(), 0),
245 Expr->getStepRecurrence(SE), Expr->getLoop(), Flags);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000246
Tobias Grosser0695ee42013-09-17 03:30:31 +0000247 isl_pw_aff *ZeroStartResult = visit(ZeroStartExpr);
248 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000249
Tobias Grosser0695ee42013-09-17 03:30:31 +0000250 return isl_pw_aff_add(ZeroStartResult, Start);
251}
252
253__isl_give isl_pw_aff *SCEVAffinator::visitSMaxExpr(const SCEVSMaxExpr *Expr) {
254 isl_pw_aff *Max = visit(Expr->getOperand(0));
255
256 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
257 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
258 Max = isl_pw_aff_max(Max, NextOperand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000259 }
260
Tobias Grosser0695ee42013-09-17 03:30:31 +0000261 return Max;
262}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000263
Tobias Grosser0695ee42013-09-17 03:30:31 +0000264__isl_give isl_pw_aff *SCEVAffinator::visitUMaxExpr(const SCEVUMaxExpr *Expr) {
265 llvm_unreachable("SCEVUMaxExpr not yet supported");
266}
267
Johannes Doerfertb9d18882015-02-11 14:54:50 +0000268__isl_give isl_pw_aff *SCEVAffinator::visitSDivInstruction(Instruction *SDiv) {
269 assert(SDiv->getOpcode() == Instruction::SDiv && "Assumed SDiv instruction!");
270 auto *SE = S->getSE();
271
272 auto *Divisor = SDiv->getOperand(1);
273 auto *DivisorSCEV = SE->getSCEV(Divisor);
274 auto *DivisorPWA = visit(DivisorSCEV);
275 assert(isa<ConstantInt>(Divisor) &&
276 "SDiv is no parameter but has a non-constant RHS.");
277
278 auto *Dividend = SDiv->getOperand(0);
279 auto *DividendSCEV = SE->getSCEV(Dividend);
280 auto *DividendPWA = visit(DividendSCEV);
281 return isl_pw_aff_tdiv_q(DividendPWA, DivisorPWA);
282}
283
Tobias Grosser0695ee42013-09-17 03:30:31 +0000284__isl_give isl_pw_aff *SCEVAffinator::visitUnknown(const SCEVUnknown *Expr) {
Johannes Doerfertb9d18882015-02-11 14:54:50 +0000285 if (Instruction *I = dyn_cast<Instruction>(Expr->getValue())) {
286 switch (I->getOpcode()) {
287 case Instruction::SDiv:
288 return visitSDivInstruction(I);
289 default:
290 break; // Fall through.
291 }
292 }
293
294 llvm_unreachable(
295 "Unknowns SCEV was neither parameter nor a valid instruction.");
Tobias Grosser0695ee42013-09-17 03:30:31 +0000296}
297
298int SCEVAffinator::getLoopDepth(const Loop *L) {
299 Loop *outerLoop = S->getRegion().outermostLoopInRegion(const_cast<Loop *>(L));
300 assert(outerLoop && "Scop does not contain this loop");
301 return L->getLoopDepth() - outerLoop->getLoopDepth();
302}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000303
Johannes Doerferte7044942015-02-24 11:58:30 +0000304/// @brief Add the bounds of @p Range to the set @p S for dimension @p dim.
305static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
306 const ConstantRange &Range,
307 int dim,
308 enum isl_dim_type type) {
309 isl_val *V;
310 isl_ctx *ctx = isl_set_get_ctx(S);
311
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000312 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
313 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000314 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000315 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
316
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000317 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000318 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000319 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000320 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000321 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
322
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000323 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000324 return isl_set_union(SLB, SUB);
325 else
326 return isl_set_intersect(SLB, SUB);
327}
328
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000329ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *AccessType, isl_ctx *Ctx,
330 const SmallVector<const SCEV *, 4> &DimensionSizes)
331 : BasePtr(BasePtr), AccessType(AccessType), DimensionSizes(DimensionSizes) {
332 const std::string BasePtrName = getIslCompatibleName("MemRef_", BasePtr, "");
333 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
334}
335
336ScopArrayInfo::~ScopArrayInfo() { isl_id_free(Id); }
337
338isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
339
340void ScopArrayInfo::dump() const { print(errs()); }
341
342void ScopArrayInfo::print(raw_ostream &OS) const {
343 OS << "ScopArrayInfo:\n";
344 OS << " Base: " << *getBasePtr() << "\n";
345 OS << " Type: " << *getType() << "\n";
346 OS << " Dimension Sizes:\n";
347 for (unsigned u = 0; u < getNumberOfDimensions(); u++)
348 OS << " " << u << ") " << *DimensionSizes[u] << "\n";
349 OS << "\n";
350}
351
352const ScopArrayInfo *
353ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
354 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
355 assert(Id && "Output dimension didn't have an ID");
356 return getFromId(Id);
357}
358
359const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
360 void *User = isl_id_get_user(Id);
361 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
362 isl_id_free(Id);
363 return SAI;
364}
365
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000366const std::string
367MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
368 switch (RT) {
369 case MemoryAccess::RT_NONE:
370 llvm_unreachable("Requested a reduction operator string for a memory "
371 "access which isn't a reduction");
372 case MemoryAccess::RT_ADD:
373 return "+";
374 case MemoryAccess::RT_MUL:
375 return "*";
376 case MemoryAccess::RT_BOR:
377 return "|";
378 case MemoryAccess::RT_BXOR:
379 return "^";
380 case MemoryAccess::RT_BAND:
381 return "&";
382 }
383 llvm_unreachable("Unknown reduction type");
384 return "";
385}
386
Johannes Doerfertf6183392014-07-01 20:52:51 +0000387/// @brief Return the reduction type for a given binary operator
388static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
389 const Instruction *Load) {
390 if (!BinOp)
391 return MemoryAccess::RT_NONE;
392 switch (BinOp->getOpcode()) {
393 case Instruction::FAdd:
394 if (!BinOp->hasUnsafeAlgebra())
395 return MemoryAccess::RT_NONE;
396 // Fall through
397 case Instruction::Add:
398 return MemoryAccess::RT_ADD;
399 case Instruction::Or:
400 return MemoryAccess::RT_BOR;
401 case Instruction::Xor:
402 return MemoryAccess::RT_BXOR;
403 case Instruction::And:
404 return MemoryAccess::RT_BAND;
405 case Instruction::FMul:
406 if (!BinOp->hasUnsafeAlgebra())
407 return MemoryAccess::RT_NONE;
408 // Fall through
409 case Instruction::Mul:
410 if (DisableMultiplicativeReductions)
411 return MemoryAccess::RT_NONE;
412 return MemoryAccess::RT_MUL;
413 default:
414 return MemoryAccess::RT_NONE;
415 }
416}
Tobias Grosser75805372011-04-29 06:27:02 +0000417//===----------------------------------------------------------------------===//
418
419MemoryAccess::~MemoryAccess() {
Tobias Grosser54a86e62011-08-18 06:31:46 +0000420 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000421 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000422}
423
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000424static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
425 switch (Access.getType()) {
426 case IRAccess::READ:
427 return MemoryAccess::READ;
428 case IRAccess::MUST_WRITE:
429 return MemoryAccess::MUST_WRITE;
430 case IRAccess::MAY_WRITE:
431 return MemoryAccess::MAY_WRITE;
432 }
433 llvm_unreachable("Unknown IRAccess type!");
434}
435
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000436const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
437 isl_id *ArrayId = getArrayId();
438 void *User = isl_id_get_user(ArrayId);
439 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
440 isl_id_free(ArrayId);
441 return SAI;
442}
443
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000444__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000445 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
446}
447
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000448__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
449 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000450 isl_map *Schedule, *ScheduledAccRel;
451 isl_union_set *UDomain;
452
453 UDomain = isl_union_set_from_set(getStatement()->getDomain());
454 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
455 Schedule = isl_map_from_union_map(USchedule);
456 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
457 return isl_pw_multi_aff_from_map(ScheduledAccRel);
458}
459
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000460__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000461 return isl_map_copy(AccessRelation);
462}
463
Johannes Doerferta99130f2014-10-13 12:58:03 +0000464std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000465 return stringFromIslObj(AccessRelation);
466}
467
Johannes Doerferta99130f2014-10-13 12:58:03 +0000468__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000469 return isl_map_get_space(AccessRelation);
470}
471
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000472__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000473 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000474}
475
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000476__isl_give isl_basic_map *
477MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000478 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000479 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000480
Tobias Grosser084d8f72012-05-29 09:29:44 +0000481 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000482 isl_basic_set_universe(Statement->getDomainSpace()),
483 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000484}
485
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000486// Formalize no out-of-bound access assumption
487//
488// When delinearizing array accesses we optimistically assume that the
489// delinearized accesses do not access out of bound locations (the subscript
490// expression of each array evaluates for each statement instance that is
491// executed to a value that is larger than zero and strictly smaller than the
492// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000493// dimension for which we do not need to assume any upper bound. At this point
494// we formalize this assumption to ensure that at code generation time the
495// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000496//
497// To find the set of constraints necessary to avoid out of bound accesses, we
498// first build the set of data locations that are not within array bounds. We
499// then apply the reverse access relation to obtain the set of iterations that
500// may contain invalid accesses and reduce this set of iterations to the ones
501// that are actually executed by intersecting them with the domain of the
502// statement. If we now project out all loop dimensions, we obtain a set of
503// parameters that may cause statement instances to be executed that may
504// possibly yield out of bound memory accesses. The complement of these
505// constraints is the set of constraints that needs to be assumed to ensure such
506// statement instances are never executed.
507void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000508 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000509 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000510 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000511 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
512 isl_pw_aff *Var =
513 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
514 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
515
516 isl_set *DimOutside;
517
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000518 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
519 isl_pw_aff *SizeE = SCEVAffinator::getPwAff(Statement, Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000520
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000521 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
522 Statement->getNumIterators());
523 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
524 isl_space_dim(Space, isl_dim_set));
525 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
526 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000527
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000528 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000529
530 Outside = isl_set_union(Outside, DimOutside);
531 }
532
533 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
534 Outside = isl_set_intersect(Outside, Statement->getDomain());
535 Outside = isl_set_params(Outside);
536 Outside = isl_set_complement(Outside);
537 Statement->getParent()->addAssumption(Outside);
538 isl_space_free(Space);
539}
540
Johannes Doerferte7044942015-02-24 11:58:30 +0000541void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
542 ScalarEvolution *SE = Statement->getParent()->getSE();
543
544 Value *Ptr = getPointerOperand(*getAccessInstruction());
545 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
546 return;
547
548 auto *PtrSCEV = SE->getSCEV(Ptr);
549 if (isa<SCEVCouldNotCompute>(PtrSCEV))
550 return;
551
552 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
553 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
554 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
555
556 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
557 if (Range.isFullSet())
558 return;
559
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000560 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000561 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000562 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
563 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
564
565 auto Min = LB.sdiv(APInt(BW, ElementSize));
566 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000567
568 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
569 AccessRange =
570 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
571 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
572}
573
Tobias Grosser619190d2015-03-30 17:22:28 +0000574__isl_give isl_map *MemoryAccess::foldAccess(const IRAccess &Access,
575 __isl_take isl_map *AccessRelation,
576 ScopStmt *Statement) {
577 int Size = Access.Subscripts.size();
578
579 for (int i = Size - 2; i >= 0; --i) {
580 isl_space *Space;
581 isl_map *MapOne, *MapTwo;
582 isl_pw_aff *DimSize = SCEVAffinator::getPwAff(Statement, Access.Sizes[i]);
583
584 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
585 isl_pw_aff_free(DimSize);
586 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
587
588 Space = isl_map_get_space(AccessRelation);
589 Space = isl_space_map_from_set(isl_space_range(Space));
590 Space = isl_space_align_params(Space, SpaceSize);
591
592 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
593 isl_id_free(ParamId);
594
595 MapOne = isl_map_universe(isl_space_copy(Space));
596 for (int j = 0; j < Size; ++j)
597 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
598 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
599
600 MapTwo = isl_map_universe(isl_space_copy(Space));
601 for (int j = 0; j < Size; ++j)
602 if (j < i || j > i + 1)
603 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
604
605 isl_local_space *LS = isl_local_space_from_space(Space);
606 isl_constraint *C;
607 C = isl_equality_alloc(isl_local_space_copy(LS));
608 C = isl_constraint_set_constant_si(C, -1);
609 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
610 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
611 MapTwo = isl_map_add_constraint(MapTwo, C);
612 C = isl_equality_alloc(LS);
613 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
614 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
615 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
616 MapTwo = isl_map_add_constraint(MapTwo, C);
617 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
618
619 MapOne = isl_map_union(MapOne, MapTwo);
620 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
621 }
622 return AccessRelation;
623}
624
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000625MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000626 ScopStmt *Statement, const ScopArrayInfo *SAI)
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000627 : AccType(getMemoryAccessType(Access)), Statement(Statement), Inst(AccInst),
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000628 newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000629
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000630 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000631 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000632 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000633
634 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000635
Tobias Grossera1879642011-12-20 10:43:14 +0000636 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000637 // We overapproximate non-affine accesses with a possible access to the
638 // whole array. For read accesses it does not make a difference, if an
639 // access must or may happen. However, for write accesses it is important to
640 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000641 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000642 AccessRelation =
643 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000644
645 computeBoundsOnAccessRelation(Access.getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000646 return;
647 }
648
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000649 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000650 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000651
Tobias Grosser79baa212014-04-10 08:38:02 +0000652 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Sebastian Pop18016682014-04-08 21:20:44 +0000653 isl_pw_aff *Affine =
654 SCEVAffinator::getPwAff(Statement, Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000655
Sebastian Pop422e33f2014-06-03 18:16:31 +0000656 if (Size == 1) {
657 // For the non delinearized arrays, divide the access function of the last
658 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000659 //
660 // A stride one array access in C expressed as A[i] is expressed in
661 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
662 // two subsequent values of 'i' index two values that are stored next to
663 // each other in memory. By this division we make this characteristic
664 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000665 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000666 Affine = isl_pw_aff_scale_down_val(Affine, v);
667 }
668
669 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
670
Tobias Grosser79baa212014-04-10 08:38:02 +0000671 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000672 }
673
Tobias Grosser619190d2015-03-30 17:22:28 +0000674 AccessRelation = foldAccess(Access, AccessRelation, Statement);
675
Tobias Grosser79baa212014-04-10 08:38:02 +0000676 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000677 AccessRelation = isl_map_set_tuple_id(
678 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000679 AccessRelation =
680 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
681
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000682 assumeNoOutOfBound(Access);
Tobias Grosseraa660a92015-03-30 00:07:50 +0000683 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000684 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000685}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000686
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000687void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000688 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000689 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000690}
691
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000692const std::string MemoryAccess::getReductionOperatorStr() const {
693 return MemoryAccess::getReductionOperatorStr(getReductionType());
694}
695
Johannes Doerfertf6183392014-07-01 20:52:51 +0000696raw_ostream &polly::operator<<(raw_ostream &OS,
697 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000698 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000699 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000700 else
701 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000702 return OS;
703}
704
Tobias Grosser75805372011-04-29 06:27:02 +0000705void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000706 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000707 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000708 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000709 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000710 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000711 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000712 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000713 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000714 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000715 break;
716 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000717 OS << "[Reduction Type: " << getReductionType() << "] ";
718 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000719 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000720}
721
Tobias Grosser74394f02013-01-14 22:40:23 +0000722void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000723
724// Create a map in the size of the provided set domain, that maps from the
725// one element of the provided set domain to another element of the provided
726// set domain.
727// The mapping is limited to all points that are equal in all but the last
728// dimension and for which the last dimension of the input is strict smaller
729// than the last dimension of the output.
730//
731// getEqualAndLarger(set[i0, i1, ..., iX]):
732//
733// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
734// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
735//
Tobias Grosserf5338802011-10-06 00:03:35 +0000736static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000737 isl_space *Space = isl_space_map_from_set(setDomain);
738 isl_map *Map = isl_map_universe(isl_space_copy(Space));
739 isl_local_space *MapLocalSpace = isl_local_space_from_space(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000740 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000741
742 // Set all but the last dimension to be equal for the input and output
743 //
744 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
745 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000746 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000747 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000748
749 // Set the last dimension of the input to be strict smaller than the
750 // last dimension of the output.
751 //
752 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
753 //
Tobias Grosseredab1352013-06-21 06:41:31 +0000754 isl_val *v;
755 isl_ctx *Ctx = isl_map_get_ctx(Map);
Tobias Grosserf5338802011-10-06 00:03:35 +0000756 isl_constraint *c = isl_inequality_alloc(isl_local_space_copy(MapLocalSpace));
Tobias Grosseredab1352013-06-21 06:41:31 +0000757 v = isl_val_int_from_si(Ctx, -1);
758 c = isl_constraint_set_coefficient_val(c, isl_dim_in, lastDimension, v);
759 v = isl_val_int_from_si(Ctx, 1);
760 c = isl_constraint_set_coefficient_val(c, isl_dim_out, lastDimension, v);
761 v = isl_val_int_from_si(Ctx, -1);
762 c = isl_constraint_set_constant_val(c, v);
Tobias Grosser75805372011-04-29 06:27:02 +0000763
Tobias Grosserc327932c2012-02-01 14:23:36 +0000764 Map = isl_map_add_constraint(Map, c);
Tobias Grosser75805372011-04-29 06:27:02 +0000765
Tobias Grosser23b36662011-10-17 08:32:36 +0000766 isl_local_space_free(MapLocalSpace);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000767 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000768}
769
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000770__isl_give isl_set *
771MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000772 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000773 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000774 isl_space *Space = isl_space_range(isl_map_get_space(S));
775 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000776
Sebastian Popa00a0292012-12-18 07:46:06 +0000777 S = isl_map_reverse(S);
778 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000779
Sebastian Popa00a0292012-12-18 07:46:06 +0000780 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
781 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
782 NextScatt = isl_map_apply_domain(NextScatt, S);
783 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000784
Sebastian Popa00a0292012-12-18 07:46:06 +0000785 isl_set *Deltas = isl_map_deltas(NextScatt);
786 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000787}
788
Sebastian Popa00a0292012-12-18 07:46:06 +0000789bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000790 int StrideWidth) const {
791 isl_set *Stride, *StrideX;
792 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000793
Sebastian Popa00a0292012-12-18 07:46:06 +0000794 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000795 StrideX = isl_set_universe(isl_set_get_space(Stride));
796 StrideX = isl_set_fix_si(StrideX, isl_dim_set, 0, StrideWidth);
797 IsStrideX = isl_set_is_equal(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000798
Tobias Grosser28dd4862012-01-24 16:42:16 +0000799 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000800 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000801
Tobias Grosser28dd4862012-01-24 16:42:16 +0000802 return IsStrideX;
803}
804
Sebastian Popa00a0292012-12-18 07:46:06 +0000805bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
806 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000807}
808
Tobias Grosser79baa212014-04-10 08:38:02 +0000809bool MemoryAccess::isScalar() const {
810 return isl_map_n_out(AccessRelation) == 0;
811}
812
Sebastian Popa00a0292012-12-18 07:46:06 +0000813bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
814 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000815}
816
Tobias Grosser5d453812011-10-06 00:04:11 +0000817void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000818 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000819 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000820}
Tobias Grosser75805372011-04-29 06:27:02 +0000821
822//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000823
Tobias Grosser54839312015-04-21 11:37:25 +0000824isl_map *ScopStmt::getSchedule() const { return isl_map_copy(Schedule); }
Tobias Grossercf3942d2011-10-06 00:04:05 +0000825
Tobias Grosser37eb4222014-02-20 21:43:54 +0000826void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
827 assert(isl_set_is_subset(NewDomain, Domain) &&
828 "New domain is not a subset of old domain!");
829 isl_set_free(Domain);
830 Domain = NewDomain;
Tobias Grosser54839312015-04-21 11:37:25 +0000831 Schedule = isl_map_intersect_domain(Schedule, isl_set_copy(Domain));
Tobias Grosser37eb4222014-02-20 21:43:54 +0000832}
833
Tobias Grosser54839312015-04-21 11:37:25 +0000834void ScopStmt::setSchedule(__isl_take isl_map *NewSchedule) {
835 assert(NewSchedule && "New schedule is nullptr");
836 isl_map_free(Schedule);
837 Schedule = NewSchedule;
Tobias Grosserb76f38532011-08-20 11:11:25 +0000838}
839
Tobias Grosser54839312015-04-21 11:37:25 +0000840void ScopStmt::buildSchedule(SmallVectorImpl<unsigned> &ScheduleVec) {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000841 unsigned NbIterators = getNumIterators();
Tobias Grosser54839312015-04-21 11:37:25 +0000842 unsigned NbScheduleDims = Parent.getMaxLoopDepth() * 2 + 1;
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000843
Tobias Grosser54839312015-04-21 11:37:25 +0000844 isl_space *Space = isl_space_set_alloc(getIslCtx(), 0, NbScheduleDims);
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000845
Tobias Grosser54839312015-04-21 11:37:25 +0000846 Schedule = isl_map_from_domain_and_range(isl_set_universe(getDomainSpace()),
Tobias Grosser654af8f2015-04-21 11:42:01 +0000847 isl_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000848
849 // Loop dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000850 for (unsigned i = 0; i < NbIterators; ++i)
Tobias Grosser654af8f2015-04-21 11:42:01 +0000851 Schedule = isl_map_equate(Schedule, isl_dim_out, 2 * i + 1, isl_dim_in, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000852
853 // Constant dimensions
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000854 for (unsigned i = 0; i < NbIterators + 1; ++i)
Tobias Grosser54839312015-04-21 11:37:25 +0000855 Schedule = isl_map_fix_si(Schedule, isl_dim_out, 2 * i, ScheduleVec[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000856
Tobias Grosser54839312015-04-21 11:37:25 +0000857 // Fill schedule dimensions.
858 for (unsigned i = 2 * NbIterators + 1; i < NbScheduleDims; ++i)
859 Schedule = isl_map_fix_si(Schedule, isl_dim_out, i, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000860
Tobias Grosser54839312015-04-21 11:37:25 +0000861 Schedule = isl_map_align_params(Schedule, Parent.getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000862}
863
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000864void ScopStmt::buildAccesses(TempScop &tempScop, BasicBlock *Block,
865 bool isApproximated) {
866 AccFuncSetType *AFS = tempScop.getAccessFunctions(Block);
867 if (!AFS)
868 return;
869
870 for (auto &AccessPair : *AFS) {
871 IRAccess &Access = AccessPair.first;
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000872 Instruction *AccessInst = AccessPair.second;
873
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000874 Type *AccessType = getAccessInstType(AccessInst)->getPointerTo();
875 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
876 Access.getBase(), AccessType, Access.Sizes);
877
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000878 if (isApproximated && Access.isWrite())
879 Access.setMayWrite();
880
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000881 MemAccs.push_back(new MemoryAccess(Access, AccessInst, this, SAI));
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000882
883 // We do not track locations for scalar memory accesses at the moment.
884 //
885 // We do not have a use for this information at the moment. If we need this
886 // at some point, the "instruction -> access" mapping needs to be enhanced
887 // as a single instruction could then possibly perform multiple accesses.
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000888 if (!Access.isScalar()) {
889 assert(!InstructionToAccess.count(AccessInst) &&
Tobias Grosser3fc91542014-02-20 21:43:45 +0000890 "Unexpected 1-to-N mapping on instruction to access map!");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000891 InstructionToAccess[AccessInst] = MemAccs.back();
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000892 }
Tobias Grosser75805372011-04-29 06:27:02 +0000893 }
894}
895
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000896void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000897 for (MemoryAccess *MA : *this)
898 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000899
900 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser54839312015-04-21 11:37:25 +0000901 Schedule = isl_map_align_params(Schedule, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000902}
903
Tobias Grosser65b00582011-11-08 15:41:19 +0000904__isl_give isl_set *ScopStmt::buildConditionSet(const Comparison &Comp) {
Tobias Grossera601fbd2011-11-09 22:34:44 +0000905 isl_pw_aff *L = SCEVAffinator::getPwAff(this, Comp.getLHS());
906 isl_pw_aff *R = SCEVAffinator::getPwAff(this, Comp.getRHS());
Tobias Grosser75805372011-04-29 06:27:02 +0000907
Tobias Grosserd2795d02011-08-18 07:51:40 +0000908 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000909 case ICmpInst::ICMP_EQ:
Tobias Grosser048c8792011-10-23 20:59:20 +0000910 return isl_pw_aff_eq_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000911 case ICmpInst::ICMP_NE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000912 return isl_pw_aff_ne_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000913 case ICmpInst::ICMP_SLT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000914 return isl_pw_aff_lt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000915 case ICmpInst::ICMP_SLE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000916 return isl_pw_aff_le_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000917 case ICmpInst::ICMP_SGT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000918 return isl_pw_aff_gt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000919 case ICmpInst::ICMP_SGE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000920 return isl_pw_aff_ge_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000921 case ICmpInst::ICMP_ULT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000922 return isl_pw_aff_lt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000923 case ICmpInst::ICMP_UGT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000924 return isl_pw_aff_gt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000925 case ICmpInst::ICMP_ULE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000926 return isl_pw_aff_le_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000927 case ICmpInst::ICMP_UGE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000928 return isl_pw_aff_ge_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000929 default:
930 llvm_unreachable("Non integer predicate not supported");
931 }
Tobias Grosser75805372011-04-29 06:27:02 +0000932}
933
Tobias Grossere19661e2011-10-07 08:46:57 +0000934__isl_give isl_set *ScopStmt::addLoopBoundsToDomain(__isl_take isl_set *Domain,
Tobias Grosser60b54f12011-11-08 15:41:28 +0000935 TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000936 isl_space *Space;
937 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000938
Tobias Grossere19661e2011-10-07 08:46:57 +0000939 Space = isl_set_get_space(Domain);
940 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000941
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000942 ScalarEvolution *SE = getParent()->getSE();
Tobias Grosser75805372011-04-29 06:27:02 +0000943 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000944 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000945 isl_pw_aff *IV =
946 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000947
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000948 // 0 <= IV.
949 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
950 Domain = isl_set_intersect(Domain, LowerBound);
951
952 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000953 const Loop *L = getLoopForDimension(i);
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000954 const SCEV *LatchExecutions = SE->getBackedgeTakenCount(L);
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000955 isl_pw_aff *UpperBound = SCEVAffinator::getPwAff(this, LatchExecutions);
956 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
Tobias Grosser75805372011-04-29 06:27:02 +0000957 Domain = isl_set_intersect(Domain, UpperBoundSet);
958 }
959
Tobias Grosserf5338802011-10-06 00:03:35 +0000960 isl_local_space_free(LocalSpace);
Tobias Grossere19661e2011-10-07 08:46:57 +0000961 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000962}
963
Tobias Grossere602a072013-05-07 07:30:56 +0000964__isl_give isl_set *ScopStmt::addConditionsToDomain(__isl_take isl_set *Domain,
965 TempScop &tempScop,
966 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000967 const Region *TopRegion = tempScop.getMaxRegion().getParent(),
Tobias Grosserd7e58642013-04-10 06:55:45 +0000968 *CurrentRegion = &CurRegion;
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000969 const BasicBlock *BranchingBB = BB ? BB : R->getEntry();
Tobias Grosser75805372011-04-29 06:27:02 +0000970
Tobias Grosser75805372011-04-29 06:27:02 +0000971 do {
Tobias Grossere19661e2011-10-07 08:46:57 +0000972 if (BranchingBB != CurrentRegion->getEntry()) {
973 if (const BBCond *Condition = tempScop.getBBCond(BranchingBB))
Tobias Grosser083d3d32014-06-28 08:59:45 +0000974 for (const auto &C : *Condition) {
975 isl_set *ConditionSet = buildConditionSet(C);
Tobias Grossere19661e2011-10-07 08:46:57 +0000976 Domain = isl_set_intersect(Domain, ConditionSet);
Tobias Grosser75805372011-04-29 06:27:02 +0000977 }
978 }
Tobias Grossere19661e2011-10-07 08:46:57 +0000979 BranchingBB = CurrentRegion->getEntry();
980 CurrentRegion = CurrentRegion->getParent();
981 } while (TopRegion != CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000982
Tobias Grossere19661e2011-10-07 08:46:57 +0000983 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000984}
985
Tobias Grossere602a072013-05-07 07:30:56 +0000986__isl_give isl_set *ScopStmt::buildDomain(TempScop &tempScop,
987 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000988 isl_space *Space;
989 isl_set *Domain;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000990 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000991
992 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
993
Tobias Grosser084d8f72012-05-29 09:29:44 +0000994 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
995
Tobias Grossere19661e2011-10-07 08:46:57 +0000996 Domain = isl_set_universe(Space);
Tobias Grossere19661e2011-10-07 08:46:57 +0000997 Domain = addLoopBoundsToDomain(Domain, tempScop);
998 Domain = addConditionsToDomain(Domain, tempScop, CurRegion);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000999 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grossere19661e2011-10-07 08:46:57 +00001000
1001 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +00001002}
1003
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001004void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
1005 int Dimension = 0;
1006 isl_ctx *Ctx = Parent.getIslCtx();
1007 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1008 Type *Ty = GEP->getPointerOperandType();
1009 ScalarEvolution &SE = *Parent.getSE();
1010
1011 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
1012 Dimension = 1;
1013 Ty = PtrTy->getElementType();
1014 }
1015
1016 while (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
1017 unsigned int Operand = 1 + Dimension;
1018
1019 if (GEP->getNumOperands() <= Operand)
1020 break;
1021
1022 const SCEV *Expr = SE.getSCEV(GEP->getOperand(Operand));
1023
1024 if (isAffineExpr(&Parent.getRegion(), Expr, SE)) {
1025 isl_pw_aff *AccessOffset = SCEVAffinator::getPwAff(this, Expr);
1026 AccessOffset =
1027 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
1028
1029 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1030 isl_local_space_copy(LSpace),
1031 isl_val_int_from_si(Ctx, ArrayTy->getNumElements())));
1032
1033 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1034 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1035 OutOfBound = isl_set_params(OutOfBound);
1036 isl_set *InBound = isl_set_complement(OutOfBound);
1037 isl_set *Executed = isl_set_params(getDomain());
1038
1039 // A => B == !A or B
1040 isl_set *InBoundIfExecuted =
1041 isl_set_union(isl_set_complement(Executed), InBound);
1042
1043 Parent.addAssumption(InBoundIfExecuted);
1044 }
1045
1046 Dimension += 1;
1047 Ty = ArrayTy->getElementType();
1048 }
1049
1050 isl_local_space_free(LSpace);
1051}
1052
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001053void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1054 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001055 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1056 deriveAssumptionsFromGEP(GEP);
1057}
1058
Tobias Grosser74394f02013-01-14 22:40:23 +00001059ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001060 Region &R, SmallVectorImpl<Loop *> &Nest,
Tobias Grosser54839312015-04-21 11:37:25 +00001061 SmallVectorImpl<unsigned> &ScheduleVec)
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001062 : Parent(parent), BB(nullptr), R(&R), Build(nullptr),
1063 NestLoops(Nest.size()) {
1064 // Setup the induction variables.
1065 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
1066 NestLoops[i] = Nest[i];
1067
1068 BaseName = getIslCompatibleName("Stmt_(", R.getNameStr(), ")");
1069
1070 Domain = buildDomain(tempScop, CurRegion);
Tobias Grosser54839312015-04-21 11:37:25 +00001071 buildSchedule(ScheduleVec);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001072
1073 BasicBlock *EntryBB = R.getEntry();
1074 for (BasicBlock *Block : R.blocks()) {
1075 buildAccesses(tempScop, Block, Block != EntryBB);
1076 deriveAssumptions(Block);
1077 }
1078 checkForReductions();
1079}
1080
1081ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Sebastian Pop860e0212013-02-15 21:26:44 +00001082 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest,
Tobias Grosser54839312015-04-21 11:37:25 +00001083 SmallVectorImpl<unsigned> &ScheduleVec)
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001084 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr),
1085 NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +00001086 // Setup the induction variables.
Tobias Grosser683b8e42014-11-30 14:33:31 +00001087 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
Sebastian Pop860e0212013-02-15 21:26:44 +00001088 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +00001089
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001090 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +00001091
Tobias Grossere19661e2011-10-07 08:46:57 +00001092 Domain = buildDomain(tempScop, CurRegion);
Tobias Grosser54839312015-04-21 11:37:25 +00001093 buildSchedule(ScheduleVec);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001094 buildAccesses(tempScop, BB);
1095 deriveAssumptions(BB);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001096 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001097}
1098
Johannes Doerferte58a0122014-06-27 20:31:28 +00001099/// @brief Collect loads which might form a reduction chain with @p StoreMA
1100///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001101/// Check if the stored value for @p StoreMA is a binary operator with one or
1102/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001103/// used only once (by @p StoreMA) and its load operands are also used only
1104/// once, we have found a possible reduction chain. It starts at an operand
1105/// load and includes the binary operator and @p StoreMA.
1106///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001107/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001108/// escape this block or into any other store except @p StoreMA.
1109void ScopStmt::collectCandiateReductionLoads(
1110 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1111 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1112 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001113 return;
1114
1115 // Skip if there is not one binary operator between the load and the store
1116 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001117 if (!BinOp)
1118 return;
1119
1120 // Skip if the binary operators has multiple uses
1121 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001122 return;
1123
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001124 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001125 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1126 return;
1127
Johannes Doerfert9890a052014-07-01 00:32:29 +00001128 // Skip if the binary operator is outside the current SCoP
1129 if (BinOp->getParent() != Store->getParent())
1130 return;
1131
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001132 // Skip if it is a multiplicative reduction and we disabled them
1133 if (DisableMultiplicativeReductions &&
1134 (BinOp->getOpcode() == Instruction::Mul ||
1135 BinOp->getOpcode() == Instruction::FMul))
1136 return;
1137
Johannes Doerferte58a0122014-06-27 20:31:28 +00001138 // Check the binary operator operands for a candidate load
1139 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1140 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1141 if (!PossibleLoad0 && !PossibleLoad1)
1142 return;
1143
1144 // A load is only a candidate if it cannot escape (thus has only this use)
1145 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001146 if (PossibleLoad0->getParent() == Store->getParent())
1147 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001148 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001149 if (PossibleLoad1->getParent() == Store->getParent())
1150 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001151}
1152
1153/// @brief Check for reductions in this ScopStmt
1154///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001155/// Iterate over all store memory accesses and check for valid binary reduction
1156/// like chains. For all candidates we check if they have the same base address
1157/// and there are no other accesses which overlap with them. The base address
1158/// check rules out impossible reductions candidates early. The overlap check,
1159/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001160/// guarantees that none of the intermediate results will escape during
1161/// execution of the loop nest. We basically check here that no other memory
1162/// access can access the same memory as the potential reduction.
1163void ScopStmt::checkForReductions() {
1164 SmallVector<MemoryAccess *, 2> Loads;
1165 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1166
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001167 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001168 // stores and collecting possible reduction loads.
1169 for (MemoryAccess *StoreMA : MemAccs) {
1170 if (StoreMA->isRead())
1171 continue;
1172
1173 Loads.clear();
1174 collectCandiateReductionLoads(StoreMA, Loads);
1175 for (MemoryAccess *LoadMA : Loads)
1176 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1177 }
1178
1179 // Then check each possible candidate pair.
1180 for (const auto &CandidatePair : Candidates) {
1181 bool Valid = true;
1182 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1183 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1184
1185 // Skip those with obviously unequal base addresses.
1186 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1187 isl_map_free(LoadAccs);
1188 isl_map_free(StoreAccs);
1189 continue;
1190 }
1191
1192 // And check if the remaining for overlap with other memory accesses.
1193 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1194 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1195 isl_set *AllAccs = isl_map_range(AllAccsRel);
1196
1197 for (MemoryAccess *MA : MemAccs) {
1198 if (MA == CandidatePair.first || MA == CandidatePair.second)
1199 continue;
1200
1201 isl_map *AccRel =
1202 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1203 isl_set *Accs = isl_map_range(AccRel);
1204
1205 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1206 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1207 Valid = Valid && isl_set_is_empty(OverlapAccs);
1208 isl_set_free(OverlapAccs);
1209 }
1210 }
1211
1212 isl_set_free(AllAccs);
1213 if (!Valid)
1214 continue;
1215
Johannes Doerfertf6183392014-07-01 20:52:51 +00001216 const LoadInst *Load =
1217 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1218 MemoryAccess::ReductionType RT =
1219 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1220
Johannes Doerferte58a0122014-06-27 20:31:28 +00001221 // If no overlapping access was found we mark the load and store as
1222 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001223 CandidatePair.first->markAsReductionLike(RT);
1224 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001225 }
Tobias Grosser75805372011-04-29 06:27:02 +00001226}
1227
Tobias Grosser74394f02013-01-14 22:40:23 +00001228std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001229
Tobias Grosser54839312015-04-21 11:37:25 +00001230std::string ScopStmt::getScheduleStr() const {
1231 return stringFromIslObj(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00001232}
1233
Tobias Grosser74394f02013-01-14 22:40:23 +00001234unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001235
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001236unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001237
Tobias Grosser54839312015-04-21 11:37:25 +00001238unsigned ScopStmt::getNumSchedule() const {
1239 return isl_map_dim(Schedule, isl_dim_out);
Tobias Grosser75805372011-04-29 06:27:02 +00001240}
1241
1242const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1243
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001244const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001245 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001246}
1247
Tobias Grosser74394f02013-01-14 22:40:23 +00001248isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001249
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001250__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001251
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001252__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001253 return isl_set_get_space(Domain);
1254}
1255
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001256__isl_give isl_id *ScopStmt::getDomainId() const {
1257 return isl_set_get_tuple_id(Domain);
1258}
Tobias Grossercd95b772012-08-30 11:49:38 +00001259
Tobias Grosser75805372011-04-29 06:27:02 +00001260ScopStmt::~ScopStmt() {
1261 while (!MemAccs.empty()) {
1262 delete MemAccs.back();
1263 MemAccs.pop_back();
1264 }
1265
1266 isl_set_free(Domain);
Tobias Grosser54839312015-04-21 11:37:25 +00001267 isl_map_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00001268}
1269
1270void ScopStmt::print(raw_ostream &OS) const {
1271 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001272 OS.indent(12) << "Domain :=\n";
1273
1274 if (Domain) {
1275 OS.indent(16) << getDomainStr() << ";\n";
1276 } else
1277 OS.indent(16) << "n/a\n";
1278
Tobias Grosser54839312015-04-21 11:37:25 +00001279 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001280
1281 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001282 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001283 } else
1284 OS.indent(16) << "n/a\n";
1285
Tobias Grosser083d3d32014-06-28 08:59:45 +00001286 for (MemoryAccess *Access : MemAccs)
1287 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001288}
1289
1290void ScopStmt::dump() const { print(dbgs()); }
1291
1292//===----------------------------------------------------------------------===//
1293/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001294
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001295void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001296 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1297 isl_set_free(Context);
1298 Context = NewContext;
1299}
1300
Tobias Grosserabfbe632013-02-05 12:09:06 +00001301void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001302 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001303 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001304 if (ParameterIds.find(Parameter) != ParameterIds.end())
1305 continue;
1306
1307 int dimension = Parameters.size();
1308
1309 Parameters.push_back(Parameter);
1310 ParameterIds[Parameter] = dimension;
1311 }
1312}
1313
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001314__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1315 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001316
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001317 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001318 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001319
Tobias Grosser8f99c162011-11-15 11:38:55 +00001320 std::string ParameterName;
1321
1322 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1323 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001324 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001325 }
1326
1327 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001328 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001329
Tobias Grosser20532b82014-04-11 17:56:49 +00001330 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1331 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001332}
Tobias Grosser75805372011-04-29 06:27:02 +00001333
Tobias Grosser6be480c2011-11-08 15:41:13 +00001334void Scop::buildContext() {
1335 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001336 Context = isl_set_universe(isl_space_copy(Space));
1337 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001338}
1339
Tobias Grosser18daaca2012-05-22 10:47:27 +00001340void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001341 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001342 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001343
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001344 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001345
Johannes Doerferte7044942015-02-24 11:58:30 +00001346 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001347 }
1348}
1349
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001350void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001351 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001352 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001353
Tobias Grosser083d3d32014-06-28 08:59:45 +00001354 for (const auto &ParamID : ParameterIds) {
1355 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001356 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001357 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001358 }
1359
1360 // Align the parameters of all data structures to the model.
1361 Context = isl_set_align_params(Context, Space);
1362
Tobias Grosser083d3d32014-06-28 08:59:45 +00001363 for (ScopStmt *Stmt : *this)
1364 Stmt->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001365}
1366
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001367void Scop::simplifyAssumedContext() {
1368 // The parameter constraints of the iteration domains give us a set of
1369 // constraints that need to hold for all cases where at least a single
1370 // statement iteration is executed in the whole scop. We now simplify the
1371 // assumed context under the assumption that such constraints hold and at
1372 // least a single statement iteration is executed. For cases where no
1373 // statement instances are executed, the assumptions we have taken about
1374 // the executed code do not matter and can be changed.
1375 //
1376 // WARNING: This only holds if the assumptions we have taken do not reduce
1377 // the set of statement instances that are executed. Otherwise we
1378 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001379 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001380 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001381 // performed. In such a case, modifying the run-time conditions and
1382 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001383 // to not be executed.
1384 //
1385 // Example:
1386 //
1387 // When delinearizing the following code:
1388 //
1389 // for (long i = 0; i < 100; i++)
1390 // for (long j = 0; j < m; j++)
1391 // A[i+p][j] = 1.0;
1392 //
1393 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001394 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001395 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1396 AssumedContext =
1397 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001398 AssumedContext = isl_set_gist_params(AssumedContext, getContext());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001399}
1400
Johannes Doerfertb164c792014-09-18 11:17:17 +00001401/// @brief Add the minimal/maximal access in @p Set to @p User.
1402static int buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
1403 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1404 isl_pw_multi_aff *MinPMA, *MaxPMA;
1405 isl_pw_aff *LastDimAff;
1406 isl_aff *OneAff;
1407 unsigned Pos;
1408
Johannes Doerfert9143d672014-09-27 11:02:39 +00001409 // Restrict the number of parameters involved in the access as the lexmin/
1410 // lexmax computation will take too long if this number is high.
1411 //
1412 // Experiments with a simple test case using an i7 4800MQ:
1413 //
1414 // #Parameters involved | Time (in sec)
1415 // 6 | 0.01
1416 // 7 | 0.04
1417 // 8 | 0.12
1418 // 9 | 0.40
1419 // 10 | 1.54
1420 // 11 | 6.78
1421 // 12 | 30.38
1422 //
1423 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1424 unsigned InvolvedParams = 0;
1425 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1426 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1427 InvolvedParams++;
1428
1429 if (InvolvedParams > RunTimeChecksMaxParameters) {
1430 isl_set_free(Set);
1431 return -1;
1432 }
1433 }
1434
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001435 Set = isl_set_remove_divs(Set);
1436
Johannes Doerfertb164c792014-09-18 11:17:17 +00001437 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1438 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1439
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001440 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1441 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1442
Johannes Doerfertb164c792014-09-18 11:17:17 +00001443 // Adjust the last dimension of the maximal access by one as we want to
1444 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1445 // we test during code generation might now point after the end of the
1446 // allocated array but we will never dereference it anyway.
1447 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1448 "Assumed at least one output dimension");
1449 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1450 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1451 OneAff = isl_aff_zero_on_domain(
1452 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1453 OneAff = isl_aff_add_constant_si(OneAff, 1);
1454 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1455 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1456
1457 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1458
1459 isl_set_free(Set);
1460 return 0;
1461}
1462
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001463static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1464 isl_set *Domain = MA->getStatement()->getDomain();
1465 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1466 return isl_set_reset_tuple_id(Domain);
1467}
1468
Johannes Doerfert9143d672014-09-27 11:02:39 +00001469bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001470 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001471 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001472 // for all memory accesses inside the SCoP.
1473 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001474 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001475 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001476 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001477 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001478 // if their access domains intersect, otherwise they are in different
1479 // ones.
Johannes Doerfert13771732014-10-01 12:40:46 +00001480 // o) We split groups such that they contain at most one read only base
1481 // address.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001482 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfertb164c792014-09-18 11:17:17 +00001483 // and maximal accesses to each array in this group.
1484 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1485
1486 AliasSetTracker AST(AA);
1487
1488 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001489 DenseSet<Value *> HasWriteAccess;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001490 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001491
1492 // Skip statements with an empty domain as they will never be executed.
1493 isl_set *StmtDomain = Stmt->getDomain();
1494 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1495 isl_set_free(StmtDomain);
1496 if (StmtDomainEmpty)
1497 continue;
1498
Johannes Doerfertb164c792014-09-18 11:17:17 +00001499 for (MemoryAccess *MA : *Stmt) {
1500 if (MA->isScalar())
1501 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001502 if (!MA->isRead())
1503 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001504 Instruction *Acc = MA->getAccessInstruction();
1505 PtrToAcc[getPointerOperand(*Acc)] = MA;
1506 AST.add(Acc);
1507 }
1508 }
1509
1510 SmallVector<AliasGroupTy, 4> AliasGroups;
1511 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001512 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001513 continue;
1514 AliasGroupTy AG;
1515 for (auto PR : AS)
1516 AG.push_back(PtrToAcc[PR.getValue()]);
1517 assert(AG.size() > 1 &&
1518 "Alias groups should contain at least two accesses");
1519 AliasGroups.push_back(std::move(AG));
1520 }
1521
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001522 // Split the alias groups based on their domain.
1523 for (unsigned u = 0; u < AliasGroups.size(); u++) {
1524 AliasGroupTy NewAG;
1525 AliasGroupTy &AG = AliasGroups[u];
1526 AliasGroupTy::iterator AGI = AG.begin();
1527 isl_set *AGDomain = getAccessDomain(*AGI);
1528 while (AGI != AG.end()) {
1529 MemoryAccess *MA = *AGI;
1530 isl_set *MADomain = getAccessDomain(MA);
1531 if (isl_set_is_disjoint(AGDomain, MADomain)) {
1532 NewAG.push_back(MA);
1533 AGI = AG.erase(AGI);
1534 isl_set_free(MADomain);
1535 } else {
1536 AGDomain = isl_set_union(AGDomain, MADomain);
1537 AGI++;
1538 }
1539 }
1540 if (NewAG.size() > 1)
1541 AliasGroups.push_back(std::move(NewAG));
1542 isl_set_free(AGDomain);
1543 }
1544
Tobias Grosserf4c24b22015-04-05 13:11:54 +00001545 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00001546 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
1547 for (AliasGroupTy &AG : AliasGroups) {
1548 NonReadOnlyBaseValues.clear();
1549 ReadOnlyPairs.clear();
1550
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001551 if (AG.size() < 2) {
1552 AG.clear();
1553 continue;
1554 }
1555
Johannes Doerfert13771732014-10-01 12:40:46 +00001556 for (auto II = AG.begin(); II != AG.end();) {
1557 Value *BaseAddr = (*II)->getBaseAddr();
1558 if (HasWriteAccess.count(BaseAddr)) {
1559 NonReadOnlyBaseValues.insert(BaseAddr);
1560 II++;
1561 } else {
1562 ReadOnlyPairs[BaseAddr].insert(*II);
1563 II = AG.erase(II);
1564 }
1565 }
1566
1567 // If we don't have read only pointers check if there are at least two
1568 // non read only pointers, otherwise clear the alias group.
1569 if (ReadOnlyPairs.empty()) {
1570 if (NonReadOnlyBaseValues.size() <= 1)
1571 AG.clear();
1572 continue;
1573 }
1574
1575 // If we don't have non read only pointers clear the alias group.
1576 if (NonReadOnlyBaseValues.empty()) {
1577 AG.clear();
1578 continue;
1579 }
1580
1581 // If we have both read only and non read only base pointers we combine
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001582 // the non read only ones with exactly one read only one at a time into a
Johannes Doerfert13771732014-10-01 12:40:46 +00001583 // new alias group and clear the old alias group in the end.
1584 for (const auto &ReadOnlyPair : ReadOnlyPairs) {
1585 AliasGroupTy AGNonReadOnly = AG;
1586 for (MemoryAccess *MA : ReadOnlyPair.second)
1587 AGNonReadOnly.push_back(MA);
1588 AliasGroups.push_back(std::move(AGNonReadOnly));
1589 }
1590 AG.clear();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001591 }
1592
1593 for (AliasGroupTy &AG : AliasGroups) {
Johannes Doerfert13771732014-10-01 12:40:46 +00001594 if (AG.empty())
1595 continue;
1596
Johannes Doerfertb164c792014-09-18 11:17:17 +00001597 MinMaxVectorTy *MinMaxAccesses = new MinMaxVectorTy();
1598 MinMaxAccesses->reserve(AG.size());
1599
1600 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
1601 for (MemoryAccess *MA : AG)
1602 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
1603 Accesses = isl_union_map_intersect_domain(Accesses, getDomains());
1604
1605 isl_union_set *Locations = isl_union_map_range(Accesses);
1606 Locations = isl_union_set_intersect_params(Locations, getAssumedContext());
1607 Locations = isl_union_set_coalesce(Locations);
1608 Locations = isl_union_set_detect_equalities(Locations);
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001609 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
1610 MinMaxAccesses));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001611 isl_union_set_free(Locations);
Johannes Doerfertb164c792014-09-18 11:17:17 +00001612 MinMaxAliasGroups.push_back(MinMaxAccesses);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001613
1614 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001615 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001616 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001617
Tobias Grosser71500722015-03-28 15:11:14 +00001618 // Bail out if the number of values we need to compare is too large.
1619 // This is important as the number of comparisions grows quadratically with
1620 // the number of values we need to compare.
1621 for (const auto *Values : MinMaxAliasGroups)
1622 if (Values->size() > RunTimeChecksMaxArraysPerGroup)
1623 return false;
1624
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001625 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001626}
1627
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001628static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
1629 ScopDetection &SD) {
1630
1631 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
1632
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001633 unsigned MinLD = INT_MAX, MaxLD = 0;
1634 for (BasicBlock *BB : R.blocks()) {
1635 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00001636 if (!R.contains(L))
1637 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001638 if (BoxedLoops && BoxedLoops->count(L))
1639 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001640 unsigned LD = L->getLoopDepth();
1641 MinLD = std::min(MinLD, LD);
1642 MaxLD = std::max(MaxLD, LD);
1643 }
1644 }
1645
1646 // Handle the case that there is no loop in the SCoP first.
1647 if (MaxLD == 0)
1648 return 1;
1649
1650 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
1651 assert(MaxLD >= MinLD &&
1652 "Maximal loop depth was smaller than mininaml loop depth?");
1653 return MaxLD - MinLD + 1;
1654}
1655
Tobias Grosser3f296192015-01-01 23:01:11 +00001656void Scop::dropConstantScheduleDims() {
1657 isl_union_map *FullSchedule = getSchedule();
1658
1659 if (isl_union_map_n_map(FullSchedule) == 0) {
1660 isl_union_map_free(FullSchedule);
1661 return;
1662 }
1663
1664 isl_set *ScheduleSpace =
1665 isl_set_from_union_set(isl_union_map_range(FullSchedule));
1666 isl_map *DropDimMap = isl_set_identity(isl_set_copy(ScheduleSpace));
1667
1668 int NumDimsDropped = 0;
Johannes Doerfert3f21e272015-03-04 22:23:21 +00001669 for (unsigned i = 0; i < isl_set_dim(ScheduleSpace, isl_dim_set); i += 2) {
1670 isl_val *FixedVal =
1671 isl_set_plain_get_val_if_fixed(ScheduleSpace, isl_dim_set, i);
1672 if (isl_val_is_int(FixedVal)) {
1673 DropDimMap =
1674 isl_map_project_out(DropDimMap, isl_dim_out, i - NumDimsDropped, 1);
1675 NumDimsDropped++;
Tobias Grosser3f296192015-01-01 23:01:11 +00001676 }
Johannes Doerfert3f21e272015-03-04 22:23:21 +00001677 isl_val_free(FixedVal);
1678 }
Tobias Grosser3f296192015-01-01 23:01:11 +00001679
Tobias Grosser3f296192015-01-01 23:01:11 +00001680 for (auto *S : *this) {
Tobias Grosser54839312015-04-21 11:37:25 +00001681 isl_map *Schedule = S->getSchedule();
Tobias Grosser3f296192015-01-01 23:01:11 +00001682 Schedule = isl_map_apply_range(Schedule, isl_map_copy(DropDimMap));
Tobias Grosser54839312015-04-21 11:37:25 +00001683 S->setSchedule(Schedule);
Tobias Grosser3f296192015-01-01 23:01:11 +00001684 }
1685 isl_set_free(ScheduleSpace);
1686 isl_map_free(DropDimMap);
1687}
1688
Tobias Grosser0e27e242011-10-06 00:03:48 +00001689Scop::Scop(TempScop &tempScop, LoopInfo &LI, ScalarEvolution &ScalarEvolution,
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001690 ScopDetection &SD, isl_ctx *Context)
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001691 : SE(&ScalarEvolution), R(tempScop.getMaxRegion()), IsOptimized(false),
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001692 MaxLoopDepth(getMaxLoopDepthInRegion(tempScop.getMaxRegion(), LI, SD)) {
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001693 IslCtx = Context;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001694
Tobias Grosser6be480c2011-11-08 15:41:13 +00001695 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001696
Tobias Grosserabfbe632013-02-05 12:09:06 +00001697 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser54839312015-04-21 11:37:25 +00001698 SmallVector<unsigned, 8> Schedule;
Tobias Grosser75805372011-04-29 06:27:02 +00001699
Tobias Grosser54839312015-04-21 11:37:25 +00001700 Schedule.assign(MaxLoopDepth + 1, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001701
Tobias Grosser54839312015-04-21 11:37:25 +00001702 // Build the iteration domain, access functions and schedule functions
Tobias Grosser75805372011-04-29 06:27:02 +00001703 // traversing the region tree.
Tobias Grosser54839312015-04-21 11:37:25 +00001704 buildScop(tempScop, getRegion(), NestLoops, Schedule, LI, SD);
Tobias Grosser75805372011-04-29 06:27:02 +00001705
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001706 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001707 addParameterBounds();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001708 simplifyAssumedContext();
Tobias Grosser3f296192015-01-01 23:01:11 +00001709 dropConstantScheduleDims();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001710
Tobias Grosser75805372011-04-29 06:27:02 +00001711 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1712}
1713
1714Scop::~Scop() {
1715 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001716 isl_set_free(AssumedContext);
Tobias Grosser75805372011-04-29 06:27:02 +00001717
1718 // Free the statements;
Tobias Grosser083d3d32014-06-28 08:59:45 +00001719 for (ScopStmt *Stmt : *this)
1720 delete Stmt;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001721
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001722 // Free the ScopArrayInfo objects.
Tobias Grossere71ed192015-05-06 10:05:20 +00001723 for (auto &ScopArrayInfoPair : arrays())
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001724 delete ScopArrayInfoPair.second;
1725
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) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001739 const ScopArrayInfo *&SAI = ScopArrayInfoMap[BasePtr];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001740 if (!SAI)
1741 SAI = new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001742 return SAI;
1743}
1744
1745const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr) {
1746 const SCEV *PtrSCEV = SE->getSCEV(BasePtr);
1747 const SCEVUnknown *PtrBaseSCEV =
1748 cast<SCEVUnknown>(SE->getPointerBase(PtrSCEV));
1749 const ScopArrayInfo *SAI = ScopArrayInfoMap[PtrBaseSCEV->getValue()];
1750 assert(SAI && "No ScopArrayInfo available for this base pointer");
1751 return SAI;
1752}
1753
Tobias Grosser74394f02013-01-14 22:40:23 +00001754std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001755std::string Scop::getAssumedContextStr() const {
1756 return stringFromIslObj(AssumedContext);
1757}
Tobias Grosser75805372011-04-29 06:27:02 +00001758
1759std::string Scop::getNameStr() const {
1760 std::string ExitName, EntryName;
1761 raw_string_ostream ExitStr(ExitName);
1762 raw_string_ostream EntryStr(EntryName);
1763
Tobias Grosserf240b482014-01-09 10:42:15 +00001764 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001765 EntryStr.str();
1766
1767 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001768 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001769 ExitStr.str();
1770 } else
1771 ExitName = "FunctionExit";
1772
1773 return EntryName + "---" + ExitName;
1774}
1775
Tobias Grosser74394f02013-01-14 22:40:23 +00001776__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001777__isl_give isl_space *Scop::getParamSpace() const {
1778 return isl_set_get_space(this->Context);
1779}
1780
Tobias Grossere86109f2013-10-29 21:05:49 +00001781__isl_give isl_set *Scop::getAssumedContext() const {
1782 return isl_set_copy(AssumedContext);
1783}
1784
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001785void Scop::addAssumption(__isl_take isl_set *Set) {
1786 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001787 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001788}
1789
Tobias Grosser75805372011-04-29 06:27:02 +00001790void Scop::printContext(raw_ostream &OS) const {
1791 OS << "Context:\n";
1792
1793 if (!Context) {
1794 OS.indent(4) << "n/a\n\n";
1795 return;
1796 }
1797
1798 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001799
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001800 OS.indent(4) << "Assumed Context:\n";
1801 if (!AssumedContext) {
1802 OS.indent(4) << "n/a\n\n";
1803 return;
1804 }
1805
1806 OS.indent(4) << getAssumedContextStr() << "\n";
1807
Tobias Grosser083d3d32014-06-28 08:59:45 +00001808 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001809 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001810 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1811 }
Tobias Grosser75805372011-04-29 06:27:02 +00001812}
1813
Johannes Doerfertb164c792014-09-18 11:17:17 +00001814void Scop::printAliasAssumptions(raw_ostream &OS) const {
1815 OS.indent(4) << "Alias Groups (" << MinMaxAliasGroups.size() << "):\n";
1816 if (MinMaxAliasGroups.empty()) {
1817 OS.indent(8) << "n/a\n";
1818 return;
1819 }
1820 for (MinMaxVectorTy *MinMaxAccesses : MinMaxAliasGroups) {
1821 OS.indent(8) << "[[";
1822 for (MinMaxAccessTy &MinMacAccess : *MinMaxAccesses)
1823 OS << " <" << MinMacAccess.first << ", " << MinMacAccess.second << ">";
1824 OS << " ]]\n";
1825 }
1826}
1827
Tobias Grosser75805372011-04-29 06:27:02 +00001828void Scop::printStatements(raw_ostream &OS) const {
1829 OS << "Statements {\n";
1830
Tobias Grosser083d3d32014-06-28 08:59:45 +00001831 for (ScopStmt *Stmt : *this)
1832 OS.indent(4) << *Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001833
1834 OS.indent(4) << "}\n";
1835}
1836
Tobias Grosser75805372011-04-29 06:27:02 +00001837void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00001838 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
1839 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00001840 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00001841 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001842 printContext(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001843 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001844 printStatements(OS.indent(4));
1845}
1846
1847void Scop::dump() const { print(dbgs()); }
1848
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001849isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00001850
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001851__isl_give isl_union_set *Scop::getDomains() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001852 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001853
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001854 for (ScopStmt *Stmt : *this)
1855 Domain = isl_union_set_add_set(Domain, Stmt->getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001856
1857 return Domain;
1858}
1859
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001860__isl_give isl_union_map *Scop::getMustWrites() {
1861 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1862
1863 for (ScopStmt *Stmt : *this) {
1864 for (MemoryAccess *MA : *Stmt) {
1865 if (!MA->isMustWrite())
1866 continue;
1867
1868 isl_set *Domain = Stmt->getDomain();
1869 isl_map *AccessDomain = MA->getAccessRelation();
1870 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1871 Write = isl_union_map_add_map(Write, AccessDomain);
1872 }
1873 }
1874 return isl_union_map_coalesce(Write);
1875}
1876
1877__isl_give isl_union_map *Scop::getMayWrites() {
1878 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1879
1880 for (ScopStmt *Stmt : *this) {
1881 for (MemoryAccess *MA : *Stmt) {
1882 if (!MA->isMayWrite())
1883 continue;
1884
1885 isl_set *Domain = Stmt->getDomain();
1886 isl_map *AccessDomain = MA->getAccessRelation();
1887 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1888 Write = isl_union_map_add_map(Write, AccessDomain);
1889 }
1890 }
1891 return isl_union_map_coalesce(Write);
1892}
1893
Tobias Grosser37eb4222014-02-20 21:43:54 +00001894__isl_give isl_union_map *Scop::getWrites() {
1895 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1896
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001897 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001898 for (MemoryAccess *MA : *Stmt) {
1899 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001900 continue;
1901
1902 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001903 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001904 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1905 Write = isl_union_map_add_map(Write, AccessDomain);
1906 }
1907 }
1908 return isl_union_map_coalesce(Write);
1909}
1910
1911__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001912 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001913
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001914 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001915 for (MemoryAccess *MA : *Stmt) {
1916 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001917 continue;
1918
1919 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001920 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001921
1922 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1923 Read = isl_union_map_add_map(Read, AccessDomain);
1924 }
1925 }
1926 return isl_union_map_coalesce(Read);
1927}
1928
1929__isl_give isl_union_map *Scop::getSchedule() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001930 isl_union_map *Schedule = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001931
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001932 for (ScopStmt *Stmt : *this)
Tobias Grosser54839312015-04-21 11:37:25 +00001933 Schedule = isl_union_map_add_map(Schedule, Stmt->getSchedule());
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001934
Tobias Grosser37eb4222014-02-20 21:43:54 +00001935 return isl_union_map_coalesce(Schedule);
1936}
1937
1938bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
1939 bool Changed = false;
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001940 for (ScopStmt *Stmt : *this) {
Tobias Grosser37eb4222014-02-20 21:43:54 +00001941 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt->getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001942 isl_union_set *NewStmtDomain = isl_union_set_intersect(
1943 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
1944
1945 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
1946 isl_union_set_free(StmtDomain);
1947 isl_union_set_free(NewStmtDomain);
1948 continue;
1949 }
1950
1951 Changed = true;
1952
1953 isl_union_set_free(StmtDomain);
1954 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
1955
1956 if (isl_union_set_is_empty(NewStmtDomain)) {
1957 Stmt->restrictDomain(isl_set_empty(Stmt->getDomainSpace()));
1958 isl_union_set_free(NewStmtDomain);
1959 } else
1960 Stmt->restrictDomain(isl_set_from_union_set(NewStmtDomain));
1961 }
1962 isl_union_set_free(Domain);
1963 return Changed;
1964}
1965
Tobias Grosser75805372011-04-29 06:27:02 +00001966ScalarEvolution *Scop::getSE() const { return SE; }
1967
1968bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
1969 if (tempScop.getAccessFunctions(BB))
1970 return false;
1971
1972 return true;
1973}
1974
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001975void Scop::addScopStmt(BasicBlock *BB, Region *R, TempScop &tempScop,
1976 const Region &CurRegion,
1977 SmallVectorImpl<Loop *> &NestLoops,
Tobias Grosser54839312015-04-21 11:37:25 +00001978 SmallVectorImpl<unsigned> &ScheduleVec) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001979 ScopStmt *Stmt;
1980
1981 if (BB) {
Tobias Grosser654af8f2015-04-21 11:42:01 +00001982 Stmt =
1983 new ScopStmt(*this, tempScop, CurRegion, *BB, NestLoops, ScheduleVec);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001984 StmtMap[BB] = Stmt;
1985 } else {
1986 assert(R && "Either a basic block or a region is needed to "
1987 "create a new SCoP stmt.");
Tobias Grosser54839312015-04-21 11:37:25 +00001988 Stmt = new ScopStmt(*this, tempScop, CurRegion, *R, NestLoops, ScheduleVec);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001989 for (BasicBlock *BB : R->blocks())
1990 StmtMap[BB] = Stmt;
1991 }
1992
1993 // Insert all statements into the statement map and the statement vector.
1994 Stmts.push_back(Stmt);
1995
Tobias Grosser54839312015-04-21 11:37:25 +00001996 // Increasing the Schedule function is OK for the moment, because
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001997 // we are using a depth first iterator and the program is well structured.
Tobias Grosser54839312015-04-21 11:37:25 +00001998 ++ScheduleVec[NestLoops.size()];
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001999}
2000
Tobias Grosser74394f02013-01-14 22:40:23 +00002001void Scop::buildScop(TempScop &tempScop, const Region &CurRegion,
2002 SmallVectorImpl<Loop *> &NestLoops,
Tobias Grosser54839312015-04-21 11:37:25 +00002003 SmallVectorImpl<unsigned> &ScheduleVec, LoopInfo &LI,
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002004 ScopDetection &SD) {
2005 if (SD.isNonAffineSubRegion(&CurRegion, &getRegion()))
2006 return addScopStmt(nullptr, const_cast<Region *>(&CurRegion), tempScop,
Tobias Grosser54839312015-04-21 11:37:25 +00002007 CurRegion, NestLoops, ScheduleVec);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002008
Tobias Grosser75805372011-04-29 06:27:02 +00002009 Loop *L = castToLoop(CurRegion, LI);
2010
2011 if (L)
2012 NestLoops.push_back(L);
2013
2014 unsigned loopDepth = NestLoops.size();
Tobias Grosser54839312015-04-21 11:37:25 +00002015 assert(ScheduleVec.size() > loopDepth && "Schedule not big enough!");
Tobias Grosser75805372011-04-29 06:27:02 +00002016
2017 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00002018 E = CurRegion.element_end();
2019 I != E; ++I)
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002020 if (I->isSubRegion()) {
Tobias Grosser654af8f2015-04-21 11:42:01 +00002021 buildScop(tempScop, *I->getNodeAs<Region>(), NestLoops, ScheduleVec, LI,
2022 SD);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002023 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00002024 BasicBlock *BB = I->getNodeAs<BasicBlock>();
2025
2026 if (isTrivialBB(BB, tempScop))
2027 continue;
2028
Tobias Grosser54839312015-04-21 11:37:25 +00002029 addScopStmt(BB, nullptr, tempScop, CurRegion, NestLoops, ScheduleVec);
Tobias Grosser75805372011-04-29 06:27:02 +00002030 }
2031
2032 if (!L)
2033 return;
2034
2035 // Exiting a loop region.
Tobias Grosser54839312015-04-21 11:37:25 +00002036 ScheduleVec[loopDepth] = 0;
Tobias Grosser75805372011-04-29 06:27:02 +00002037 NestLoops.pop_back();
Tobias Grosser54839312015-04-21 11:37:25 +00002038 ++ScheduleVec[loopDepth - 1];
Tobias Grosser75805372011-04-29 06:27:02 +00002039}
2040
Johannes Doerfert7c494212014-10-31 23:13:39 +00002041ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
2042 const auto &StmtMapIt = StmtMap.find(BB);
2043 if (StmtMapIt == StmtMap.end())
2044 return nullptr;
2045 return StmtMapIt->second;
2046}
2047
Tobias Grosser75805372011-04-29 06:27:02 +00002048//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00002049ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
2050 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00002051 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00002052}
2053
2054ScopInfo::~ScopInfo() {
2055 clear();
2056 isl_ctx_free(ctx);
2057}
2058
Tobias Grosser75805372011-04-29 06:27:02 +00002059void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00002060 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00002061 AU.addRequired<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00002062 AU.addRequired<ScalarEvolution>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002063 AU.addRequired<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00002064 AU.addRequired<TempScopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002065 AU.addRequired<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00002066 AU.setPreservesAll();
2067}
2068
2069bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Chandler Carruthf5579872015-01-17 14:16:56 +00002070 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002071 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002072 ScopDetection &SD = getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00002073 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
2074
2075 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop(R);
2076
2077 // This region is no Scop.
2078 if (!tempScop) {
Tobias Grosserc98a8fc2014-11-14 11:12:31 +00002079 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002080 return false;
2081 }
2082
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002083 scop = new Scop(*tempScop, LI, SE, SD, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00002084
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002085 if (!PollyUseRuntimeAliasChecks) {
2086 // Statistics.
2087 ++ScopFound;
2088 if (scop->getMaxLoopDepth() > 0)
2089 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002090 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002091 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002092
Johannes Doerfert9143d672014-09-27 11:02:39 +00002093 // If a problem occurs while building the alias groups we need to delete
2094 // this SCoP and pretend it wasn't valid in the first place.
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002095 if (scop->buildAliasGroups(AA)) {
2096 // Statistics.
2097 ++ScopFound;
2098 if (scop->getMaxLoopDepth() > 0)
2099 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002100 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002101 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002102
2103 DEBUG(dbgs()
2104 << "\n\nNOTE: Run time checks for " << scop->getNameStr()
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002105 << " could not be created as the number of parameters involved is too "
Johannes Doerfert9143d672014-09-27 11:02:39 +00002106 "high. The SCoP will be "
2107 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust the "
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002108 "maximal number of parameters but be advised that the compile time "
Johannes Doerfert9143d672014-09-27 11:02:39 +00002109 "might increase exponentially.\n\n");
2110
2111 delete scop;
2112 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002113 return false;
2114}
2115
2116char ScopInfo::ID = 0;
2117
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002118Pass *polly::createScopInfoPass() { return new ScopInfo(); }
2119
Tobias Grosser73600b82011-10-08 00:30:40 +00002120INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
2121 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002122 false);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002123INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Chandler Carruthf5579872015-01-17 14:16:56 +00002124INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00002125INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002126INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002127INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002128INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Tobias Grosser73600b82011-10-08 00:30:40 +00002129INITIALIZE_PASS_END(ScopInfo, "polly-scops",
2130 "Polly - Create polyhedral description of Scops", false,
2131 false)