blob: 59bf345cd6f262e0e0bb1a5fa27e3a6216a2958e [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"
Sebastian Pop27c10c62013-03-22 22:07:43 +000021#include "polly/ScopInfo.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000022#include "polly/Options.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 Grosser75805372011-04-29 06:27:02 +000027#include "llvm/ADT/SetVector.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000028#include "llvm/ADT/MapVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000029#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000030#include "llvm/ADT/StringExtras.h"
Tobias Grosser83628182013-05-07 08:11:54 +000031#include "llvm/Analysis/LoopInfo.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000032#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser83628182013-05-07 08:11:54 +000033#include "llvm/Analysis/RegionIterator.h"
34#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000035#include "llvm/Support/Debug.h"
36
37#include "isl/constraint.h"
38#include "isl/set.h"
39#include "isl/map.h"
Tobias Grosser37eb4222014-02-20 21:43:54 +000040#include "isl/union_map.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000041#include "isl/aff.h"
42#include "isl/printer.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000043#include "isl/local_space.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000044#include "isl/options.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000045#include "isl/val.h"
Chandler Carruth95fef942014-04-22 03:30:19 +000046
Tobias Grosser75805372011-04-29 06:27:02 +000047#include <sstream>
48#include <string>
49#include <vector>
50
51using namespace llvm;
52using namespace polly;
53
Chandler Carruth95fef942014-04-22 03:30:19 +000054#define DEBUG_TYPE "polly-scops"
55
Tobias Grosser74394f02013-01-14 22:40:23 +000056STATISTIC(ScopFound, "Number of valid Scops");
57STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000058
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000059// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000060// operations can overflow easily. Additive reductions and bit operations
61// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000062static cl::opt<bool> DisableMultiplicativeReductions(
63 "polly-disable-multiplicative-reductions",
64 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
65 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000066
Johannes Doerfert9143d672014-09-27 11:02:39 +000067static cl::opt<unsigned> RunTimeChecksMaxParameters(
68 "polly-rtc-max-parameters",
69 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
70 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
71
Tobias Grosser71500722015-03-28 15:11:14 +000072static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
73 "polly-rtc-max-arrays-per-group",
74 cl::desc("The maximal number of arrays to compare in each alias group."),
75 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
76
Tobias Grosser0695ee42013-09-17 03:30:31 +000077/// Translate a 'const SCEV *' expression in an isl_pw_aff.
Tobias Grosserabfbe632013-02-05 12:09:06 +000078struct SCEVAffinator : public SCEVVisitor<SCEVAffinator, isl_pw_aff *> {
Tobias Grosser0695ee42013-09-17 03:30:31 +000079public:
Tobias Grosser0695ee42013-09-17 03:30:31 +000080 /// @brief Translate a 'const SCEV *' to an isl_pw_aff.
81 ///
82 /// @param Stmt The location at which the scalar evolution expression
83 /// is evaluated.
84 /// @param Expr The expression that is translated.
85 static __isl_give isl_pw_aff *getPwAff(ScopStmt *Stmt, const SCEV *Expr);
86
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000087private:
Tobias Grosser3cc99742012-06-06 16:33:15 +000088 isl_ctx *Ctx;
Tobias Grosserf5338802011-10-06 00:03:35 +000089 int NbLoopSpaces;
Tobias Grosser3cc99742012-06-06 16:33:15 +000090 const Scop *S;
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000091
Tobias Grosser0695ee42013-09-17 03:30:31 +000092 SCEVAffinator(const ScopStmt *Stmt);
93 int getLoopDepth(const Loop *L);
Tobias Grosser60b54f12011-11-08 15:41:28 +000094
Tobias Grosser0695ee42013-09-17 03:30:31 +000095 __isl_give isl_pw_aff *visit(const SCEV *Expr);
96 __isl_give isl_pw_aff *visitConstant(const SCEVConstant *Expr);
97 __isl_give isl_pw_aff *visitTruncateExpr(const SCEVTruncateExpr *Expr);
98 __isl_give isl_pw_aff *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr);
99 __isl_give isl_pw_aff *visitSignExtendExpr(const SCEVSignExtendExpr *Expr);
100 __isl_give isl_pw_aff *visitAddExpr(const SCEVAddExpr *Expr);
101 __isl_give isl_pw_aff *visitMulExpr(const SCEVMulExpr *Expr);
102 __isl_give isl_pw_aff *visitUDivExpr(const SCEVUDivExpr *Expr);
103 __isl_give isl_pw_aff *visitAddRecExpr(const SCEVAddRecExpr *Expr);
104 __isl_give isl_pw_aff *visitSMaxExpr(const SCEVSMaxExpr *Expr);
105 __isl_give isl_pw_aff *visitUMaxExpr(const SCEVUMaxExpr *Expr);
106 __isl_give isl_pw_aff *visitUnknown(const SCEVUnknown *Expr);
Johannes Doerfertb9d18882015-02-11 14:54:50 +0000107 __isl_give isl_pw_aff *visitSDivInstruction(Instruction *SDiv);
Tobias Grosser60b54f12011-11-08 15:41:28 +0000108
Tobias Grosser0695ee42013-09-17 03:30:31 +0000109 friend struct SCEVVisitor<SCEVAffinator, isl_pw_aff *>;
110};
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000111
Tobias Grosser0695ee42013-09-17 03:30:31 +0000112SCEVAffinator::SCEVAffinator(const ScopStmt *Stmt)
113 : Ctx(Stmt->getIslCtx()), NbLoopSpaces(Stmt->getNumIterators()),
114 S(Stmt->getParent()) {}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000115
Tobias Grosser0695ee42013-09-17 03:30:31 +0000116__isl_give isl_pw_aff *SCEVAffinator::getPwAff(ScopStmt *Stmt,
117 const SCEV *Scev) {
118 Scop *S = Stmt->getParent();
119 const Region *Reg = &S->getRegion();
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000120
Tobias Grosser0695ee42013-09-17 03:30:31 +0000121 S->addParams(getParamsInAffineExpr(Reg, Scev, *S->getSE()));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000122
Tobias Grosser0695ee42013-09-17 03:30:31 +0000123 SCEVAffinator Affinator(Stmt);
124 return Affinator.visit(Scev);
125}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000126
Tobias Grosser0695ee42013-09-17 03:30:31 +0000127__isl_give isl_pw_aff *SCEVAffinator::visit(const SCEV *Expr) {
128 // In case the scev is a valid parameter, we do not further analyze this
129 // expression, but create a new parameter in the isl_pw_aff. This allows us
130 // to treat subexpressions that we cannot translate into an piecewise affine
131 // expression, as constant parameters of the piecewise affine expression.
132 if (isl_id *Id = S->getIdForParam(Expr)) {
133 isl_space *Space = isl_space_set_alloc(Ctx, 1, NbLoopSpaces);
134 Space = isl_space_set_dim_id(Space, isl_dim_param, 0, Id);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000135
Tobias Grosser0695ee42013-09-17 03:30:31 +0000136 isl_set *Domain = isl_set_universe(isl_space_copy(Space));
137 isl_aff *Affine = isl_aff_zero_on_domain(isl_local_space_from_space(Space));
138 Affine = isl_aff_add_coefficient_si(Affine, isl_dim_param, 0, 1);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000139
140 return isl_pw_aff_alloc(Domain, Affine);
141 }
142
Tobias Grosser0695ee42013-09-17 03:30:31 +0000143 return SCEVVisitor<SCEVAffinator, isl_pw_aff *>::visit(Expr);
144}
145
Tobias Grosser0d170132013-10-03 13:09:19 +0000146__isl_give isl_pw_aff *SCEVAffinator::visitConstant(const SCEVConstant *Expr) {
Tobias Grosser0695ee42013-09-17 03:30:31 +0000147 ConstantInt *Value = Expr->getValue();
148 isl_val *v;
149
150 // LLVM does not define if an integer value is interpreted as a signed or
151 // unsigned value. Hence, without further information, it is unknown how
152 // this value needs to be converted to GMP. At the moment, we only support
153 // signed operations. So we just interpret it as signed. Later, there are
154 // two options:
155 //
156 // 1. We always interpret any value as signed and convert the values on
157 // demand.
158 // 2. We pass down the signedness of the calculation and use it to interpret
159 // this constant correctly.
160 v = isl_valFromAPInt(Ctx, Value->getValue(), /* isSigned */ true);
161
162 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
Johannes Doerfert9c147372014-11-19 15:36:59 +0000163 isl_local_space *ls = isl_local_space_from_space(Space);
164 return isl_pw_aff_from_aff(isl_aff_val_on_domain(ls, v));
Tobias Grosser0695ee42013-09-17 03:30:31 +0000165}
166
167__isl_give isl_pw_aff *
168SCEVAffinator::visitTruncateExpr(const SCEVTruncateExpr *Expr) {
169 llvm_unreachable("SCEVTruncateExpr not yet supported");
170}
171
172__isl_give isl_pw_aff *
173SCEVAffinator::visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
174 llvm_unreachable("SCEVZeroExtendExpr not yet supported");
175}
176
177__isl_give isl_pw_aff *
178SCEVAffinator::visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
179 // Assuming the value is signed, a sign extension is basically a noop.
180 // TODO: Reconsider this as soon as we support unsigned values.
181 return visit(Expr->getOperand());
182}
183
184__isl_give isl_pw_aff *SCEVAffinator::visitAddExpr(const SCEVAddExpr *Expr) {
185 isl_pw_aff *Sum = visit(Expr->getOperand(0));
186
187 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
188 isl_pw_aff *NextSummand = visit(Expr->getOperand(i));
189 Sum = isl_pw_aff_add(Sum, NextSummand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000190 }
191
Tobias Grosser0695ee42013-09-17 03:30:31 +0000192 // TODO: Check for NSW and NUW.
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000193
Tobias Grosser0695ee42013-09-17 03:30:31 +0000194 return Sum;
195}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000196
Tobias Grosser0695ee42013-09-17 03:30:31 +0000197__isl_give isl_pw_aff *SCEVAffinator::visitMulExpr(const SCEVMulExpr *Expr) {
Johannes Doerfertbe409962015-03-29 20:45:09 +0000198 // Divide Expr into a constant part and the rest. Then visit both and multiply
199 // the result to obtain the representation for Expr. While the second part of
200 // ConstantAndLeftOverPair might still be a SCEVMulExpr we will not get to
201 // this point again. The reason is that if it is a multiplication it consists
202 // only of parameters and we will stop in the visit(const SCEV *) function and
203 // return the isl_pw_aff for that parameter.
204 auto ConstantAndLeftOverPair = extractConstantFactor(Expr, *S->getSE());
205 return isl_pw_aff_mul(visit(ConstantAndLeftOverPair.first),
206 visit(ConstantAndLeftOverPair.second));
Tobias Grosser0695ee42013-09-17 03:30:31 +0000207}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000208
Tobias Grosser0695ee42013-09-17 03:30:31 +0000209__isl_give isl_pw_aff *SCEVAffinator::visitUDivExpr(const SCEVUDivExpr *Expr) {
210 llvm_unreachable("SCEVUDivExpr not yet supported");
211}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000212
Tobias Grosser0695ee42013-09-17 03:30:31 +0000213__isl_give isl_pw_aff *
214SCEVAffinator::visitAddRecExpr(const SCEVAddRecExpr *Expr) {
215 assert(Expr->isAffine() && "Only affine AddRecurrences allowed");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000216
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.
239 ScalarEvolution &SE = *S->getSE();
240 const SCEV *ZeroStartExpr = SE.getAddRecExpr(
241 SE.getConstant(Expr->getStart()->getType(), 0),
242 Expr->getStepRecurrence(SE), Expr->getLoop(), SCEV::FlagAnyWrap);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000243
Tobias Grosser0695ee42013-09-17 03:30:31 +0000244 isl_pw_aff *ZeroStartResult = visit(ZeroStartExpr);
245 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000246
Tobias Grosser0695ee42013-09-17 03:30:31 +0000247 return isl_pw_aff_add(ZeroStartResult, Start);
248}
249
250__isl_give isl_pw_aff *SCEVAffinator::visitSMaxExpr(const SCEVSMaxExpr *Expr) {
251 isl_pw_aff *Max = visit(Expr->getOperand(0));
252
253 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
254 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
255 Max = isl_pw_aff_max(Max, NextOperand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000256 }
257
Tobias Grosser0695ee42013-09-17 03:30:31 +0000258 return Max;
259}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000260
Tobias Grosser0695ee42013-09-17 03:30:31 +0000261__isl_give isl_pw_aff *SCEVAffinator::visitUMaxExpr(const SCEVUMaxExpr *Expr) {
262 llvm_unreachable("SCEVUMaxExpr not yet supported");
263}
264
Johannes Doerfertb9d18882015-02-11 14:54:50 +0000265__isl_give isl_pw_aff *SCEVAffinator::visitSDivInstruction(Instruction *SDiv) {
266 assert(SDiv->getOpcode() == Instruction::SDiv && "Assumed SDiv instruction!");
267 auto *SE = S->getSE();
268
269 auto *Divisor = SDiv->getOperand(1);
270 auto *DivisorSCEV = SE->getSCEV(Divisor);
271 auto *DivisorPWA = visit(DivisorSCEV);
272 assert(isa<ConstantInt>(Divisor) &&
273 "SDiv is no parameter but has a non-constant RHS.");
274
275 auto *Dividend = SDiv->getOperand(0);
276 auto *DividendSCEV = SE->getSCEV(Dividend);
277 auto *DividendPWA = visit(DividendSCEV);
278 return isl_pw_aff_tdiv_q(DividendPWA, DivisorPWA);
279}
280
Tobias Grosser0695ee42013-09-17 03:30:31 +0000281__isl_give isl_pw_aff *SCEVAffinator::visitUnknown(const SCEVUnknown *Expr) {
Johannes Doerfertb9d18882015-02-11 14:54:50 +0000282 if (Instruction *I = dyn_cast<Instruction>(Expr->getValue())) {
283 switch (I->getOpcode()) {
284 case Instruction::SDiv:
285 return visitSDivInstruction(I);
286 default:
287 break; // Fall through.
288 }
289 }
290
291 llvm_unreachable(
292 "Unknowns SCEV was neither parameter nor a valid instruction.");
Tobias Grosser0695ee42013-09-17 03:30:31 +0000293}
294
295int SCEVAffinator::getLoopDepth(const Loop *L) {
296 Loop *outerLoop = S->getRegion().outermostLoopInRegion(const_cast<Loop *>(L));
297 assert(outerLoop && "Scop does not contain this loop");
298 return L->getLoopDepth() - outerLoop->getLoopDepth();
299}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000300
Johannes Doerferte7044942015-02-24 11:58:30 +0000301/// @brief Add the bounds of @p Range to the set @p S for dimension @p dim.
302static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
303 const ConstantRange &Range,
304 int dim,
305 enum isl_dim_type type) {
306 isl_val *V;
307 isl_ctx *ctx = isl_set_get_ctx(S);
308
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000309 bool isWrapping = Range.isSignWrappedSet();
310 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
311 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000312 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
313
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000314 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
315 V = isl_valFromAPInt(ctx, UB, true);
316 if (isWrapping)
317 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000318 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
319
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000320 if (isWrapping)
Johannes Doerferte7044942015-02-24 11:58:30 +0000321 return isl_set_union(SLB, SUB);
322 else
323 return isl_set_intersect(SLB, SUB);
324}
325
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000326ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *AccessType, isl_ctx *Ctx,
327 const SmallVector<const SCEV *, 4> &DimensionSizes)
328 : BasePtr(BasePtr), AccessType(AccessType), DimensionSizes(DimensionSizes) {
329 const std::string BasePtrName = getIslCompatibleName("MemRef_", BasePtr, "");
330 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
331}
332
333ScopArrayInfo::~ScopArrayInfo() { isl_id_free(Id); }
334
335isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
336
337void ScopArrayInfo::dump() const { print(errs()); }
338
339void ScopArrayInfo::print(raw_ostream &OS) const {
340 OS << "ScopArrayInfo:\n";
341 OS << " Base: " << *getBasePtr() << "\n";
342 OS << " Type: " << *getType() << "\n";
343 OS << " Dimension Sizes:\n";
344 for (unsigned u = 0; u < getNumberOfDimensions(); u++)
345 OS << " " << u << ") " << *DimensionSizes[u] << "\n";
346 OS << "\n";
347}
348
349const ScopArrayInfo *
350ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
351 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
352 assert(Id && "Output dimension didn't have an ID");
353 return getFromId(Id);
354}
355
356const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
357 void *User = isl_id_get_user(Id);
358 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
359 isl_id_free(Id);
360 return SAI;
361}
362
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000363const std::string
364MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
365 switch (RT) {
366 case MemoryAccess::RT_NONE:
367 llvm_unreachable("Requested a reduction operator string for a memory "
368 "access which isn't a reduction");
369 case MemoryAccess::RT_ADD:
370 return "+";
371 case MemoryAccess::RT_MUL:
372 return "*";
373 case MemoryAccess::RT_BOR:
374 return "|";
375 case MemoryAccess::RT_BXOR:
376 return "^";
377 case MemoryAccess::RT_BAND:
378 return "&";
379 }
380 llvm_unreachable("Unknown reduction type");
381 return "";
382}
383
Johannes Doerfertf6183392014-07-01 20:52:51 +0000384/// @brief Return the reduction type for a given binary operator
385static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
386 const Instruction *Load) {
387 if (!BinOp)
388 return MemoryAccess::RT_NONE;
389 switch (BinOp->getOpcode()) {
390 case Instruction::FAdd:
391 if (!BinOp->hasUnsafeAlgebra())
392 return MemoryAccess::RT_NONE;
393 // Fall through
394 case Instruction::Add:
395 return MemoryAccess::RT_ADD;
396 case Instruction::Or:
397 return MemoryAccess::RT_BOR;
398 case Instruction::Xor:
399 return MemoryAccess::RT_BXOR;
400 case Instruction::And:
401 return MemoryAccess::RT_BAND;
402 case Instruction::FMul:
403 if (!BinOp->hasUnsafeAlgebra())
404 return MemoryAccess::RT_NONE;
405 // Fall through
406 case Instruction::Mul:
407 if (DisableMultiplicativeReductions)
408 return MemoryAccess::RT_NONE;
409 return MemoryAccess::RT_MUL;
410 default:
411 return MemoryAccess::RT_NONE;
412 }
413}
Tobias Grosser75805372011-04-29 06:27:02 +0000414//===----------------------------------------------------------------------===//
415
416MemoryAccess::~MemoryAccess() {
Tobias Grosser54a86e62011-08-18 06:31:46 +0000417 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000418 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000419}
420
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000421static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
422 switch (Access.getType()) {
423 case IRAccess::READ:
424 return MemoryAccess::READ;
425 case IRAccess::MUST_WRITE:
426 return MemoryAccess::MUST_WRITE;
427 case IRAccess::MAY_WRITE:
428 return MemoryAccess::MAY_WRITE;
429 }
430 llvm_unreachable("Unknown IRAccess type!");
431}
432
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000433const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
434 isl_id *ArrayId = getArrayId();
435 void *User = isl_id_get_user(ArrayId);
436 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
437 isl_id_free(ArrayId);
438 return SAI;
439}
440
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000441__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000442 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
443}
444
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000445__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
446 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000447 isl_map *Schedule, *ScheduledAccRel;
448 isl_union_set *UDomain;
449
450 UDomain = isl_union_set_from_set(getStatement()->getDomain());
451 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
452 Schedule = isl_map_from_union_map(USchedule);
453 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
454 return isl_pw_multi_aff_from_map(ScheduledAccRel);
455}
456
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000457__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000458 return isl_map_copy(AccessRelation);
459}
460
Johannes Doerferta99130f2014-10-13 12:58:03 +0000461std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000462 return stringFromIslObj(AccessRelation);
463}
464
Johannes Doerferta99130f2014-10-13 12:58:03 +0000465__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000466 return isl_map_get_space(AccessRelation);
467}
468
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000469__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000470 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000471}
472
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000473__isl_give isl_basic_map *
474MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000475 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000476 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000477
Tobias Grosser084d8f72012-05-29 09:29:44 +0000478 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000479 isl_basic_set_universe(Statement->getDomainSpace()),
480 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000481}
482
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000483// Formalize no out-of-bound access assumption
484//
485// When delinearizing array accesses we optimistically assume that the
486// delinearized accesses do not access out of bound locations (the subscript
487// expression of each array evaluates for each statement instance that is
488// executed to a value that is larger than zero and strictly smaller than the
489// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000490// dimension for which we do not need to assume any upper bound. At this point
491// we formalize this assumption to ensure that at code generation time the
492// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000493//
494// To find the set of constraints necessary to avoid out of bound accesses, we
495// first build the set of data locations that are not within array bounds. We
496// then apply the reverse access relation to obtain the set of iterations that
497// may contain invalid accesses and reduce this set of iterations to the ones
498// that are actually executed by intersecting them with the domain of the
499// statement. If we now project out all loop dimensions, we obtain a set of
500// parameters that may cause statement instances to be executed that may
501// possibly yield out of bound memory accesses. The complement of these
502// constraints is the set of constraints that needs to be assumed to ensure such
503// statement instances are never executed.
504void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000505 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000506 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000507 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000508 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
509 isl_pw_aff *Var =
510 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
511 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
512
513 isl_set *DimOutside;
514
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000515 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
516 isl_pw_aff *SizeE = SCEVAffinator::getPwAff(Statement, Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000517
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000518 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
519 Statement->getNumIterators());
520 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
521 isl_space_dim(Space, isl_dim_set));
522 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
523 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000524
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000525 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000526
527 Outside = isl_set_union(Outside, DimOutside);
528 }
529
530 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
531 Outside = isl_set_intersect(Outside, Statement->getDomain());
532 Outside = isl_set_params(Outside);
533 Outside = isl_set_complement(Outside);
534 Statement->getParent()->addAssumption(Outside);
535 isl_space_free(Space);
536}
537
Johannes Doerferte7044942015-02-24 11:58:30 +0000538void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
539 ScalarEvolution *SE = Statement->getParent()->getSE();
540
541 Value *Ptr = getPointerOperand(*getAccessInstruction());
542 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
543 return;
544
545 auto *PtrSCEV = SE->getSCEV(Ptr);
546 if (isa<SCEVCouldNotCompute>(PtrSCEV))
547 return;
548
549 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
550 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
551 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
552
553 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
554 if (Range.isFullSet())
555 return;
556
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000557 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000558 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000559 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
560 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
561
562 auto Min = LB.sdiv(APInt(BW, ElementSize));
563 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000564
565 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
566 AccessRange =
567 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
568 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
569}
570
Tobias Grosser619190d2015-03-30 17:22:28 +0000571__isl_give isl_map *MemoryAccess::foldAccess(const IRAccess &Access,
572 __isl_take isl_map *AccessRelation,
573 ScopStmt *Statement) {
574 int Size = Access.Subscripts.size();
575
576 for (int i = Size - 2; i >= 0; --i) {
577 isl_space *Space;
578 isl_map *MapOne, *MapTwo;
579 isl_pw_aff *DimSize = SCEVAffinator::getPwAff(Statement, Access.Sizes[i]);
580
581 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
582 isl_pw_aff_free(DimSize);
583 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
584
585 Space = isl_map_get_space(AccessRelation);
586 Space = isl_space_map_from_set(isl_space_range(Space));
587 Space = isl_space_align_params(Space, SpaceSize);
588
589 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
590 isl_id_free(ParamId);
591
592 MapOne = isl_map_universe(isl_space_copy(Space));
593 for (int j = 0; j < Size; ++j)
594 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
595 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
596
597 MapTwo = isl_map_universe(isl_space_copy(Space));
598 for (int j = 0; j < Size; ++j)
599 if (j < i || j > i + 1)
600 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
601
602 isl_local_space *LS = isl_local_space_from_space(Space);
603 isl_constraint *C;
604 C = isl_equality_alloc(isl_local_space_copy(LS));
605 C = isl_constraint_set_constant_si(C, -1);
606 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
607 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
608 MapTwo = isl_map_add_constraint(MapTwo, C);
609 C = isl_equality_alloc(LS);
610 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
611 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
612 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
613 MapTwo = isl_map_add_constraint(MapTwo, C);
614 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
615
616 MapOne = isl_map_union(MapOne, MapTwo);
617 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
618 }
619 return AccessRelation;
620}
621
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000622MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000623 ScopStmt *Statement, const ScopArrayInfo *SAI)
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000624 : AccType(getMemoryAccessType(Access)), Statement(Statement), Inst(AccInst),
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000625 newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000626
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000627 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000628 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000629 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000630
631 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000632
Tobias Grossera1879642011-12-20 10:43:14 +0000633 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000634 // We overapproximate non-affine accesses with a possible access to the
635 // whole array. For read accesses it does not make a difference, if an
636 // access must or may happen. However, for write accesses it is important to
637 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000638 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000639 AccessRelation =
640 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000641
642 computeBoundsOnAccessRelation(Access.getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000643 return;
644 }
645
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000646 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000647 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000648
Tobias Grosser79baa212014-04-10 08:38:02 +0000649 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Sebastian Pop18016682014-04-08 21:20:44 +0000650 isl_pw_aff *Affine =
651 SCEVAffinator::getPwAff(Statement, Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000652
Sebastian Pop422e33f2014-06-03 18:16:31 +0000653 if (Size == 1) {
654 // For the non delinearized arrays, divide the access function of the last
655 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000656 //
657 // A stride one array access in C expressed as A[i] is expressed in
658 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
659 // two subsequent values of 'i' index two values that are stored next to
660 // each other in memory. By this division we make this characteristic
661 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000662 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000663 Affine = isl_pw_aff_scale_down_val(Affine, v);
664 }
665
666 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
667
Tobias Grosser79baa212014-04-10 08:38:02 +0000668 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000669 }
670
Tobias Grosser619190d2015-03-30 17:22:28 +0000671 AccessRelation = foldAccess(Access, AccessRelation, Statement);
672
Tobias Grosser79baa212014-04-10 08:38:02 +0000673 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000674 AccessRelation = isl_map_set_tuple_id(
675 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000676 AccessRelation =
677 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
678
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000679 assumeNoOutOfBound(Access);
Tobias Grosseraa660a92015-03-30 00:07:50 +0000680 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000681 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000682}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000683
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000684void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000685 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000686 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000687}
688
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000689const std::string MemoryAccess::getReductionOperatorStr() const {
690 return MemoryAccess::getReductionOperatorStr(getReductionType());
691}
692
Johannes Doerfertf6183392014-07-01 20:52:51 +0000693raw_ostream &polly::operator<<(raw_ostream &OS,
694 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000695 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000696 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000697 else
698 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000699 return OS;
700}
701
Tobias Grosser75805372011-04-29 06:27:02 +0000702void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000703 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000704 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000705 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000706 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000707 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000708 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000709 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000710 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000711 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000712 break;
713 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000714 OS << "[Reduction Type: " << getReductionType() << "] ";
715 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000716 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000717}
718
Tobias Grosser74394f02013-01-14 22:40:23 +0000719void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000720
721// Create a map in the size of the provided set domain, that maps from the
722// one element of the provided set domain to another element of the provided
723// set domain.
724// The mapping is limited to all points that are equal in all but the last
725// dimension and for which the last dimension of the input is strict smaller
726// than the last dimension of the output.
727//
728// getEqualAndLarger(set[i0, i1, ..., iX]):
729//
730// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
731// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
732//
Tobias Grosserf5338802011-10-06 00:03:35 +0000733static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000734 isl_space *Space = isl_space_map_from_set(setDomain);
735 isl_map *Map = isl_map_universe(isl_space_copy(Space));
736 isl_local_space *MapLocalSpace = isl_local_space_from_space(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000737 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000738
739 // Set all but the last dimension to be equal for the input and output
740 //
741 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
742 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000743 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000744 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000745
746 // Set the last dimension of the input to be strict smaller than the
747 // last dimension of the output.
748 //
749 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
750 //
Tobias Grosseredab1352013-06-21 06:41:31 +0000751 isl_val *v;
752 isl_ctx *Ctx = isl_map_get_ctx(Map);
Tobias Grosserf5338802011-10-06 00:03:35 +0000753 isl_constraint *c = isl_inequality_alloc(isl_local_space_copy(MapLocalSpace));
Tobias Grosseredab1352013-06-21 06:41:31 +0000754 v = isl_val_int_from_si(Ctx, -1);
755 c = isl_constraint_set_coefficient_val(c, isl_dim_in, lastDimension, v);
756 v = isl_val_int_from_si(Ctx, 1);
757 c = isl_constraint_set_coefficient_val(c, isl_dim_out, lastDimension, v);
758 v = isl_val_int_from_si(Ctx, -1);
759 c = isl_constraint_set_constant_val(c, v);
Tobias Grosser75805372011-04-29 06:27:02 +0000760
Tobias Grosserc327932c2012-02-01 14:23:36 +0000761 Map = isl_map_add_constraint(Map, c);
Tobias Grosser75805372011-04-29 06:27:02 +0000762
Tobias Grosser23b36662011-10-17 08:32:36 +0000763 isl_local_space_free(MapLocalSpace);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000764 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000765}
766
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000767__isl_give isl_set *
768MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000769 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000770 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000771 isl_space *Space = isl_space_range(isl_map_get_space(S));
772 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000773
Sebastian Popa00a0292012-12-18 07:46:06 +0000774 S = isl_map_reverse(S);
775 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000776
Sebastian Popa00a0292012-12-18 07:46:06 +0000777 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
778 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
779 NextScatt = isl_map_apply_domain(NextScatt, S);
780 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000781
Sebastian Popa00a0292012-12-18 07:46:06 +0000782 isl_set *Deltas = isl_map_deltas(NextScatt);
783 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000784}
785
Sebastian Popa00a0292012-12-18 07:46:06 +0000786bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000787 int StrideWidth) const {
788 isl_set *Stride, *StrideX;
789 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000790
Sebastian Popa00a0292012-12-18 07:46:06 +0000791 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000792 StrideX = isl_set_universe(isl_set_get_space(Stride));
793 StrideX = isl_set_fix_si(StrideX, isl_dim_set, 0, StrideWidth);
794 IsStrideX = isl_set_is_equal(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000795
Tobias Grosser28dd4862012-01-24 16:42:16 +0000796 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000797 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000798
Tobias Grosser28dd4862012-01-24 16:42:16 +0000799 return IsStrideX;
800}
801
Sebastian Popa00a0292012-12-18 07:46:06 +0000802bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
803 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000804}
805
Tobias Grosser79baa212014-04-10 08:38:02 +0000806bool MemoryAccess::isScalar() const {
807 return isl_map_n_out(AccessRelation) == 0;
808}
809
Sebastian Popa00a0292012-12-18 07:46:06 +0000810bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
811 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000812}
813
Tobias Grosser5d453812011-10-06 00:04:11 +0000814void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000815 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000816 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000817}
Tobias Grosser75805372011-04-29 06:27:02 +0000818
819//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000820
Tobias Grosser54839312015-04-21 11:37:25 +0000821isl_map *ScopStmt::getSchedule() const { return isl_map_copy(Schedule); }
Tobias Grossercf3942d2011-10-06 00:04:05 +0000822
Tobias Grosser37eb4222014-02-20 21:43:54 +0000823void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
824 assert(isl_set_is_subset(NewDomain, Domain) &&
825 "New domain is not a subset of old domain!");
826 isl_set_free(Domain);
827 Domain = NewDomain;
Tobias Grosser54839312015-04-21 11:37:25 +0000828 Schedule = isl_map_intersect_domain(Schedule, isl_set_copy(Domain));
Tobias Grosser37eb4222014-02-20 21:43:54 +0000829}
830
Tobias Grosser54839312015-04-21 11:37:25 +0000831void ScopStmt::setSchedule(__isl_take isl_map *NewSchedule) {
832 assert(NewSchedule && "New schedule is nullptr");
833 isl_map_free(Schedule);
834 Schedule = NewSchedule;
Tobias Grosserb76f38532011-08-20 11:11:25 +0000835}
836
Tobias Grosser54839312015-04-21 11:37:25 +0000837void ScopStmt::buildSchedule(SmallVectorImpl<unsigned> &ScheduleVec) {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000838 unsigned NbIterators = getNumIterators();
Tobias Grosser54839312015-04-21 11:37:25 +0000839 unsigned NbScheduleDims = Parent.getMaxLoopDepth() * 2 + 1;
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000840
Tobias Grosser54839312015-04-21 11:37:25 +0000841 isl_space *Space = isl_space_set_alloc(getIslCtx(), 0, NbScheduleDims);
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000842
Tobias Grosser54839312015-04-21 11:37:25 +0000843 Schedule = isl_map_from_domain_and_range(isl_set_universe(getDomainSpace()),
Tobias Grosser654af8f2015-04-21 11:42:01 +0000844 isl_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000845
846 // Loop dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000847 for (unsigned i = 0; i < NbIterators; ++i)
Tobias Grosser654af8f2015-04-21 11:42:01 +0000848 Schedule = isl_map_equate(Schedule, isl_dim_out, 2 * i + 1, isl_dim_in, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000849
850 // Constant dimensions
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000851 for (unsigned i = 0; i < NbIterators + 1; ++i)
Tobias Grosser54839312015-04-21 11:37:25 +0000852 Schedule = isl_map_fix_si(Schedule, isl_dim_out, 2 * i, ScheduleVec[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000853
Tobias Grosser54839312015-04-21 11:37:25 +0000854 // Fill schedule dimensions.
855 for (unsigned i = 2 * NbIterators + 1; i < NbScheduleDims; ++i)
856 Schedule = isl_map_fix_si(Schedule, isl_dim_out, i, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000857
Tobias Grosser54839312015-04-21 11:37:25 +0000858 Schedule = isl_map_align_params(Schedule, Parent.getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000859}
860
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000861void ScopStmt::buildAccesses(TempScop &tempScop, BasicBlock *Block,
862 bool isApproximated) {
863 AccFuncSetType *AFS = tempScop.getAccessFunctions(Block);
864 if (!AFS)
865 return;
866
867 for (auto &AccessPair : *AFS) {
868 IRAccess &Access = AccessPair.first;
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000869 Instruction *AccessInst = AccessPair.second;
870
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000871 Type *AccessType = getAccessInstType(AccessInst)->getPointerTo();
872 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
873 Access.getBase(), AccessType, Access.Sizes);
874
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000875 if (isApproximated && Access.isWrite())
876 Access.setMayWrite();
877
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000878 MemAccs.push_back(new MemoryAccess(Access, AccessInst, this, SAI));
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000879
880 // We do not track locations for scalar memory accesses at the moment.
881 //
882 // We do not have a use for this information at the moment. If we need this
883 // at some point, the "instruction -> access" mapping needs to be enhanced
884 // as a single instruction could then possibly perform multiple accesses.
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000885 if (!Access.isScalar()) {
886 assert(!InstructionToAccess.count(AccessInst) &&
Tobias Grosser3fc91542014-02-20 21:43:45 +0000887 "Unexpected 1-to-N mapping on instruction to access map!");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000888 InstructionToAccess[AccessInst] = MemAccs.back();
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000889 }
Tobias Grosser75805372011-04-29 06:27:02 +0000890 }
891}
892
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000893void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000894 for (MemoryAccess *MA : *this)
895 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000896
897 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser54839312015-04-21 11:37:25 +0000898 Schedule = isl_map_align_params(Schedule, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000899}
900
Tobias Grosser65b00582011-11-08 15:41:19 +0000901__isl_give isl_set *ScopStmt::buildConditionSet(const Comparison &Comp) {
Tobias Grossera601fbd2011-11-09 22:34:44 +0000902 isl_pw_aff *L = SCEVAffinator::getPwAff(this, Comp.getLHS());
903 isl_pw_aff *R = SCEVAffinator::getPwAff(this, Comp.getRHS());
Tobias Grosser75805372011-04-29 06:27:02 +0000904
Tobias Grosserd2795d02011-08-18 07:51:40 +0000905 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000906 case ICmpInst::ICMP_EQ:
Tobias Grosser048c8792011-10-23 20:59:20 +0000907 return isl_pw_aff_eq_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000908 case ICmpInst::ICMP_NE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000909 return isl_pw_aff_ne_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000910 case ICmpInst::ICMP_SLT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000911 return isl_pw_aff_lt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000912 case ICmpInst::ICMP_SLE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000913 return isl_pw_aff_le_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000914 case ICmpInst::ICMP_SGT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000915 return isl_pw_aff_gt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000916 case ICmpInst::ICMP_SGE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000917 return isl_pw_aff_ge_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000918 case ICmpInst::ICMP_ULT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000919 return isl_pw_aff_lt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000920 case ICmpInst::ICMP_UGT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000921 return isl_pw_aff_gt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000922 case ICmpInst::ICMP_ULE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000923 return isl_pw_aff_le_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000924 case ICmpInst::ICMP_UGE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000925 return isl_pw_aff_ge_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000926 default:
927 llvm_unreachable("Non integer predicate not supported");
928 }
Tobias Grosser75805372011-04-29 06:27:02 +0000929}
930
Tobias Grossere19661e2011-10-07 08:46:57 +0000931__isl_give isl_set *ScopStmt::addLoopBoundsToDomain(__isl_take isl_set *Domain,
Tobias Grosser60b54f12011-11-08 15:41:28 +0000932 TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000933 isl_space *Space;
934 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000935
Tobias Grossere19661e2011-10-07 08:46:57 +0000936 Space = isl_set_get_space(Domain);
937 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000938
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000939 ScalarEvolution *SE = getParent()->getSE();
Tobias Grosser75805372011-04-29 06:27:02 +0000940 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000941 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000942 isl_pw_aff *IV =
943 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000944
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000945 // 0 <= IV.
946 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
947 Domain = isl_set_intersect(Domain, LowerBound);
948
949 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000950 const Loop *L = getLoopForDimension(i);
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000951 const SCEV *LatchExecutions = SE->getBackedgeTakenCount(L);
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000952 isl_pw_aff *UpperBound = SCEVAffinator::getPwAff(this, LatchExecutions);
953 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
Tobias Grosser75805372011-04-29 06:27:02 +0000954 Domain = isl_set_intersect(Domain, UpperBoundSet);
955 }
956
Tobias Grosserf5338802011-10-06 00:03:35 +0000957 isl_local_space_free(LocalSpace);
Tobias Grossere19661e2011-10-07 08:46:57 +0000958 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000959}
960
Tobias Grossere602a072013-05-07 07:30:56 +0000961__isl_give isl_set *ScopStmt::addConditionsToDomain(__isl_take isl_set *Domain,
962 TempScop &tempScop,
963 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000964 const Region *TopRegion = tempScop.getMaxRegion().getParent(),
Tobias Grosserd7e58642013-04-10 06:55:45 +0000965 *CurrentRegion = &CurRegion;
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000966 const BasicBlock *BranchingBB = BB ? BB : R->getEntry();
Tobias Grosser75805372011-04-29 06:27:02 +0000967
Tobias Grosser75805372011-04-29 06:27:02 +0000968 do {
Tobias Grossere19661e2011-10-07 08:46:57 +0000969 if (BranchingBB != CurrentRegion->getEntry()) {
970 if (const BBCond *Condition = tempScop.getBBCond(BranchingBB))
Tobias Grosser083d3d32014-06-28 08:59:45 +0000971 for (const auto &C : *Condition) {
972 isl_set *ConditionSet = buildConditionSet(C);
Tobias Grossere19661e2011-10-07 08:46:57 +0000973 Domain = isl_set_intersect(Domain, ConditionSet);
Tobias Grosser75805372011-04-29 06:27:02 +0000974 }
975 }
Tobias Grossere19661e2011-10-07 08:46:57 +0000976 BranchingBB = CurrentRegion->getEntry();
977 CurrentRegion = CurrentRegion->getParent();
978 } while (TopRegion != CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000979
Tobias Grossere19661e2011-10-07 08:46:57 +0000980 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000981}
982
Tobias Grossere602a072013-05-07 07:30:56 +0000983__isl_give isl_set *ScopStmt::buildDomain(TempScop &tempScop,
984 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000985 isl_space *Space;
986 isl_set *Domain;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000987 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000988
989 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
990
Tobias Grosser084d8f72012-05-29 09:29:44 +0000991 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
992
Tobias Grossere19661e2011-10-07 08:46:57 +0000993 Domain = isl_set_universe(Space);
Tobias Grossere19661e2011-10-07 08:46:57 +0000994 Domain = addLoopBoundsToDomain(Domain, tempScop);
995 Domain = addConditionsToDomain(Domain, tempScop, CurRegion);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000996 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grossere19661e2011-10-07 08:46:57 +0000997
998 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000999}
1000
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001001void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
1002 int Dimension = 0;
1003 isl_ctx *Ctx = Parent.getIslCtx();
1004 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1005 Type *Ty = GEP->getPointerOperandType();
1006 ScalarEvolution &SE = *Parent.getSE();
1007
1008 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
1009 Dimension = 1;
1010 Ty = PtrTy->getElementType();
1011 }
1012
1013 while (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
1014 unsigned int Operand = 1 + Dimension;
1015
1016 if (GEP->getNumOperands() <= Operand)
1017 break;
1018
1019 const SCEV *Expr = SE.getSCEV(GEP->getOperand(Operand));
1020
1021 if (isAffineExpr(&Parent.getRegion(), Expr, SE)) {
1022 isl_pw_aff *AccessOffset = SCEVAffinator::getPwAff(this, Expr);
1023 AccessOffset =
1024 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
1025
1026 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1027 isl_local_space_copy(LSpace),
1028 isl_val_int_from_si(Ctx, ArrayTy->getNumElements())));
1029
1030 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1031 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1032 OutOfBound = isl_set_params(OutOfBound);
1033 isl_set *InBound = isl_set_complement(OutOfBound);
1034 isl_set *Executed = isl_set_params(getDomain());
1035
1036 // A => B == !A or B
1037 isl_set *InBoundIfExecuted =
1038 isl_set_union(isl_set_complement(Executed), InBound);
1039
1040 Parent.addAssumption(InBoundIfExecuted);
1041 }
1042
1043 Dimension += 1;
1044 Ty = ArrayTy->getElementType();
1045 }
1046
1047 isl_local_space_free(LSpace);
1048}
1049
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001050void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1051 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001052 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1053 deriveAssumptionsFromGEP(GEP);
1054}
1055
Tobias Grosser74394f02013-01-14 22:40:23 +00001056ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001057 Region &R, SmallVectorImpl<Loop *> &Nest,
Tobias Grosser54839312015-04-21 11:37:25 +00001058 SmallVectorImpl<unsigned> &ScheduleVec)
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001059 : Parent(parent), BB(nullptr), R(&R), Build(nullptr),
1060 NestLoops(Nest.size()) {
1061 // Setup the induction variables.
1062 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
1063 NestLoops[i] = Nest[i];
1064
1065 BaseName = getIslCompatibleName("Stmt_(", R.getNameStr(), ")");
1066
1067 Domain = buildDomain(tempScop, CurRegion);
Tobias Grosser54839312015-04-21 11:37:25 +00001068 buildSchedule(ScheduleVec);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001069
1070 BasicBlock *EntryBB = R.getEntry();
1071 for (BasicBlock *Block : R.blocks()) {
1072 buildAccesses(tempScop, Block, Block != EntryBB);
1073 deriveAssumptions(Block);
1074 }
1075 checkForReductions();
1076}
1077
1078ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Sebastian Pop860e0212013-02-15 21:26:44 +00001079 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest,
Tobias Grosser54839312015-04-21 11:37:25 +00001080 SmallVectorImpl<unsigned> &ScheduleVec)
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001081 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr),
1082 NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +00001083 // Setup the induction variables.
Tobias Grosser683b8e42014-11-30 14:33:31 +00001084 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
Sebastian Pop860e0212013-02-15 21:26:44 +00001085 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +00001086
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001087 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +00001088
Tobias Grossere19661e2011-10-07 08:46:57 +00001089 Domain = buildDomain(tempScop, CurRegion);
Tobias Grosser54839312015-04-21 11:37:25 +00001090 buildSchedule(ScheduleVec);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001091 buildAccesses(tempScop, BB);
1092 deriveAssumptions(BB);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001093 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001094}
1095
Johannes Doerferte58a0122014-06-27 20:31:28 +00001096/// @brief Collect loads which might form a reduction chain with @p StoreMA
1097///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001098/// Check if the stored value for @p StoreMA is a binary operator with one or
1099/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001100/// used only once (by @p StoreMA) and its load operands are also used only
1101/// once, we have found a possible reduction chain. It starts at an operand
1102/// load and includes the binary operator and @p StoreMA.
1103///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001104/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001105/// escape this block or into any other store except @p StoreMA.
1106void ScopStmt::collectCandiateReductionLoads(
1107 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1108 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1109 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001110 return;
1111
1112 // Skip if there is not one binary operator between the load and the store
1113 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001114 if (!BinOp)
1115 return;
1116
1117 // Skip if the binary operators has multiple uses
1118 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001119 return;
1120
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001121 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001122 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1123 return;
1124
Johannes Doerfert9890a052014-07-01 00:32:29 +00001125 // Skip if the binary operator is outside the current SCoP
1126 if (BinOp->getParent() != Store->getParent())
1127 return;
1128
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001129 // Skip if it is a multiplicative reduction and we disabled them
1130 if (DisableMultiplicativeReductions &&
1131 (BinOp->getOpcode() == Instruction::Mul ||
1132 BinOp->getOpcode() == Instruction::FMul))
1133 return;
1134
Johannes Doerferte58a0122014-06-27 20:31:28 +00001135 // Check the binary operator operands for a candidate load
1136 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1137 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1138 if (!PossibleLoad0 && !PossibleLoad1)
1139 return;
1140
1141 // A load is only a candidate if it cannot escape (thus has only this use)
1142 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001143 if (PossibleLoad0->getParent() == Store->getParent())
1144 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001145 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001146 if (PossibleLoad1->getParent() == Store->getParent())
1147 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001148}
1149
1150/// @brief Check for reductions in this ScopStmt
1151///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001152/// Iterate over all store memory accesses and check for valid binary reduction
1153/// like chains. For all candidates we check if they have the same base address
1154/// and there are no other accesses which overlap with them. The base address
1155/// check rules out impossible reductions candidates early. The overlap check,
1156/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001157/// guarantees that none of the intermediate results will escape during
1158/// execution of the loop nest. We basically check here that no other memory
1159/// access can access the same memory as the potential reduction.
1160void ScopStmt::checkForReductions() {
1161 SmallVector<MemoryAccess *, 2> Loads;
1162 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1163
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001164 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001165 // stores and collecting possible reduction loads.
1166 for (MemoryAccess *StoreMA : MemAccs) {
1167 if (StoreMA->isRead())
1168 continue;
1169
1170 Loads.clear();
1171 collectCandiateReductionLoads(StoreMA, Loads);
1172 for (MemoryAccess *LoadMA : Loads)
1173 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1174 }
1175
1176 // Then check each possible candidate pair.
1177 for (const auto &CandidatePair : Candidates) {
1178 bool Valid = true;
1179 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1180 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1181
1182 // Skip those with obviously unequal base addresses.
1183 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1184 isl_map_free(LoadAccs);
1185 isl_map_free(StoreAccs);
1186 continue;
1187 }
1188
1189 // And check if the remaining for overlap with other memory accesses.
1190 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1191 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1192 isl_set *AllAccs = isl_map_range(AllAccsRel);
1193
1194 for (MemoryAccess *MA : MemAccs) {
1195 if (MA == CandidatePair.first || MA == CandidatePair.second)
1196 continue;
1197
1198 isl_map *AccRel =
1199 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1200 isl_set *Accs = isl_map_range(AccRel);
1201
1202 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1203 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1204 Valid = Valid && isl_set_is_empty(OverlapAccs);
1205 isl_set_free(OverlapAccs);
1206 }
1207 }
1208
1209 isl_set_free(AllAccs);
1210 if (!Valid)
1211 continue;
1212
Johannes Doerfertf6183392014-07-01 20:52:51 +00001213 const LoadInst *Load =
1214 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1215 MemoryAccess::ReductionType RT =
1216 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1217
Johannes Doerferte58a0122014-06-27 20:31:28 +00001218 // If no overlapping access was found we mark the load and store as
1219 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001220 CandidatePair.first->markAsReductionLike(RT);
1221 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001222 }
Tobias Grosser75805372011-04-29 06:27:02 +00001223}
1224
Tobias Grosser74394f02013-01-14 22:40:23 +00001225std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001226
Tobias Grosser54839312015-04-21 11:37:25 +00001227std::string ScopStmt::getScheduleStr() const {
1228 return stringFromIslObj(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00001229}
1230
Tobias Grosser74394f02013-01-14 22:40:23 +00001231unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001232
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001233unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001234
Tobias Grosser54839312015-04-21 11:37:25 +00001235unsigned ScopStmt::getNumSchedule() const {
1236 return isl_map_dim(Schedule, isl_dim_out);
Tobias Grosser75805372011-04-29 06:27:02 +00001237}
1238
1239const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1240
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001241const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001242 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001243}
1244
Tobias Grosser74394f02013-01-14 22:40:23 +00001245isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001246
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001247__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001248
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001249__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001250 return isl_set_get_space(Domain);
1251}
1252
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001253__isl_give isl_id *ScopStmt::getDomainId() const {
1254 return isl_set_get_tuple_id(Domain);
1255}
Tobias Grossercd95b772012-08-30 11:49:38 +00001256
Tobias Grosser75805372011-04-29 06:27:02 +00001257ScopStmt::~ScopStmt() {
1258 while (!MemAccs.empty()) {
1259 delete MemAccs.back();
1260 MemAccs.pop_back();
1261 }
1262
1263 isl_set_free(Domain);
Tobias Grosser54839312015-04-21 11:37:25 +00001264 isl_map_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00001265}
1266
1267void ScopStmt::print(raw_ostream &OS) const {
1268 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001269 OS.indent(12) << "Domain :=\n";
1270
1271 if (Domain) {
1272 OS.indent(16) << getDomainStr() << ";\n";
1273 } else
1274 OS.indent(16) << "n/a\n";
1275
Tobias Grosser54839312015-04-21 11:37:25 +00001276 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001277
1278 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001279 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001280 } else
1281 OS.indent(16) << "n/a\n";
1282
Tobias Grosser083d3d32014-06-28 08:59:45 +00001283 for (MemoryAccess *Access : MemAccs)
1284 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001285}
1286
1287void ScopStmt::dump() const { print(dbgs()); }
1288
1289//===----------------------------------------------------------------------===//
1290/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001291
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001292void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001293 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1294 isl_set_free(Context);
1295 Context = NewContext;
1296}
1297
Tobias Grosserabfbe632013-02-05 12:09:06 +00001298void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001299 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001300 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001301 if (ParameterIds.find(Parameter) != ParameterIds.end())
1302 continue;
1303
1304 int dimension = Parameters.size();
1305
1306 Parameters.push_back(Parameter);
1307 ParameterIds[Parameter] = dimension;
1308 }
1309}
1310
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001311__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1312 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001313
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001314 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001315 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001316
Tobias Grosser8f99c162011-11-15 11:38:55 +00001317 std::string ParameterName;
1318
1319 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1320 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001321 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001322 }
1323
1324 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001325 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001326
Tobias Grosser20532b82014-04-11 17:56:49 +00001327 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1328 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001329}
Tobias Grosser75805372011-04-29 06:27:02 +00001330
Tobias Grosser6be480c2011-11-08 15:41:13 +00001331void Scop::buildContext() {
1332 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001333 Context = isl_set_universe(isl_space_copy(Space));
1334 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001335}
1336
Tobias Grosser18daaca2012-05-22 10:47:27 +00001337void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001338 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001339 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001340
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001341 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001342
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001343 // TODO: Find a case where the full set is actually helpful.
1344 if (SRange.isFullSet())
Tobias Grosser55bc4c02015-01-08 19:26:53 +00001345 continue;
1346
Johannes Doerferte7044942015-02-24 11:58:30 +00001347 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001348 }
1349}
1350
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001351void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001352 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001353 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001354
Tobias Grosser083d3d32014-06-28 08:59:45 +00001355 for (const auto &ParamID : ParameterIds) {
1356 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001357 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001358 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001359 }
1360
1361 // Align the parameters of all data structures to the model.
1362 Context = isl_set_align_params(Context, Space);
1363
Tobias Grosser083d3d32014-06-28 08:59:45 +00001364 for (ScopStmt *Stmt : *this)
1365 Stmt->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001366}
1367
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001368void Scop::simplifyAssumedContext() {
1369 // The parameter constraints of the iteration domains give us a set of
1370 // constraints that need to hold for all cases where at least a single
1371 // statement iteration is executed in the whole scop. We now simplify the
1372 // assumed context under the assumption that such constraints hold and at
1373 // least a single statement iteration is executed. For cases where no
1374 // statement instances are executed, the assumptions we have taken about
1375 // the executed code do not matter and can be changed.
1376 //
1377 // WARNING: This only holds if the assumptions we have taken do not reduce
1378 // the set of statement instances that are executed. Otherwise we
1379 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001380 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001381 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001382 // performed. In such a case, modifying the run-time conditions and
1383 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001384 // to not be executed.
1385 //
1386 // Example:
1387 //
1388 // When delinearizing the following code:
1389 //
1390 // for (long i = 0; i < 100; i++)
1391 // for (long j = 0; j < m; j++)
1392 // A[i+p][j] = 1.0;
1393 //
1394 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001395 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001396 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1397 AssumedContext =
1398 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001399 AssumedContext = isl_set_gist_params(AssumedContext, getContext());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001400}
1401
Johannes Doerfertb164c792014-09-18 11:17:17 +00001402/// @brief Add the minimal/maximal access in @p Set to @p User.
1403static int buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
1404 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1405 isl_pw_multi_aff *MinPMA, *MaxPMA;
1406 isl_pw_aff *LastDimAff;
1407 isl_aff *OneAff;
1408 unsigned Pos;
1409
Johannes Doerfert9143d672014-09-27 11:02:39 +00001410 // Restrict the number of parameters involved in the access as the lexmin/
1411 // lexmax computation will take too long if this number is high.
1412 //
1413 // Experiments with a simple test case using an i7 4800MQ:
1414 //
1415 // #Parameters involved | Time (in sec)
1416 // 6 | 0.01
1417 // 7 | 0.04
1418 // 8 | 0.12
1419 // 9 | 0.40
1420 // 10 | 1.54
1421 // 11 | 6.78
1422 // 12 | 30.38
1423 //
1424 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1425 unsigned InvolvedParams = 0;
1426 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1427 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1428 InvolvedParams++;
1429
1430 if (InvolvedParams > RunTimeChecksMaxParameters) {
1431 isl_set_free(Set);
1432 return -1;
1433 }
1434 }
1435
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001436 Set = isl_set_remove_divs(Set);
1437
Johannes Doerfertb164c792014-09-18 11:17:17 +00001438 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1439 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1440
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001441 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1442 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1443
Johannes Doerfertb164c792014-09-18 11:17:17 +00001444 // Adjust the last dimension of the maximal access by one as we want to
1445 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1446 // we test during code generation might now point after the end of the
1447 // allocated array but we will never dereference it anyway.
1448 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1449 "Assumed at least one output dimension");
1450 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1451 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1452 OneAff = isl_aff_zero_on_domain(
1453 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1454 OneAff = isl_aff_add_constant_si(OneAff, 1);
1455 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1456 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1457
1458 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1459
1460 isl_set_free(Set);
1461 return 0;
1462}
1463
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001464static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1465 isl_set *Domain = MA->getStatement()->getDomain();
1466 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1467 return isl_set_reset_tuple_id(Domain);
1468}
1469
Johannes Doerfert9143d672014-09-27 11:02:39 +00001470bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001471 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001472 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001473 // for all memory accesses inside the SCoP.
1474 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001475 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001476 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001477 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001478 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001479 // if their access domains intersect, otherwise they are in different
1480 // ones.
Johannes Doerfert13771732014-10-01 12:40:46 +00001481 // o) We split groups such that they contain at most one read only base
1482 // address.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001483 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfertb164c792014-09-18 11:17:17 +00001484 // and maximal accesses to each array in this group.
1485 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1486
1487 AliasSetTracker AST(AA);
1488
1489 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001490 DenseSet<Value *> HasWriteAccess;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001491 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001492
1493 // Skip statements with an empty domain as they will never be executed.
1494 isl_set *StmtDomain = Stmt->getDomain();
1495 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1496 isl_set_free(StmtDomain);
1497 if (StmtDomainEmpty)
1498 continue;
1499
Johannes Doerfertb164c792014-09-18 11:17:17 +00001500 for (MemoryAccess *MA : *Stmt) {
1501 if (MA->isScalar())
1502 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001503 if (!MA->isRead())
1504 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001505 Instruction *Acc = MA->getAccessInstruction();
1506 PtrToAcc[getPointerOperand(*Acc)] = MA;
1507 AST.add(Acc);
1508 }
1509 }
1510
1511 SmallVector<AliasGroupTy, 4> AliasGroups;
1512 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001513 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001514 continue;
1515 AliasGroupTy AG;
1516 for (auto PR : AS)
1517 AG.push_back(PtrToAcc[PR.getValue()]);
1518 assert(AG.size() > 1 &&
1519 "Alias groups should contain at least two accesses");
1520 AliasGroups.push_back(std::move(AG));
1521 }
1522
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001523 // Split the alias groups based on their domain.
1524 for (unsigned u = 0; u < AliasGroups.size(); u++) {
1525 AliasGroupTy NewAG;
1526 AliasGroupTy &AG = AliasGroups[u];
1527 AliasGroupTy::iterator AGI = AG.begin();
1528 isl_set *AGDomain = getAccessDomain(*AGI);
1529 while (AGI != AG.end()) {
1530 MemoryAccess *MA = *AGI;
1531 isl_set *MADomain = getAccessDomain(MA);
1532 if (isl_set_is_disjoint(AGDomain, MADomain)) {
1533 NewAG.push_back(MA);
1534 AGI = AG.erase(AGI);
1535 isl_set_free(MADomain);
1536 } else {
1537 AGDomain = isl_set_union(AGDomain, MADomain);
1538 AGI++;
1539 }
1540 }
1541 if (NewAG.size() > 1)
1542 AliasGroups.push_back(std::move(NewAG));
1543 isl_set_free(AGDomain);
1544 }
1545
Tobias Grosserf4c24b22015-04-05 13:11:54 +00001546 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00001547 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
1548 for (AliasGroupTy &AG : AliasGroups) {
1549 NonReadOnlyBaseValues.clear();
1550 ReadOnlyPairs.clear();
1551
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001552 if (AG.size() < 2) {
1553 AG.clear();
1554 continue;
1555 }
1556
Johannes Doerfert13771732014-10-01 12:40:46 +00001557 for (auto II = AG.begin(); II != AG.end();) {
1558 Value *BaseAddr = (*II)->getBaseAddr();
1559 if (HasWriteAccess.count(BaseAddr)) {
1560 NonReadOnlyBaseValues.insert(BaseAddr);
1561 II++;
1562 } else {
1563 ReadOnlyPairs[BaseAddr].insert(*II);
1564 II = AG.erase(II);
1565 }
1566 }
1567
1568 // If we don't have read only pointers check if there are at least two
1569 // non read only pointers, otherwise clear the alias group.
1570 if (ReadOnlyPairs.empty()) {
1571 if (NonReadOnlyBaseValues.size() <= 1)
1572 AG.clear();
1573 continue;
1574 }
1575
1576 // If we don't have non read only pointers clear the alias group.
1577 if (NonReadOnlyBaseValues.empty()) {
1578 AG.clear();
1579 continue;
1580 }
1581
1582 // If we have both read only and non read only base pointers we combine
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001583 // the non read only ones with exactly one read only one at a time into a
Johannes Doerfert13771732014-10-01 12:40:46 +00001584 // new alias group and clear the old alias group in the end.
1585 for (const auto &ReadOnlyPair : ReadOnlyPairs) {
1586 AliasGroupTy AGNonReadOnly = AG;
1587 for (MemoryAccess *MA : ReadOnlyPair.second)
1588 AGNonReadOnly.push_back(MA);
1589 AliasGroups.push_back(std::move(AGNonReadOnly));
1590 }
1591 AG.clear();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001592 }
1593
1594 for (AliasGroupTy &AG : AliasGroups) {
Johannes Doerfert13771732014-10-01 12:40:46 +00001595 if (AG.empty())
1596 continue;
1597
Johannes Doerfertb164c792014-09-18 11:17:17 +00001598 MinMaxVectorTy *MinMaxAccesses = new MinMaxVectorTy();
1599 MinMaxAccesses->reserve(AG.size());
1600
1601 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
1602 for (MemoryAccess *MA : AG)
1603 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
1604 Accesses = isl_union_map_intersect_domain(Accesses, getDomains());
1605
1606 isl_union_set *Locations = isl_union_map_range(Accesses);
1607 Locations = isl_union_set_intersect_params(Locations, getAssumedContext());
1608 Locations = isl_union_set_coalesce(Locations);
1609 Locations = isl_union_set_detect_equalities(Locations);
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001610 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
1611 MinMaxAccesses));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001612 isl_union_set_free(Locations);
Johannes Doerfertb164c792014-09-18 11:17:17 +00001613 MinMaxAliasGroups.push_back(MinMaxAccesses);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001614
1615 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001616 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001617 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001618
Tobias Grosser71500722015-03-28 15:11:14 +00001619 // Bail out if the number of values we need to compare is too large.
1620 // This is important as the number of comparisions grows quadratically with
1621 // the number of values we need to compare.
1622 for (const auto *Values : MinMaxAliasGroups)
1623 if (Values->size() > RunTimeChecksMaxArraysPerGroup)
1624 return false;
1625
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001626 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001627}
1628
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001629static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
1630 ScopDetection &SD) {
1631
1632 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
1633
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001634 unsigned MinLD = INT_MAX, MaxLD = 0;
1635 for (BasicBlock *BB : R.blocks()) {
1636 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00001637 if (!R.contains(L))
1638 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001639 if (BoxedLoops && BoxedLoops->count(L))
1640 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001641 unsigned LD = L->getLoopDepth();
1642 MinLD = std::min(MinLD, LD);
1643 MaxLD = std::max(MaxLD, LD);
1644 }
1645 }
1646
1647 // Handle the case that there is no loop in the SCoP first.
1648 if (MaxLD == 0)
1649 return 1;
1650
1651 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
1652 assert(MaxLD >= MinLD &&
1653 "Maximal loop depth was smaller than mininaml loop depth?");
1654 return MaxLD - MinLD + 1;
1655}
1656
Tobias Grosser3f296192015-01-01 23:01:11 +00001657void Scop::dropConstantScheduleDims() {
1658 isl_union_map *FullSchedule = getSchedule();
1659
1660 if (isl_union_map_n_map(FullSchedule) == 0) {
1661 isl_union_map_free(FullSchedule);
1662 return;
1663 }
1664
1665 isl_set *ScheduleSpace =
1666 isl_set_from_union_set(isl_union_map_range(FullSchedule));
1667 isl_map *DropDimMap = isl_set_identity(isl_set_copy(ScheduleSpace));
1668
1669 int NumDimsDropped = 0;
Johannes Doerfert3f21e272015-03-04 22:23:21 +00001670 for (unsigned i = 0; i < isl_set_dim(ScheduleSpace, isl_dim_set); i += 2) {
1671 isl_val *FixedVal =
1672 isl_set_plain_get_val_if_fixed(ScheduleSpace, isl_dim_set, i);
1673 if (isl_val_is_int(FixedVal)) {
1674 DropDimMap =
1675 isl_map_project_out(DropDimMap, isl_dim_out, i - NumDimsDropped, 1);
1676 NumDimsDropped++;
Tobias Grosser3f296192015-01-01 23:01:11 +00001677 }
Johannes Doerfert3f21e272015-03-04 22:23:21 +00001678 isl_val_free(FixedVal);
1679 }
Tobias Grosser3f296192015-01-01 23:01:11 +00001680
Tobias Grosser3f296192015-01-01 23:01:11 +00001681 for (auto *S : *this) {
Tobias Grosser54839312015-04-21 11:37:25 +00001682 isl_map *Schedule = S->getSchedule();
Tobias Grosser3f296192015-01-01 23:01:11 +00001683 Schedule = isl_map_apply_range(Schedule, isl_map_copy(DropDimMap));
Tobias Grosser54839312015-04-21 11:37:25 +00001684 S->setSchedule(Schedule);
Tobias Grosser3f296192015-01-01 23:01:11 +00001685 }
1686 isl_set_free(ScheduleSpace);
1687 isl_map_free(DropDimMap);
1688}
1689
Tobias Grosser0e27e242011-10-06 00:03:48 +00001690Scop::Scop(TempScop &tempScop, LoopInfo &LI, ScalarEvolution &ScalarEvolution,
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001691 ScopDetection &SD, isl_ctx *Context)
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001692 : SE(&ScalarEvolution), R(tempScop.getMaxRegion()), IsOptimized(false),
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001693 MaxLoopDepth(getMaxLoopDepthInRegion(tempScop.getMaxRegion(), LI, SD)) {
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001694 IslCtx = Context;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001695
Tobias Grosser6be480c2011-11-08 15:41:13 +00001696 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001697
Tobias Grosserabfbe632013-02-05 12:09:06 +00001698 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser54839312015-04-21 11:37:25 +00001699 SmallVector<unsigned, 8> Schedule;
Tobias Grosser75805372011-04-29 06:27:02 +00001700
Tobias Grosser54839312015-04-21 11:37:25 +00001701 Schedule.assign(MaxLoopDepth + 1, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001702
Tobias Grosser54839312015-04-21 11:37:25 +00001703 // Build the iteration domain, access functions and schedule functions
Tobias Grosser75805372011-04-29 06:27:02 +00001704 // traversing the region tree.
Tobias Grosser54839312015-04-21 11:37:25 +00001705 buildScop(tempScop, getRegion(), NestLoops, Schedule, LI, SD);
Tobias Grosser75805372011-04-29 06:27:02 +00001706
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001707 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001708 addParameterBounds();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001709 simplifyAssumedContext();
Tobias Grosser3f296192015-01-01 23:01:11 +00001710 dropConstantScheduleDims();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001711
Tobias Grosser75805372011-04-29 06:27:02 +00001712 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1713}
1714
1715Scop::~Scop() {
1716 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001717 isl_set_free(AssumedContext);
Tobias Grosser75805372011-04-29 06:27:02 +00001718
1719 // Free the statements;
Tobias Grosser083d3d32014-06-28 08:59:45 +00001720 for (ScopStmt *Stmt : *this)
1721 delete Stmt;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001722
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001723 // Free the ScopArrayInfo objects.
1724 for (auto &ScopArrayInfoPair : ScopArrayInfoMap)
1725 delete ScopArrayInfoPair.second;
1726
Johannes Doerfertb164c792014-09-18 11:17:17 +00001727 // Free the alias groups
1728 for (MinMaxVectorTy *MinMaxAccesses : MinMaxAliasGroups) {
1729 for (MinMaxAccessTy &MMA : *MinMaxAccesses) {
1730 isl_pw_multi_aff_free(MMA.first);
1731 isl_pw_multi_aff_free(MMA.second);
1732 }
1733 delete MinMaxAccesses;
1734 }
Tobias Grosser75805372011-04-29 06:27:02 +00001735}
1736
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001737const ScopArrayInfo *
1738Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
1739 const SmallVector<const SCEV *, 4> &Sizes) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001740 const ScopArrayInfo *&SAI = ScopArrayInfoMap[BasePtr];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001741 if (!SAI)
1742 SAI = new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001743 return SAI;
1744}
1745
1746const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr) {
1747 const SCEV *PtrSCEV = SE->getSCEV(BasePtr);
1748 const SCEVUnknown *PtrBaseSCEV =
1749 cast<SCEVUnknown>(SE->getPointerBase(PtrSCEV));
1750 const ScopArrayInfo *SAI = ScopArrayInfoMap[PtrBaseSCEV->getValue()];
1751 assert(SAI && "No ScopArrayInfo available for this base pointer");
1752 return SAI;
1753}
1754
Tobias Grosser74394f02013-01-14 22:40:23 +00001755std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001756std::string Scop::getAssumedContextStr() const {
1757 return stringFromIslObj(AssumedContext);
1758}
Tobias Grosser75805372011-04-29 06:27:02 +00001759
1760std::string Scop::getNameStr() const {
1761 std::string ExitName, EntryName;
1762 raw_string_ostream ExitStr(ExitName);
1763 raw_string_ostream EntryStr(EntryName);
1764
Tobias Grosserf240b482014-01-09 10:42:15 +00001765 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001766 EntryStr.str();
1767
1768 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001769 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001770 ExitStr.str();
1771 } else
1772 ExitName = "FunctionExit";
1773
1774 return EntryName + "---" + ExitName;
1775}
1776
Tobias Grosser74394f02013-01-14 22:40:23 +00001777__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001778__isl_give isl_space *Scop::getParamSpace() const {
1779 return isl_set_get_space(this->Context);
1780}
1781
Tobias Grossere86109f2013-10-29 21:05:49 +00001782__isl_give isl_set *Scop::getAssumedContext() const {
1783 return isl_set_copy(AssumedContext);
1784}
1785
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001786void Scop::addAssumption(__isl_take isl_set *Set) {
1787 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001788 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001789}
1790
Tobias Grosser75805372011-04-29 06:27:02 +00001791void Scop::printContext(raw_ostream &OS) const {
1792 OS << "Context:\n";
1793
1794 if (!Context) {
1795 OS.indent(4) << "n/a\n\n";
1796 return;
1797 }
1798
1799 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001800
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001801 OS.indent(4) << "Assumed Context:\n";
1802 if (!AssumedContext) {
1803 OS.indent(4) << "n/a\n\n";
1804 return;
1805 }
1806
1807 OS.indent(4) << getAssumedContextStr() << "\n";
1808
Tobias Grosser083d3d32014-06-28 08:59:45 +00001809 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001810 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001811 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1812 }
Tobias Grosser75805372011-04-29 06:27:02 +00001813}
1814
Johannes Doerfertb164c792014-09-18 11:17:17 +00001815void Scop::printAliasAssumptions(raw_ostream &OS) const {
1816 OS.indent(4) << "Alias Groups (" << MinMaxAliasGroups.size() << "):\n";
1817 if (MinMaxAliasGroups.empty()) {
1818 OS.indent(8) << "n/a\n";
1819 return;
1820 }
1821 for (MinMaxVectorTy *MinMaxAccesses : MinMaxAliasGroups) {
1822 OS.indent(8) << "[[";
1823 for (MinMaxAccessTy &MinMacAccess : *MinMaxAccesses)
1824 OS << " <" << MinMacAccess.first << ", " << MinMacAccess.second << ">";
1825 OS << " ]]\n";
1826 }
1827}
1828
Tobias Grosser75805372011-04-29 06:27:02 +00001829void Scop::printStatements(raw_ostream &OS) const {
1830 OS << "Statements {\n";
1831
Tobias Grosser083d3d32014-06-28 08:59:45 +00001832 for (ScopStmt *Stmt : *this)
1833 OS.indent(4) << *Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001834
1835 OS.indent(4) << "}\n";
1836}
1837
Tobias Grosser75805372011-04-29 06:27:02 +00001838void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00001839 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
1840 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00001841 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00001842 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001843 printContext(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001844 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001845 printStatements(OS.indent(4));
1846}
1847
1848void Scop::dump() const { print(dbgs()); }
1849
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001850isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00001851
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001852__isl_give isl_union_set *Scop::getDomains() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001853 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001854
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001855 for (ScopStmt *Stmt : *this)
1856 Domain = isl_union_set_add_set(Domain, Stmt->getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001857
1858 return Domain;
1859}
1860
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001861__isl_give isl_union_map *Scop::getMustWrites() {
1862 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1863
1864 for (ScopStmt *Stmt : *this) {
1865 for (MemoryAccess *MA : *Stmt) {
1866 if (!MA->isMustWrite())
1867 continue;
1868
1869 isl_set *Domain = Stmt->getDomain();
1870 isl_map *AccessDomain = MA->getAccessRelation();
1871 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1872 Write = isl_union_map_add_map(Write, AccessDomain);
1873 }
1874 }
1875 return isl_union_map_coalesce(Write);
1876}
1877
1878__isl_give isl_union_map *Scop::getMayWrites() {
1879 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1880
1881 for (ScopStmt *Stmt : *this) {
1882 for (MemoryAccess *MA : *Stmt) {
1883 if (!MA->isMayWrite())
1884 continue;
1885
1886 isl_set *Domain = Stmt->getDomain();
1887 isl_map *AccessDomain = MA->getAccessRelation();
1888 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1889 Write = isl_union_map_add_map(Write, AccessDomain);
1890 }
1891 }
1892 return isl_union_map_coalesce(Write);
1893}
1894
Tobias Grosser37eb4222014-02-20 21:43:54 +00001895__isl_give isl_union_map *Scop::getWrites() {
1896 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1897
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001898 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001899 for (MemoryAccess *MA : *Stmt) {
1900 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001901 continue;
1902
1903 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001904 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001905 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1906 Write = isl_union_map_add_map(Write, AccessDomain);
1907 }
1908 }
1909 return isl_union_map_coalesce(Write);
1910}
1911
1912__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001913 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001914
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001915 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001916 for (MemoryAccess *MA : *Stmt) {
1917 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001918 continue;
1919
1920 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001921 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001922
1923 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1924 Read = isl_union_map_add_map(Read, AccessDomain);
1925 }
1926 }
1927 return isl_union_map_coalesce(Read);
1928}
1929
1930__isl_give isl_union_map *Scop::getSchedule() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001931 isl_union_map *Schedule = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001932
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001933 for (ScopStmt *Stmt : *this)
Tobias Grosser54839312015-04-21 11:37:25 +00001934 Schedule = isl_union_map_add_map(Schedule, Stmt->getSchedule());
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001935
Tobias Grosser37eb4222014-02-20 21:43:54 +00001936 return isl_union_map_coalesce(Schedule);
1937}
1938
1939bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
1940 bool Changed = false;
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001941 for (ScopStmt *Stmt : *this) {
Tobias Grosser37eb4222014-02-20 21:43:54 +00001942 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt->getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001943 isl_union_set *NewStmtDomain = isl_union_set_intersect(
1944 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
1945
1946 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
1947 isl_union_set_free(StmtDomain);
1948 isl_union_set_free(NewStmtDomain);
1949 continue;
1950 }
1951
1952 Changed = true;
1953
1954 isl_union_set_free(StmtDomain);
1955 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
1956
1957 if (isl_union_set_is_empty(NewStmtDomain)) {
1958 Stmt->restrictDomain(isl_set_empty(Stmt->getDomainSpace()));
1959 isl_union_set_free(NewStmtDomain);
1960 } else
1961 Stmt->restrictDomain(isl_set_from_union_set(NewStmtDomain));
1962 }
1963 isl_union_set_free(Domain);
1964 return Changed;
1965}
1966
Tobias Grosser75805372011-04-29 06:27:02 +00001967ScalarEvolution *Scop::getSE() const { return SE; }
1968
1969bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
1970 if (tempScop.getAccessFunctions(BB))
1971 return false;
1972
1973 return true;
1974}
1975
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001976void Scop::addScopStmt(BasicBlock *BB, Region *R, TempScop &tempScop,
1977 const Region &CurRegion,
1978 SmallVectorImpl<Loop *> &NestLoops,
Tobias Grosser54839312015-04-21 11:37:25 +00001979 SmallVectorImpl<unsigned> &ScheduleVec) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001980 ScopStmt *Stmt;
1981
1982 if (BB) {
Tobias Grosser654af8f2015-04-21 11:42:01 +00001983 Stmt =
1984 new ScopStmt(*this, tempScop, CurRegion, *BB, NestLoops, ScheduleVec);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001985 StmtMap[BB] = Stmt;
1986 } else {
1987 assert(R && "Either a basic block or a region is needed to "
1988 "create a new SCoP stmt.");
Tobias Grosser54839312015-04-21 11:37:25 +00001989 Stmt = new ScopStmt(*this, tempScop, CurRegion, *R, NestLoops, ScheduleVec);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001990 for (BasicBlock *BB : R->blocks())
1991 StmtMap[BB] = Stmt;
1992 }
1993
1994 // Insert all statements into the statement map and the statement vector.
1995 Stmts.push_back(Stmt);
1996
Tobias Grosser54839312015-04-21 11:37:25 +00001997 // Increasing the Schedule function is OK for the moment, because
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001998 // we are using a depth first iterator and the program is well structured.
Tobias Grosser54839312015-04-21 11:37:25 +00001999 ++ScheduleVec[NestLoops.size()];
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002000}
2001
Tobias Grosser74394f02013-01-14 22:40:23 +00002002void Scop::buildScop(TempScop &tempScop, const Region &CurRegion,
2003 SmallVectorImpl<Loop *> &NestLoops,
Tobias Grosser54839312015-04-21 11:37:25 +00002004 SmallVectorImpl<unsigned> &ScheduleVec, LoopInfo &LI,
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002005 ScopDetection &SD) {
2006 if (SD.isNonAffineSubRegion(&CurRegion, &getRegion()))
2007 return addScopStmt(nullptr, const_cast<Region *>(&CurRegion), tempScop,
Tobias Grosser54839312015-04-21 11:37:25 +00002008 CurRegion, NestLoops, ScheduleVec);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002009
Tobias Grosser75805372011-04-29 06:27:02 +00002010 Loop *L = castToLoop(CurRegion, LI);
2011
2012 if (L)
2013 NestLoops.push_back(L);
2014
2015 unsigned loopDepth = NestLoops.size();
Tobias Grosser54839312015-04-21 11:37:25 +00002016 assert(ScheduleVec.size() > loopDepth && "Schedule not big enough!");
Tobias Grosser75805372011-04-29 06:27:02 +00002017
2018 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00002019 E = CurRegion.element_end();
2020 I != E; ++I)
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002021 if (I->isSubRegion()) {
Tobias Grosser654af8f2015-04-21 11:42:01 +00002022 buildScop(tempScop, *I->getNodeAs<Region>(), NestLoops, ScheduleVec, LI,
2023 SD);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002024 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00002025 BasicBlock *BB = I->getNodeAs<BasicBlock>();
2026
2027 if (isTrivialBB(BB, tempScop))
2028 continue;
2029
Tobias Grosser54839312015-04-21 11:37:25 +00002030 addScopStmt(BB, nullptr, tempScop, CurRegion, NestLoops, ScheduleVec);
Tobias Grosser75805372011-04-29 06:27:02 +00002031 }
2032
2033 if (!L)
2034 return;
2035
2036 // Exiting a loop region.
Tobias Grosser54839312015-04-21 11:37:25 +00002037 ScheduleVec[loopDepth] = 0;
Tobias Grosser75805372011-04-29 06:27:02 +00002038 NestLoops.pop_back();
Tobias Grosser54839312015-04-21 11:37:25 +00002039 ++ScheduleVec[loopDepth - 1];
Tobias Grosser75805372011-04-29 06:27:02 +00002040}
2041
Johannes Doerfert7c494212014-10-31 23:13:39 +00002042ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
2043 const auto &StmtMapIt = StmtMap.find(BB);
2044 if (StmtMapIt == StmtMap.end())
2045 return nullptr;
2046 return StmtMapIt->second;
2047}
2048
Tobias Grosser75805372011-04-29 06:27:02 +00002049//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00002050ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
2051 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00002052 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00002053}
2054
2055ScopInfo::~ScopInfo() {
2056 clear();
2057 isl_ctx_free(ctx);
2058}
2059
Tobias Grosser75805372011-04-29 06:27:02 +00002060void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00002061 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00002062 AU.addRequired<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00002063 AU.addRequired<ScalarEvolution>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002064 AU.addRequired<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00002065 AU.addRequired<TempScopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002066 AU.addRequired<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00002067 AU.setPreservesAll();
2068}
2069
2070bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Chandler Carruthf5579872015-01-17 14:16:56 +00002071 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002072 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002073 ScopDetection &SD = getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00002074 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
2075
2076 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop(R);
2077
2078 // This region is no Scop.
2079 if (!tempScop) {
Tobias Grosserc98a8fc2014-11-14 11:12:31 +00002080 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002081 return false;
2082 }
2083
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002084 scop = new Scop(*tempScop, LI, SE, SD, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00002085
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002086 if (!PollyUseRuntimeAliasChecks) {
2087 // Statistics.
2088 ++ScopFound;
2089 if (scop->getMaxLoopDepth() > 0)
2090 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002091 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002092 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002093
Johannes Doerfert9143d672014-09-27 11:02:39 +00002094 // If a problem occurs while building the alias groups we need to delete
2095 // this SCoP and pretend it wasn't valid in the first place.
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002096 if (scop->buildAliasGroups(AA)) {
2097 // Statistics.
2098 ++ScopFound;
2099 if (scop->getMaxLoopDepth() > 0)
2100 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002101 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002102 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002103
2104 DEBUG(dbgs()
2105 << "\n\nNOTE: Run time checks for " << scop->getNameStr()
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002106 << " could not be created as the number of parameters involved is too "
Johannes Doerfert9143d672014-09-27 11:02:39 +00002107 "high. The SCoP will be "
2108 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust the "
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002109 "maximal number of parameters but be advised that the compile time "
Johannes Doerfert9143d672014-09-27 11:02:39 +00002110 "might increase exponentially.\n\n");
2111
2112 delete scop;
2113 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002114 return false;
2115}
2116
2117char ScopInfo::ID = 0;
2118
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002119Pass *polly::createScopInfoPass() { return new ScopInfo(); }
2120
Tobias Grosser73600b82011-10-08 00:30:40 +00002121INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
2122 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002123 false);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002124INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Chandler Carruthf5579872015-01-17 14:16:56 +00002125INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00002126INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002127INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002128INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002129INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Tobias Grosser73600b82011-10-08 00:30:40 +00002130INITIALIZE_PASS_END(ScopInfo, "polly-scops",
2131 "Polly - Create polyhedral description of Scops", false,
2132 false)