blob: 78db4a4990964016633a283b9de0daddc2a6b95a [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 Grosser83628182013-05-07 08:11:54 +000028#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000029#include "llvm/ADT/StringExtras.h"
Tobias Grosser83628182013-05-07 08:11:54 +000030#include "llvm/Analysis/LoopInfo.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000031#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser83628182013-05-07 08:11:54 +000032#include "llvm/Analysis/RegionIterator.h"
33#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000034#include "llvm/Support/Debug.h"
35
36#include "isl/constraint.h"
37#include "isl/set.h"
38#include "isl/map.h"
Tobias Grosser37eb4222014-02-20 21:43:54 +000039#include "isl/union_map.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000040#include "isl/aff.h"
41#include "isl/printer.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000042#include "isl/local_space.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000043#include "isl/options.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000044#include "isl/val.h"
Chandler Carruth95fef942014-04-22 03:30:19 +000045
Tobias Grosser75805372011-04-29 06:27:02 +000046#include <sstream>
47#include <string>
48#include <vector>
49
50using namespace llvm;
51using namespace polly;
52
Chandler Carruth95fef942014-04-22 03:30:19 +000053#define DEBUG_TYPE "polly-scops"
54
Tobias Grosser74394f02013-01-14 22:40:23 +000055STATISTIC(ScopFound, "Number of valid Scops");
56STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000057
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000058// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000059// operations can overflow easily. Additive reductions and bit operations
60// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000061static cl::opt<bool> DisableMultiplicativeReductions(
62 "polly-disable-multiplicative-reductions",
63 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
64 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000065
Johannes Doerfert9143d672014-09-27 11:02:39 +000066static cl::opt<unsigned> RunTimeChecksMaxParameters(
67 "polly-rtc-max-parameters",
68 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
69 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
70
Tobias Grosser0695ee42013-09-17 03:30:31 +000071/// Translate a 'const SCEV *' expression in an isl_pw_aff.
Tobias Grosserabfbe632013-02-05 12:09:06 +000072struct SCEVAffinator : public SCEVVisitor<SCEVAffinator, isl_pw_aff *> {
Tobias Grosser0695ee42013-09-17 03:30:31 +000073public:
Tobias Grosser0695ee42013-09-17 03:30:31 +000074 /// @brief Translate a 'const SCEV *' to an isl_pw_aff.
75 ///
76 /// @param Stmt The location at which the scalar evolution expression
77 /// is evaluated.
78 /// @param Expr The expression that is translated.
79 static __isl_give isl_pw_aff *getPwAff(ScopStmt *Stmt, const SCEV *Expr);
80
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000081private:
Tobias Grosser3cc99742012-06-06 16:33:15 +000082 isl_ctx *Ctx;
Tobias Grosserf5338802011-10-06 00:03:35 +000083 int NbLoopSpaces;
Tobias Grosser3cc99742012-06-06 16:33:15 +000084 const Scop *S;
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000085
Tobias Grosser0695ee42013-09-17 03:30:31 +000086 SCEVAffinator(const ScopStmt *Stmt);
87 int getLoopDepth(const Loop *L);
Tobias Grosser60b54f12011-11-08 15:41:28 +000088
Tobias Grosser0695ee42013-09-17 03:30:31 +000089 __isl_give isl_pw_aff *visit(const SCEV *Expr);
90 __isl_give isl_pw_aff *visitConstant(const SCEVConstant *Expr);
91 __isl_give isl_pw_aff *visitTruncateExpr(const SCEVTruncateExpr *Expr);
92 __isl_give isl_pw_aff *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr);
93 __isl_give isl_pw_aff *visitSignExtendExpr(const SCEVSignExtendExpr *Expr);
94 __isl_give isl_pw_aff *visitAddExpr(const SCEVAddExpr *Expr);
95 __isl_give isl_pw_aff *visitMulExpr(const SCEVMulExpr *Expr);
96 __isl_give isl_pw_aff *visitUDivExpr(const SCEVUDivExpr *Expr);
97 __isl_give isl_pw_aff *visitAddRecExpr(const SCEVAddRecExpr *Expr);
98 __isl_give isl_pw_aff *visitSMaxExpr(const SCEVSMaxExpr *Expr);
99 __isl_give isl_pw_aff *visitUMaxExpr(const SCEVUMaxExpr *Expr);
100 __isl_give isl_pw_aff *visitUnknown(const SCEVUnknown *Expr);
Johannes Doerfertb9d18882015-02-11 14:54:50 +0000101 __isl_give isl_pw_aff *visitSDivInstruction(Instruction *SDiv);
Tobias Grosser60b54f12011-11-08 15:41:28 +0000102
Tobias Grosser0695ee42013-09-17 03:30:31 +0000103 friend struct SCEVVisitor<SCEVAffinator, isl_pw_aff *>;
104};
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000105
Tobias Grosser0695ee42013-09-17 03:30:31 +0000106SCEVAffinator::SCEVAffinator(const ScopStmt *Stmt)
107 : Ctx(Stmt->getIslCtx()), NbLoopSpaces(Stmt->getNumIterators()),
108 S(Stmt->getParent()) {}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000109
Tobias Grosser0695ee42013-09-17 03:30:31 +0000110__isl_give isl_pw_aff *SCEVAffinator::getPwAff(ScopStmt *Stmt,
111 const SCEV *Scev) {
112 Scop *S = Stmt->getParent();
113 const Region *Reg = &S->getRegion();
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000114
Tobias Grosser0695ee42013-09-17 03:30:31 +0000115 S->addParams(getParamsInAffineExpr(Reg, Scev, *S->getSE()));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000116
Tobias Grosser0695ee42013-09-17 03:30:31 +0000117 SCEVAffinator Affinator(Stmt);
118 return Affinator.visit(Scev);
119}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000120
Tobias Grosser0695ee42013-09-17 03:30:31 +0000121__isl_give isl_pw_aff *SCEVAffinator::visit(const SCEV *Expr) {
122 // In case the scev is a valid parameter, we do not further analyze this
123 // expression, but create a new parameter in the isl_pw_aff. This allows us
124 // to treat subexpressions that we cannot translate into an piecewise affine
125 // expression, as constant parameters of the piecewise affine expression.
126 if (isl_id *Id = S->getIdForParam(Expr)) {
127 isl_space *Space = isl_space_set_alloc(Ctx, 1, NbLoopSpaces);
128 Space = isl_space_set_dim_id(Space, isl_dim_param, 0, Id);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000129
Tobias Grosser0695ee42013-09-17 03:30:31 +0000130 isl_set *Domain = isl_set_universe(isl_space_copy(Space));
131 isl_aff *Affine = isl_aff_zero_on_domain(isl_local_space_from_space(Space));
132 Affine = isl_aff_add_coefficient_si(Affine, isl_dim_param, 0, 1);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000133
134 return isl_pw_aff_alloc(Domain, Affine);
135 }
136
Tobias Grosser0695ee42013-09-17 03:30:31 +0000137 return SCEVVisitor<SCEVAffinator, isl_pw_aff *>::visit(Expr);
138}
139
Tobias Grosser0d170132013-10-03 13:09:19 +0000140__isl_give isl_pw_aff *SCEVAffinator::visitConstant(const SCEVConstant *Expr) {
Tobias Grosser0695ee42013-09-17 03:30:31 +0000141 ConstantInt *Value = Expr->getValue();
142 isl_val *v;
143
144 // LLVM does not define if an integer value is interpreted as a signed or
145 // unsigned value. Hence, without further information, it is unknown how
146 // this value needs to be converted to GMP. At the moment, we only support
147 // signed operations. So we just interpret it as signed. Later, there are
148 // two options:
149 //
150 // 1. We always interpret any value as signed and convert the values on
151 // demand.
152 // 2. We pass down the signedness of the calculation and use it to interpret
153 // this constant correctly.
154 v = isl_valFromAPInt(Ctx, Value->getValue(), /* isSigned */ true);
155
156 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
Johannes Doerfert9c147372014-11-19 15:36:59 +0000157 isl_local_space *ls = isl_local_space_from_space(Space);
158 return isl_pw_aff_from_aff(isl_aff_val_on_domain(ls, v));
Tobias Grosser0695ee42013-09-17 03:30:31 +0000159}
160
161__isl_give isl_pw_aff *
162SCEVAffinator::visitTruncateExpr(const SCEVTruncateExpr *Expr) {
163 llvm_unreachable("SCEVTruncateExpr not yet supported");
164}
165
166__isl_give isl_pw_aff *
167SCEVAffinator::visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
168 llvm_unreachable("SCEVZeroExtendExpr not yet supported");
169}
170
171__isl_give isl_pw_aff *
172SCEVAffinator::visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
173 // Assuming the value is signed, a sign extension is basically a noop.
174 // TODO: Reconsider this as soon as we support unsigned values.
175 return visit(Expr->getOperand());
176}
177
178__isl_give isl_pw_aff *SCEVAffinator::visitAddExpr(const SCEVAddExpr *Expr) {
179 isl_pw_aff *Sum = visit(Expr->getOperand(0));
180
181 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
182 isl_pw_aff *NextSummand = visit(Expr->getOperand(i));
183 Sum = isl_pw_aff_add(Sum, NextSummand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000184 }
185
Tobias Grosser0695ee42013-09-17 03:30:31 +0000186 // TODO: Check for NSW and NUW.
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000187
Tobias Grosser0695ee42013-09-17 03:30:31 +0000188 return Sum;
189}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000190
Tobias Grosser0695ee42013-09-17 03:30:31 +0000191__isl_give isl_pw_aff *SCEVAffinator::visitMulExpr(const SCEVMulExpr *Expr) {
192 isl_pw_aff *Product = visit(Expr->getOperand(0));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000193
Tobias Grosser0695ee42013-09-17 03:30:31 +0000194 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
195 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
196
197 if (!isl_pw_aff_is_cst(Product) && !isl_pw_aff_is_cst(NextOperand)) {
198 isl_pw_aff_free(Product);
199 isl_pw_aff_free(NextOperand);
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000200 return nullptr;
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000201 }
202
Tobias Grosser0695ee42013-09-17 03:30:31 +0000203 Product = isl_pw_aff_mul(Product, NextOperand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000204 }
205
Tobias Grosser0695ee42013-09-17 03:30:31 +0000206 // TODO: Check for NSW and NUW.
207 return Product;
208}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000209
Tobias Grosser0695ee42013-09-17 03:30:31 +0000210__isl_give isl_pw_aff *SCEVAffinator::visitUDivExpr(const SCEVUDivExpr *Expr) {
211 llvm_unreachable("SCEVUDivExpr not yet supported");
212}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000213
Tobias Grosser0695ee42013-09-17 03:30:31 +0000214__isl_give isl_pw_aff *
215SCEVAffinator::visitAddRecExpr(const SCEVAddRecExpr *Expr) {
216 assert(Expr->isAffine() && "Only affine AddRecurrences allowed");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000217
Tobias Grosser0695ee42013-09-17 03:30:31 +0000218 // Directly generate isl_pw_aff for Expr if 'start' is zero.
219 if (Expr->getStart()->isZero()) {
220 assert(S->getRegion().contains(Expr->getLoop()) &&
221 "Scop does not contain the loop referenced in this AddRec");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000222
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000223 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser0695ee42013-09-17 03:30:31 +0000224 isl_pw_aff *Step = visit(Expr->getOperand(1));
225 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
226 isl_local_space *LocalSpace = isl_local_space_from_space(Space);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000227
Tobias Grosser0695ee42013-09-17 03:30:31 +0000228 int loopDimension = getLoopDepth(Expr->getLoop());
229
230 isl_aff *LAff = isl_aff_set_coefficient_si(
231 isl_aff_zero_on_domain(LocalSpace), isl_dim_in, loopDimension, 1);
232 isl_pw_aff *LPwAff = isl_pw_aff_from_aff(LAff);
233
234 // TODO: Do we need to check for NSW and NUW?
235 return isl_pw_aff_add(Start, isl_pw_aff_mul(Step, LPwAff));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000236 }
237
Tobias Grosser0695ee42013-09-17 03:30:31 +0000238 // Translate AddRecExpr from '{start, +, inc}' into 'start + {0, +, inc}'
239 // if 'start' is not zero.
240 ScalarEvolution &SE = *S->getSE();
241 const SCEV *ZeroStartExpr = SE.getAddRecExpr(
242 SE.getConstant(Expr->getStart()->getType(), 0),
243 Expr->getStepRecurrence(SE), Expr->getLoop(), SCEV::FlagAnyWrap);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000244
Tobias Grosser0695ee42013-09-17 03:30:31 +0000245 isl_pw_aff *ZeroStartResult = visit(ZeroStartExpr);
246 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000247
Tobias Grosser0695ee42013-09-17 03:30:31 +0000248 return isl_pw_aff_add(ZeroStartResult, Start);
249}
250
251__isl_give isl_pw_aff *SCEVAffinator::visitSMaxExpr(const SCEVSMaxExpr *Expr) {
252 isl_pw_aff *Max = visit(Expr->getOperand(0));
253
254 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
255 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
256 Max = isl_pw_aff_max(Max, NextOperand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000257 }
258
Tobias Grosser0695ee42013-09-17 03:30:31 +0000259 return Max;
260}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000261
Tobias Grosser0695ee42013-09-17 03:30:31 +0000262__isl_give isl_pw_aff *SCEVAffinator::visitUMaxExpr(const SCEVUMaxExpr *Expr) {
263 llvm_unreachable("SCEVUMaxExpr not yet supported");
264}
265
Johannes Doerfertb9d18882015-02-11 14:54:50 +0000266__isl_give isl_pw_aff *SCEVAffinator::visitSDivInstruction(Instruction *SDiv) {
267 assert(SDiv->getOpcode() == Instruction::SDiv && "Assumed SDiv instruction!");
268 auto *SE = S->getSE();
269
270 auto *Divisor = SDiv->getOperand(1);
271 auto *DivisorSCEV = SE->getSCEV(Divisor);
272 auto *DivisorPWA = visit(DivisorSCEV);
273 assert(isa<ConstantInt>(Divisor) &&
274 "SDiv is no parameter but has a non-constant RHS.");
275
276 auto *Dividend = SDiv->getOperand(0);
277 auto *DividendSCEV = SE->getSCEV(Dividend);
278 auto *DividendPWA = visit(DividendSCEV);
279 return isl_pw_aff_tdiv_q(DividendPWA, DivisorPWA);
280}
281
Tobias Grosser0695ee42013-09-17 03:30:31 +0000282__isl_give isl_pw_aff *SCEVAffinator::visitUnknown(const SCEVUnknown *Expr) {
Johannes Doerfertb9d18882015-02-11 14:54:50 +0000283 if (Instruction *I = dyn_cast<Instruction>(Expr->getValue())) {
284 switch (I->getOpcode()) {
285 case Instruction::SDiv:
286 return visitSDivInstruction(I);
287 default:
288 break; // Fall through.
289 }
290 }
291
292 llvm_unreachable(
293 "Unknowns SCEV was neither parameter nor a valid instruction.");
Tobias Grosser0695ee42013-09-17 03:30:31 +0000294}
295
296int SCEVAffinator::getLoopDepth(const Loop *L) {
297 Loop *outerLoop = S->getRegion().outermostLoopInRegion(const_cast<Loop *>(L));
298 assert(outerLoop && "Scop does not contain this loop");
299 return L->getLoopDepth() - outerLoop->getLoopDepth();
300}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000301
Johannes Doerferte7044942015-02-24 11:58:30 +0000302/// @brief Add the bounds of @p Range to the set @p S for dimension @p dim.
303static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
304 const ConstantRange &Range,
305 int dim,
306 enum isl_dim_type type) {
307 isl_val *V;
308 isl_ctx *ctx = isl_set_get_ctx(S);
309
310 V = isl_valFromAPInt(ctx, Range.getLower(), true);
311 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
312
313 V = isl_valFromAPInt(ctx, Range.getUpper(), true);
314 V = isl_val_sub_ui(V, 1);
315 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
316
317 if (Range.isSignWrappedSet())
318 return isl_set_union(SLB, SUB);
319 else
320 return isl_set_intersect(SLB, SUB);
321}
322
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000323ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *AccessType, isl_ctx *Ctx,
324 const SmallVector<const SCEV *, 4> &DimensionSizes)
325 : BasePtr(BasePtr), AccessType(AccessType), DimensionSizes(DimensionSizes) {
326 const std::string BasePtrName = getIslCompatibleName("MemRef_", BasePtr, "");
327 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
328}
329
330ScopArrayInfo::~ScopArrayInfo() { isl_id_free(Id); }
331
332isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
333
334void ScopArrayInfo::dump() const { print(errs()); }
335
336void ScopArrayInfo::print(raw_ostream &OS) const {
337 OS << "ScopArrayInfo:\n";
338 OS << " Base: " << *getBasePtr() << "\n";
339 OS << " Type: " << *getType() << "\n";
340 OS << " Dimension Sizes:\n";
341 for (unsigned u = 0; u < getNumberOfDimensions(); u++)
342 OS << " " << u << ") " << *DimensionSizes[u] << "\n";
343 OS << "\n";
344}
345
346const ScopArrayInfo *
347ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
348 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
349 assert(Id && "Output dimension didn't have an ID");
350 return getFromId(Id);
351}
352
353const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
354 void *User = isl_id_get_user(Id);
355 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
356 isl_id_free(Id);
357 return SAI;
358}
359
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000360const std::string
361MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
362 switch (RT) {
363 case MemoryAccess::RT_NONE:
364 llvm_unreachable("Requested a reduction operator string for a memory "
365 "access which isn't a reduction");
366 case MemoryAccess::RT_ADD:
367 return "+";
368 case MemoryAccess::RT_MUL:
369 return "*";
370 case MemoryAccess::RT_BOR:
371 return "|";
372 case MemoryAccess::RT_BXOR:
373 return "^";
374 case MemoryAccess::RT_BAND:
375 return "&";
376 }
377 llvm_unreachable("Unknown reduction type");
378 return "";
379}
380
Johannes Doerfertf6183392014-07-01 20:52:51 +0000381/// @brief Return the reduction type for a given binary operator
382static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
383 const Instruction *Load) {
384 if (!BinOp)
385 return MemoryAccess::RT_NONE;
386 switch (BinOp->getOpcode()) {
387 case Instruction::FAdd:
388 if (!BinOp->hasUnsafeAlgebra())
389 return MemoryAccess::RT_NONE;
390 // Fall through
391 case Instruction::Add:
392 return MemoryAccess::RT_ADD;
393 case Instruction::Or:
394 return MemoryAccess::RT_BOR;
395 case Instruction::Xor:
396 return MemoryAccess::RT_BXOR;
397 case Instruction::And:
398 return MemoryAccess::RT_BAND;
399 case Instruction::FMul:
400 if (!BinOp->hasUnsafeAlgebra())
401 return MemoryAccess::RT_NONE;
402 // Fall through
403 case Instruction::Mul:
404 if (DisableMultiplicativeReductions)
405 return MemoryAccess::RT_NONE;
406 return MemoryAccess::RT_MUL;
407 default:
408 return MemoryAccess::RT_NONE;
409 }
410}
Tobias Grosser75805372011-04-29 06:27:02 +0000411//===----------------------------------------------------------------------===//
412
413MemoryAccess::~MemoryAccess() {
Tobias Grosser54a86e62011-08-18 06:31:46 +0000414 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000415 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000416}
417
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000418static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
419 switch (Access.getType()) {
420 case IRAccess::READ:
421 return MemoryAccess::READ;
422 case IRAccess::MUST_WRITE:
423 return MemoryAccess::MUST_WRITE;
424 case IRAccess::MAY_WRITE:
425 return MemoryAccess::MAY_WRITE;
426 }
427 llvm_unreachable("Unknown IRAccess type!");
428}
429
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000430const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
431 isl_id *ArrayId = getArrayId();
432 void *User = isl_id_get_user(ArrayId);
433 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
434 isl_id_free(ArrayId);
435 return SAI;
436}
437
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000438isl_id *MemoryAccess::getArrayId() const {
439 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
440}
441
Johannes Doerferta99130f2014-10-13 12:58:03 +0000442isl_pw_multi_aff *
443MemoryAccess::applyScheduleToAccessRelation(isl_union_map *USchedule) const {
444 isl_map *Schedule, *ScheduledAccRel;
445 isl_union_set *UDomain;
446
447 UDomain = isl_union_set_from_set(getStatement()->getDomain());
448 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
449 Schedule = isl_map_from_union_map(USchedule);
450 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
451 return isl_pw_multi_aff_from_map(ScheduledAccRel);
452}
453
454isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000455 return isl_map_copy(AccessRelation);
456}
457
Johannes Doerferta99130f2014-10-13 12:58:03 +0000458std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000459 return stringFromIslObj(AccessRelation);
460}
461
Johannes Doerferta99130f2014-10-13 12:58:03 +0000462__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000463 return isl_map_get_space(AccessRelation);
464}
465
Tobias Grosser5d453812011-10-06 00:04:11 +0000466isl_map *MemoryAccess::getNewAccessRelation() const {
467 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000468}
469
470isl_basic_map *MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000471 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000472 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000473
Tobias Grosser084d8f72012-05-29 09:29:44 +0000474 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000475 isl_basic_set_universe(Statement->getDomainSpace()),
476 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000477}
478
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000479// Formalize no out-of-bound access assumption
480//
481// When delinearizing array accesses we optimistically assume that the
482// delinearized accesses do not access out of bound locations (the subscript
483// expression of each array evaluates for each statement instance that is
484// executed to a value that is larger than zero and strictly smaller than the
485// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000486// dimension for which we do not need to assume any upper bound. At this point
487// we formalize this assumption to ensure that at code generation time the
488// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000489//
490// To find the set of constraints necessary to avoid out of bound accesses, we
491// first build the set of data locations that are not within array bounds. We
492// then apply the reverse access relation to obtain the set of iterations that
493// may contain invalid accesses and reduce this set of iterations to the ones
494// that are actually executed by intersecting them with the domain of the
495// statement. If we now project out all loop dimensions, we obtain a set of
496// parameters that may cause statement instances to be executed that may
497// possibly yield out of bound memory accesses. The complement of these
498// constraints is the set of constraints that needs to be assumed to ensure such
499// statement instances are never executed.
500void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000501 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000502 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000503 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000504 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
505 isl_pw_aff *Var =
506 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
507 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
508
509 isl_set *DimOutside;
510
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000511 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
512 isl_pw_aff *SizeE = SCEVAffinator::getPwAff(Statement, Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000513
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000514 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
515 Statement->getNumIterators());
516 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
517 isl_space_dim(Space, isl_dim_set));
518 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
519 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000520
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000521 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000522
523 Outside = isl_set_union(Outside, DimOutside);
524 }
525
526 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
527 Outside = isl_set_intersect(Outside, Statement->getDomain());
528 Outside = isl_set_params(Outside);
529 Outside = isl_set_complement(Outside);
530 Statement->getParent()->addAssumption(Outside);
531 isl_space_free(Space);
532}
533
Johannes Doerferte7044942015-02-24 11:58:30 +0000534void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
535 ScalarEvolution *SE = Statement->getParent()->getSE();
536
537 Value *Ptr = getPointerOperand(*getAccessInstruction());
538 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
539 return;
540
541 auto *PtrSCEV = SE->getSCEV(Ptr);
542 if (isa<SCEVCouldNotCompute>(PtrSCEV))
543 return;
544
545 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
546 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
547 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
548
549 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
550 if (Range.isFullSet())
551 return;
552
553 unsigned BW = Range.getBitWidth();
Johannes Doerfert65971a82015-02-24 16:02:16 +0000554 auto Min = Range.getSignedMin().sdiv(APInt(BW, ElementSize));
555 auto Max = (Range.getSignedMax() - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000556
557 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
558 AccessRange =
559 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
560 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
561}
562
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000563MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000564 ScopStmt *Statement, const ScopArrayInfo *SAI)
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000565 : AccType(getMemoryAccessType(Access)), Statement(Statement), Inst(AccInst),
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000566 newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000567
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000568 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000569 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000570 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000571
572 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000573
Tobias Grossera1879642011-12-20 10:43:14 +0000574 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000575 // We overapproximate non-affine accesses with a possible access to the
576 // whole array. For read accesses it does not make a difference, if an
577 // access must or may happen. However, for write accesses it is important to
578 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000579 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000580 AccessRelation =
581 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000582
583 computeBoundsOnAccessRelation(Access.getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000584 return;
585 }
586
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000587 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000588 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000589
Tobias Grosser79baa212014-04-10 08:38:02 +0000590 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Sebastian Pop18016682014-04-08 21:20:44 +0000591 isl_pw_aff *Affine =
592 SCEVAffinator::getPwAff(Statement, Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000593
Sebastian Pop422e33f2014-06-03 18:16:31 +0000594 if (Size == 1) {
595 // For the non delinearized arrays, divide the access function of the last
596 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000597 //
598 // A stride one array access in C expressed as A[i] is expressed in
599 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
600 // two subsequent values of 'i' index two values that are stored next to
601 // each other in memory. By this division we make this characteristic
602 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000603 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000604 Affine = isl_pw_aff_scale_down_val(Affine, v);
605 }
606
607 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
608
Tobias Grosser79baa212014-04-10 08:38:02 +0000609 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000610 }
611
Tobias Grosser79baa212014-04-10 08:38:02 +0000612 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000613 AccessRelation = isl_map_set_tuple_id(
614 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000615 AccessRelation =
616 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
617
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000618 assumeNoOutOfBound(Access);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000619 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000620}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000621
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000622void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000623 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000624 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000625}
626
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000627const std::string MemoryAccess::getReductionOperatorStr() const {
628 return MemoryAccess::getReductionOperatorStr(getReductionType());
629}
630
Johannes Doerfertf6183392014-07-01 20:52:51 +0000631raw_ostream &polly::operator<<(raw_ostream &OS,
632 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000633 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000634 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000635 else
636 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000637 return OS;
638}
639
Tobias Grosser75805372011-04-29 06:27:02 +0000640void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000641 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000642 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000643 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000644 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000645 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000646 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000647 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000648 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000649 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000650 break;
651 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000652 OS << "[Reduction Type: " << getReductionType() << "] ";
653 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000654 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000655}
656
Tobias Grosser74394f02013-01-14 22:40:23 +0000657void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000658
659// Create a map in the size of the provided set domain, that maps from the
660// one element of the provided set domain to another element of the provided
661// set domain.
662// The mapping is limited to all points that are equal in all but the last
663// dimension and for which the last dimension of the input is strict smaller
664// than the last dimension of the output.
665//
666// getEqualAndLarger(set[i0, i1, ..., iX]):
667//
668// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
669// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
670//
Tobias Grosserf5338802011-10-06 00:03:35 +0000671static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000672 isl_space *Space = isl_space_map_from_set(setDomain);
673 isl_map *Map = isl_map_universe(isl_space_copy(Space));
674 isl_local_space *MapLocalSpace = isl_local_space_from_space(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000675 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000676
677 // Set all but the last dimension to be equal for the input and output
678 //
679 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
680 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000681 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000682 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000683
684 // Set the last dimension of the input to be strict smaller than the
685 // last dimension of the output.
686 //
687 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
688 //
Tobias Grosseredab1352013-06-21 06:41:31 +0000689 isl_val *v;
690 isl_ctx *Ctx = isl_map_get_ctx(Map);
Tobias Grosserf5338802011-10-06 00:03:35 +0000691 isl_constraint *c = isl_inequality_alloc(isl_local_space_copy(MapLocalSpace));
Tobias Grosseredab1352013-06-21 06:41:31 +0000692 v = isl_val_int_from_si(Ctx, -1);
693 c = isl_constraint_set_coefficient_val(c, isl_dim_in, lastDimension, v);
694 v = isl_val_int_from_si(Ctx, 1);
695 c = isl_constraint_set_coefficient_val(c, isl_dim_out, lastDimension, v);
696 v = isl_val_int_from_si(Ctx, -1);
697 c = isl_constraint_set_constant_val(c, v);
Tobias Grosser75805372011-04-29 06:27:02 +0000698
Tobias Grosserc327932c2012-02-01 14:23:36 +0000699 Map = isl_map_add_constraint(Map, c);
Tobias Grosser75805372011-04-29 06:27:02 +0000700
Tobias Grosser23b36662011-10-17 08:32:36 +0000701 isl_local_space_free(MapLocalSpace);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000702 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000703}
704
Sebastian Popa00a0292012-12-18 07:46:06 +0000705isl_set *MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000706 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000707 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000708 isl_space *Space = isl_space_range(isl_map_get_space(S));
709 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000710
Sebastian Popa00a0292012-12-18 07:46:06 +0000711 S = isl_map_reverse(S);
712 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000713
Sebastian Popa00a0292012-12-18 07:46:06 +0000714 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
715 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
716 NextScatt = isl_map_apply_domain(NextScatt, S);
717 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000718
Sebastian Popa00a0292012-12-18 07:46:06 +0000719 isl_set *Deltas = isl_map_deltas(NextScatt);
720 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000721}
722
Sebastian Popa00a0292012-12-18 07:46:06 +0000723bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000724 int StrideWidth) const {
725 isl_set *Stride, *StrideX;
726 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000727
Sebastian Popa00a0292012-12-18 07:46:06 +0000728 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000729 StrideX = isl_set_universe(isl_set_get_space(Stride));
730 StrideX = isl_set_fix_si(StrideX, isl_dim_set, 0, StrideWidth);
731 IsStrideX = isl_set_is_equal(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000732
Tobias Grosser28dd4862012-01-24 16:42:16 +0000733 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000734 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000735
Tobias Grosser28dd4862012-01-24 16:42:16 +0000736 return IsStrideX;
737}
738
Sebastian Popa00a0292012-12-18 07:46:06 +0000739bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
740 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000741}
742
Tobias Grosser79baa212014-04-10 08:38:02 +0000743bool MemoryAccess::isScalar() const {
744 return isl_map_n_out(AccessRelation) == 0;
745}
746
Sebastian Popa00a0292012-12-18 07:46:06 +0000747bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
748 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000749}
750
Tobias Grosser5d453812011-10-06 00:04:11 +0000751void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000752 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000753 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000754}
Tobias Grosser75805372011-04-29 06:27:02 +0000755
756//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000757
Tobias Grosser74394f02013-01-14 22:40:23 +0000758isl_map *ScopStmt::getScattering() const { return isl_map_copy(Scattering); }
Tobias Grossercf3942d2011-10-06 00:04:05 +0000759
Tobias Grosser37eb4222014-02-20 21:43:54 +0000760void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
761 assert(isl_set_is_subset(NewDomain, Domain) &&
762 "New domain is not a subset of old domain!");
763 isl_set_free(Domain);
764 Domain = NewDomain;
765 Scattering = isl_map_intersect_domain(Scattering, isl_set_copy(Domain));
766}
767
Tobias Grossercf3942d2011-10-06 00:04:05 +0000768void ScopStmt::setScattering(isl_map *NewScattering) {
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000769 assert(NewScattering && "New scattering is nullptr");
Tobias Grosserb76f38532011-08-20 11:11:25 +0000770 isl_map_free(Scattering);
Tobias Grossercf3942d2011-10-06 00:04:05 +0000771 Scattering = NewScattering;
Tobias Grosserb76f38532011-08-20 11:11:25 +0000772}
773
Tobias Grosser75805372011-04-29 06:27:02 +0000774void ScopStmt::buildScattering(SmallVectorImpl<unsigned> &Scatter) {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000775 unsigned NbIterators = getNumIterators();
776 unsigned NbScatteringDims = Parent.getMaxLoopDepth() * 2 + 1;
777
Tobias Grosser084d8f72012-05-29 09:29:44 +0000778 isl_space *Space = isl_space_set_alloc(getIslCtx(), 0, NbScatteringDims);
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000779
Tobias Grosser084d8f72012-05-29 09:29:44 +0000780 Scattering = isl_map_from_domain_and_range(isl_set_universe(getDomainSpace()),
781 isl_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000782
783 // Loop dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000784 for (unsigned i = 0; i < NbIterators; ++i)
Tobias Grosserabfbe632013-02-05 12:09:06 +0000785 Scattering =
786 isl_map_equate(Scattering, isl_dim_out, 2 * i + 1, isl_dim_in, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000787
788 // Constant dimensions
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000789 for (unsigned i = 0; i < NbIterators + 1; ++i)
790 Scattering = isl_map_fix_si(Scattering, isl_dim_out, 2 * i, Scatter[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000791
792 // Fill scattering dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000793 for (unsigned i = 2 * NbIterators + 1; i < NbScatteringDims; ++i)
794 Scattering = isl_map_fix_si(Scattering, isl_dim_out, i, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000795
Tobias Grosser37487052011-10-06 00:03:42 +0000796 Scattering = isl_map_align_params(Scattering, Parent.getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000797}
798
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000799void ScopStmt::buildAccesses(TempScop &tempScop, BasicBlock *Block,
800 bool isApproximated) {
801 AccFuncSetType *AFS = tempScop.getAccessFunctions(Block);
802 if (!AFS)
803 return;
804
805 for (auto &AccessPair : *AFS) {
806 IRAccess &Access = AccessPair.first;
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000807 Instruction *AccessInst = AccessPair.second;
808
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000809 Type *AccessType = getAccessInstType(AccessInst)->getPointerTo();
810 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
811 Access.getBase(), AccessType, Access.Sizes);
812
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000813 if (isApproximated && Access.isWrite())
814 Access.setMayWrite();
815
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000816 MemAccs.push_back(new MemoryAccess(Access, AccessInst, this, SAI));
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000817
818 // We do not track locations for scalar memory accesses at the moment.
819 //
820 // We do not have a use for this information at the moment. If we need this
821 // at some point, the "instruction -> access" mapping needs to be enhanced
822 // as a single instruction could then possibly perform multiple accesses.
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000823 if (!Access.isScalar()) {
824 assert(!InstructionToAccess.count(AccessInst) &&
Tobias Grosser3fc91542014-02-20 21:43:45 +0000825 "Unexpected 1-to-N mapping on instruction to access map!");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000826 InstructionToAccess[AccessInst] = MemAccs.back();
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000827 }
Tobias Grosser75805372011-04-29 06:27:02 +0000828 }
829}
830
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000831void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000832 for (MemoryAccess *MA : *this)
833 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000834
835 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
836 Scattering = isl_map_align_params(Scattering, Parent.getParamSpace());
837}
838
Tobias Grosser65b00582011-11-08 15:41:19 +0000839__isl_give isl_set *ScopStmt::buildConditionSet(const Comparison &Comp) {
Tobias Grossera601fbd2011-11-09 22:34:44 +0000840 isl_pw_aff *L = SCEVAffinator::getPwAff(this, Comp.getLHS());
841 isl_pw_aff *R = SCEVAffinator::getPwAff(this, Comp.getRHS());
Tobias Grosser75805372011-04-29 06:27:02 +0000842
Tobias Grosserd2795d02011-08-18 07:51:40 +0000843 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000844 case ICmpInst::ICMP_EQ:
Tobias Grosser048c8792011-10-23 20:59:20 +0000845 return isl_pw_aff_eq_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000846 case ICmpInst::ICMP_NE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000847 return isl_pw_aff_ne_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000848 case ICmpInst::ICMP_SLT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000849 return isl_pw_aff_lt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000850 case ICmpInst::ICMP_SLE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000851 return isl_pw_aff_le_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000852 case ICmpInst::ICMP_SGT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000853 return isl_pw_aff_gt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000854 case ICmpInst::ICMP_SGE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000855 return isl_pw_aff_ge_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000856 case ICmpInst::ICMP_ULT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000857 return isl_pw_aff_lt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000858 case ICmpInst::ICMP_UGT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000859 return isl_pw_aff_gt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000860 case ICmpInst::ICMP_ULE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000861 return isl_pw_aff_le_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000862 case ICmpInst::ICMP_UGE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000863 return isl_pw_aff_ge_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000864 default:
865 llvm_unreachable("Non integer predicate not supported");
866 }
Tobias Grosser75805372011-04-29 06:27:02 +0000867}
868
Tobias Grossere19661e2011-10-07 08:46:57 +0000869__isl_give isl_set *ScopStmt::addLoopBoundsToDomain(__isl_take isl_set *Domain,
Tobias Grosser60b54f12011-11-08 15:41:28 +0000870 TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000871 isl_space *Space;
872 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000873
Tobias Grossere19661e2011-10-07 08:46:57 +0000874 Space = isl_set_get_space(Domain);
875 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000876
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000877 ScalarEvolution *SE = getParent()->getSE();
Tobias Grosser75805372011-04-29 06:27:02 +0000878 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000879 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000880 isl_pw_aff *IV =
881 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000882
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000883 // 0 <= IV.
884 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
885 Domain = isl_set_intersect(Domain, LowerBound);
886
887 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000888 const Loop *L = getLoopForDimension(i);
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000889 const SCEV *LatchExecutions = SE->getBackedgeTakenCount(L);
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000890 isl_pw_aff *UpperBound = SCEVAffinator::getPwAff(this, LatchExecutions);
891 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
Tobias Grosser75805372011-04-29 06:27:02 +0000892 Domain = isl_set_intersect(Domain, UpperBoundSet);
893 }
894
Tobias Grosserf5338802011-10-06 00:03:35 +0000895 isl_local_space_free(LocalSpace);
Tobias Grossere19661e2011-10-07 08:46:57 +0000896 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000897}
898
Tobias Grossere602a072013-05-07 07:30:56 +0000899__isl_give isl_set *ScopStmt::addConditionsToDomain(__isl_take isl_set *Domain,
900 TempScop &tempScop,
901 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000902 const Region *TopRegion = tempScop.getMaxRegion().getParent(),
Tobias Grosserd7e58642013-04-10 06:55:45 +0000903 *CurrentRegion = &CurRegion;
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000904 const BasicBlock *BranchingBB = BB ? BB : R->getEntry();
Tobias Grosser75805372011-04-29 06:27:02 +0000905
Tobias Grosser75805372011-04-29 06:27:02 +0000906 do {
Tobias Grossere19661e2011-10-07 08:46:57 +0000907 if (BranchingBB != CurrentRegion->getEntry()) {
908 if (const BBCond *Condition = tempScop.getBBCond(BranchingBB))
Tobias Grosser083d3d32014-06-28 08:59:45 +0000909 for (const auto &C : *Condition) {
910 isl_set *ConditionSet = buildConditionSet(C);
Tobias Grossere19661e2011-10-07 08:46:57 +0000911 Domain = isl_set_intersect(Domain, ConditionSet);
Tobias Grosser75805372011-04-29 06:27:02 +0000912 }
913 }
Tobias Grossere19661e2011-10-07 08:46:57 +0000914 BranchingBB = CurrentRegion->getEntry();
915 CurrentRegion = CurrentRegion->getParent();
916 } while (TopRegion != CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000917
Tobias Grossere19661e2011-10-07 08:46:57 +0000918 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000919}
920
Tobias Grossere602a072013-05-07 07:30:56 +0000921__isl_give isl_set *ScopStmt::buildDomain(TempScop &tempScop,
922 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000923 isl_space *Space;
924 isl_set *Domain;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000925 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000926
927 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
928
Tobias Grosser084d8f72012-05-29 09:29:44 +0000929 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
930
Tobias Grossere19661e2011-10-07 08:46:57 +0000931 Domain = isl_set_universe(Space);
Tobias Grossere19661e2011-10-07 08:46:57 +0000932 Domain = addLoopBoundsToDomain(Domain, tempScop);
933 Domain = addConditionsToDomain(Domain, tempScop, CurRegion);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000934 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grossere19661e2011-10-07 08:46:57 +0000935
936 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000937}
938
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000939void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
940 int Dimension = 0;
941 isl_ctx *Ctx = Parent.getIslCtx();
942 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
943 Type *Ty = GEP->getPointerOperandType();
944 ScalarEvolution &SE = *Parent.getSE();
945
946 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
947 Dimension = 1;
948 Ty = PtrTy->getElementType();
949 }
950
951 while (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
952 unsigned int Operand = 1 + Dimension;
953
954 if (GEP->getNumOperands() <= Operand)
955 break;
956
957 const SCEV *Expr = SE.getSCEV(GEP->getOperand(Operand));
958
959 if (isAffineExpr(&Parent.getRegion(), Expr, SE)) {
960 isl_pw_aff *AccessOffset = SCEVAffinator::getPwAff(this, Expr);
961 AccessOffset =
962 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
963
964 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
965 isl_local_space_copy(LSpace),
966 isl_val_int_from_si(Ctx, ArrayTy->getNumElements())));
967
968 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
969 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
970 OutOfBound = isl_set_params(OutOfBound);
971 isl_set *InBound = isl_set_complement(OutOfBound);
972 isl_set *Executed = isl_set_params(getDomain());
973
974 // A => B == !A or B
975 isl_set *InBoundIfExecuted =
976 isl_set_union(isl_set_complement(Executed), InBound);
977
978 Parent.addAssumption(InBoundIfExecuted);
979 }
980
981 Dimension += 1;
982 Ty = ArrayTy->getElementType();
983 }
984
985 isl_local_space_free(LSpace);
986}
987
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000988void ScopStmt::deriveAssumptions(BasicBlock *Block) {
989 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000990 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
991 deriveAssumptionsFromGEP(GEP);
992}
993
Tobias Grosser74394f02013-01-14 22:40:23 +0000994ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000995 Region &R, SmallVectorImpl<Loop *> &Nest,
996 SmallVectorImpl<unsigned> &Scatter)
997 : Parent(parent), BB(nullptr), R(&R), Build(nullptr),
998 NestLoops(Nest.size()) {
999 // Setup the induction variables.
1000 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
1001 NestLoops[i] = Nest[i];
1002
1003 BaseName = getIslCompatibleName("Stmt_(", R.getNameStr(), ")");
1004
1005 Domain = buildDomain(tempScop, CurRegion);
1006 buildScattering(Scatter);
1007
1008 BasicBlock *EntryBB = R.getEntry();
1009 for (BasicBlock *Block : R.blocks()) {
1010 buildAccesses(tempScop, Block, Block != EntryBB);
1011 deriveAssumptions(Block);
1012 }
1013 checkForReductions();
1014}
1015
1016ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Sebastian Pop860e0212013-02-15 21:26:44 +00001017 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest,
Tobias Grosser75805372011-04-29 06:27:02 +00001018 SmallVectorImpl<unsigned> &Scatter)
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001019 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr),
1020 NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +00001021 // Setup the induction variables.
Tobias Grosser683b8e42014-11-30 14:33:31 +00001022 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
Sebastian Pop860e0212013-02-15 21:26:44 +00001023 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +00001024
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001025 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +00001026
Tobias Grossere19661e2011-10-07 08:46:57 +00001027 Domain = buildDomain(tempScop, CurRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001028 buildScattering(Scatter);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001029 buildAccesses(tempScop, BB);
1030 deriveAssumptions(BB);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001031 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001032}
1033
Johannes Doerferte58a0122014-06-27 20:31:28 +00001034/// @brief Collect loads which might form a reduction chain with @p StoreMA
1035///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001036/// Check if the stored value for @p StoreMA is a binary operator with one or
1037/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001038/// used only once (by @p StoreMA) and its load operands are also used only
1039/// once, we have found a possible reduction chain. It starts at an operand
1040/// load and includes the binary operator and @p StoreMA.
1041///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001042/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001043/// escape this block or into any other store except @p StoreMA.
1044void ScopStmt::collectCandiateReductionLoads(
1045 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1046 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1047 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001048 return;
1049
1050 // Skip if there is not one binary operator between the load and the store
1051 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001052 if (!BinOp)
1053 return;
1054
1055 // Skip if the binary operators has multiple uses
1056 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001057 return;
1058
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001059 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001060 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1061 return;
1062
Johannes Doerfert9890a052014-07-01 00:32:29 +00001063 // Skip if the binary operator is outside the current SCoP
1064 if (BinOp->getParent() != Store->getParent())
1065 return;
1066
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001067 // Skip if it is a multiplicative reduction and we disabled them
1068 if (DisableMultiplicativeReductions &&
1069 (BinOp->getOpcode() == Instruction::Mul ||
1070 BinOp->getOpcode() == Instruction::FMul))
1071 return;
1072
Johannes Doerferte58a0122014-06-27 20:31:28 +00001073 // Check the binary operator operands for a candidate load
1074 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1075 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1076 if (!PossibleLoad0 && !PossibleLoad1)
1077 return;
1078
1079 // A load is only a candidate if it cannot escape (thus has only this use)
1080 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001081 if (PossibleLoad0->getParent() == Store->getParent())
1082 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001083 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001084 if (PossibleLoad1->getParent() == Store->getParent())
1085 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001086}
1087
1088/// @brief Check for reductions in this ScopStmt
1089///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001090/// Iterate over all store memory accesses and check for valid binary reduction
1091/// like chains. For all candidates we check if they have the same base address
1092/// and there are no other accesses which overlap with them. The base address
1093/// check rules out impossible reductions candidates early. The overlap check,
1094/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001095/// guarantees that none of the intermediate results will escape during
1096/// execution of the loop nest. We basically check here that no other memory
1097/// access can access the same memory as the potential reduction.
1098void ScopStmt::checkForReductions() {
1099 SmallVector<MemoryAccess *, 2> Loads;
1100 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1101
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001102 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001103 // stores and collecting possible reduction loads.
1104 for (MemoryAccess *StoreMA : MemAccs) {
1105 if (StoreMA->isRead())
1106 continue;
1107
1108 Loads.clear();
1109 collectCandiateReductionLoads(StoreMA, Loads);
1110 for (MemoryAccess *LoadMA : Loads)
1111 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1112 }
1113
1114 // Then check each possible candidate pair.
1115 for (const auto &CandidatePair : Candidates) {
1116 bool Valid = true;
1117 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1118 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1119
1120 // Skip those with obviously unequal base addresses.
1121 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1122 isl_map_free(LoadAccs);
1123 isl_map_free(StoreAccs);
1124 continue;
1125 }
1126
1127 // And check if the remaining for overlap with other memory accesses.
1128 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1129 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1130 isl_set *AllAccs = isl_map_range(AllAccsRel);
1131
1132 for (MemoryAccess *MA : MemAccs) {
1133 if (MA == CandidatePair.first || MA == CandidatePair.second)
1134 continue;
1135
1136 isl_map *AccRel =
1137 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1138 isl_set *Accs = isl_map_range(AccRel);
1139
1140 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1141 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1142 Valid = Valid && isl_set_is_empty(OverlapAccs);
1143 isl_set_free(OverlapAccs);
1144 }
1145 }
1146
1147 isl_set_free(AllAccs);
1148 if (!Valid)
1149 continue;
1150
Johannes Doerfertf6183392014-07-01 20:52:51 +00001151 const LoadInst *Load =
1152 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1153 MemoryAccess::ReductionType RT =
1154 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1155
Johannes Doerferte58a0122014-06-27 20:31:28 +00001156 // If no overlapping access was found we mark the load and store as
1157 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001158 CandidatePair.first->markAsReductionLike(RT);
1159 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001160 }
Tobias Grosser75805372011-04-29 06:27:02 +00001161}
1162
Tobias Grosser74394f02013-01-14 22:40:23 +00001163std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001164
1165std::string ScopStmt::getScatteringStr() const {
Tobias Grossercf3942d2011-10-06 00:04:05 +00001166 return stringFromIslObj(Scattering);
Tobias Grosser75805372011-04-29 06:27:02 +00001167}
1168
Tobias Grosser74394f02013-01-14 22:40:23 +00001169unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001170
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001171unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001172
1173unsigned ScopStmt::getNumScattering() const {
1174 return isl_map_dim(Scattering, isl_dim_out);
1175}
1176
1177const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1178
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001179const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001180 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001181}
1182
Tobias Grosser74394f02013-01-14 22:40:23 +00001183isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001184
Tobias Grosser74394f02013-01-14 22:40:23 +00001185isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001186
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001187isl_space *ScopStmt::getDomainSpace() const {
1188 return isl_set_get_space(Domain);
1189}
1190
Tobias Grosser74394f02013-01-14 22:40:23 +00001191isl_id *ScopStmt::getDomainId() const { return isl_set_get_tuple_id(Domain); }
Tobias Grossercd95b772012-08-30 11:49:38 +00001192
Tobias Grosser75805372011-04-29 06:27:02 +00001193ScopStmt::~ScopStmt() {
1194 while (!MemAccs.empty()) {
1195 delete MemAccs.back();
1196 MemAccs.pop_back();
1197 }
1198
1199 isl_set_free(Domain);
1200 isl_map_free(Scattering);
1201}
1202
1203void ScopStmt::print(raw_ostream &OS) const {
1204 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001205 OS.indent(12) << "Domain :=\n";
1206
1207 if (Domain) {
1208 OS.indent(16) << getDomainStr() << ";\n";
1209 } else
1210 OS.indent(16) << "n/a\n";
1211
1212 OS.indent(12) << "Scattering :=\n";
1213
1214 if (Domain) {
1215 OS.indent(16) << getScatteringStr() << ";\n";
1216 } else
1217 OS.indent(16) << "n/a\n";
1218
Tobias Grosser083d3d32014-06-28 08:59:45 +00001219 for (MemoryAccess *Access : MemAccs)
1220 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001221}
1222
1223void ScopStmt::dump() const { print(dbgs()); }
1224
1225//===----------------------------------------------------------------------===//
1226/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001227
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001228void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001229 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1230 isl_set_free(Context);
1231 Context = NewContext;
1232}
1233
Tobias Grosserabfbe632013-02-05 12:09:06 +00001234void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001235 for (const SCEV *Parameter : NewParameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001236 if (ParameterIds.find(Parameter) != ParameterIds.end())
1237 continue;
1238
1239 int dimension = Parameters.size();
1240
1241 Parameters.push_back(Parameter);
1242 ParameterIds[Parameter] = dimension;
1243 }
1244}
1245
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001246__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1247 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001248
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001249 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001250 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001251
Tobias Grosser8f99c162011-11-15 11:38:55 +00001252 std::string ParameterName;
1253
1254 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1255 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001256 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001257 }
1258
1259 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001260 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001261
Tobias Grosser20532b82014-04-11 17:56:49 +00001262 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1263 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001264}
Tobias Grosser75805372011-04-29 06:27:02 +00001265
Tobias Grosser6be480c2011-11-08 15:41:13 +00001266void Scop::buildContext() {
1267 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001268 Context = isl_set_universe(isl_space_copy(Space));
1269 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001270}
1271
Tobias Grosser18daaca2012-05-22 10:47:27 +00001272void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001273 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001274 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001275
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001276 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001277
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001278 // TODO: Find a case where the full set is actually helpful.
1279 if (SRange.isFullSet())
Tobias Grosser55bc4c02015-01-08 19:26:53 +00001280 continue;
1281
Johannes Doerferte7044942015-02-24 11:58:30 +00001282 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001283 }
1284}
1285
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001286void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001287 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001288 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001289
Tobias Grosser083d3d32014-06-28 08:59:45 +00001290 for (const auto &ParamID : ParameterIds) {
1291 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001292 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001293 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001294 }
1295
1296 // Align the parameters of all data structures to the model.
1297 Context = isl_set_align_params(Context, Space);
1298
Tobias Grosser083d3d32014-06-28 08:59:45 +00001299 for (ScopStmt *Stmt : *this)
1300 Stmt->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001301}
1302
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001303void Scop::simplifyAssumedContext() {
1304 // The parameter constraints of the iteration domains give us a set of
1305 // constraints that need to hold for all cases where at least a single
1306 // statement iteration is executed in the whole scop. We now simplify the
1307 // assumed context under the assumption that such constraints hold and at
1308 // least a single statement iteration is executed. For cases where no
1309 // statement instances are executed, the assumptions we have taken about
1310 // the executed code do not matter and can be changed.
1311 //
1312 // WARNING: This only holds if the assumptions we have taken do not reduce
1313 // the set of statement instances that are executed. Otherwise we
1314 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001315 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001316 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001317 // performed. In such a case, modifying the run-time conditions and
1318 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001319 // to not be executed.
1320 //
1321 // Example:
1322 //
1323 // When delinearizing the following code:
1324 //
1325 // for (long i = 0; i < 100; i++)
1326 // for (long j = 0; j < m; j++)
1327 // A[i+p][j] = 1.0;
1328 //
1329 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001330 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001331 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1332 AssumedContext =
1333 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001334 AssumedContext = isl_set_gist_params(AssumedContext, getContext());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001335}
1336
Johannes Doerfertb164c792014-09-18 11:17:17 +00001337/// @brief Add the minimal/maximal access in @p Set to @p User.
1338static int buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
1339 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1340 isl_pw_multi_aff *MinPMA, *MaxPMA;
1341 isl_pw_aff *LastDimAff;
1342 isl_aff *OneAff;
1343 unsigned Pos;
1344
Johannes Doerfert9143d672014-09-27 11:02:39 +00001345 // Restrict the number of parameters involved in the access as the lexmin/
1346 // lexmax computation will take too long if this number is high.
1347 //
1348 // Experiments with a simple test case using an i7 4800MQ:
1349 //
1350 // #Parameters involved | Time (in sec)
1351 // 6 | 0.01
1352 // 7 | 0.04
1353 // 8 | 0.12
1354 // 9 | 0.40
1355 // 10 | 1.54
1356 // 11 | 6.78
1357 // 12 | 30.38
1358 //
1359 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1360 unsigned InvolvedParams = 0;
1361 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1362 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1363 InvolvedParams++;
1364
1365 if (InvolvedParams > RunTimeChecksMaxParameters) {
1366 isl_set_free(Set);
1367 return -1;
1368 }
1369 }
1370
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001371 Set = isl_set_remove_divs(Set);
1372
Johannes Doerfertb164c792014-09-18 11:17:17 +00001373 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1374 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1375
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001376 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1377 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1378
Johannes Doerfertb164c792014-09-18 11:17:17 +00001379 // Adjust the last dimension of the maximal access by one as we want to
1380 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1381 // we test during code generation might now point after the end of the
1382 // allocated array but we will never dereference it anyway.
1383 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1384 "Assumed at least one output dimension");
1385 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1386 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1387 OneAff = isl_aff_zero_on_domain(
1388 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1389 OneAff = isl_aff_add_constant_si(OneAff, 1);
1390 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1391 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1392
1393 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1394
1395 isl_set_free(Set);
1396 return 0;
1397}
1398
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001399static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1400 isl_set *Domain = MA->getStatement()->getDomain();
1401 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1402 return isl_set_reset_tuple_id(Domain);
1403}
1404
Johannes Doerfert9143d672014-09-27 11:02:39 +00001405bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001406 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001407 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001408 // for all memory accesses inside the SCoP.
1409 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001410 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001411 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001412 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001413 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001414 // if their access domains intersect, otherwise they are in different
1415 // ones.
Johannes Doerfert13771732014-10-01 12:40:46 +00001416 // o) We split groups such that they contain at most one read only base
1417 // address.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001418 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfertb164c792014-09-18 11:17:17 +00001419 // and maximal accesses to each array in this group.
1420 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1421
1422 AliasSetTracker AST(AA);
1423
1424 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001425 DenseSet<Value *> HasWriteAccess;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001426 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001427
1428 // Skip statements with an empty domain as they will never be executed.
1429 isl_set *StmtDomain = Stmt->getDomain();
1430 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1431 isl_set_free(StmtDomain);
1432 if (StmtDomainEmpty)
1433 continue;
1434
Johannes Doerfertb164c792014-09-18 11:17:17 +00001435 for (MemoryAccess *MA : *Stmt) {
1436 if (MA->isScalar())
1437 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001438 if (!MA->isRead())
1439 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001440 Instruction *Acc = MA->getAccessInstruction();
1441 PtrToAcc[getPointerOperand(*Acc)] = MA;
1442 AST.add(Acc);
1443 }
1444 }
1445
1446 SmallVector<AliasGroupTy, 4> AliasGroups;
1447 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001448 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001449 continue;
1450 AliasGroupTy AG;
1451 for (auto PR : AS)
1452 AG.push_back(PtrToAcc[PR.getValue()]);
1453 assert(AG.size() > 1 &&
1454 "Alias groups should contain at least two accesses");
1455 AliasGroups.push_back(std::move(AG));
1456 }
1457
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001458 // Split the alias groups based on their domain.
1459 for (unsigned u = 0; u < AliasGroups.size(); u++) {
1460 AliasGroupTy NewAG;
1461 AliasGroupTy &AG = AliasGroups[u];
1462 AliasGroupTy::iterator AGI = AG.begin();
1463 isl_set *AGDomain = getAccessDomain(*AGI);
1464 while (AGI != AG.end()) {
1465 MemoryAccess *MA = *AGI;
1466 isl_set *MADomain = getAccessDomain(MA);
1467 if (isl_set_is_disjoint(AGDomain, MADomain)) {
1468 NewAG.push_back(MA);
1469 AGI = AG.erase(AGI);
1470 isl_set_free(MADomain);
1471 } else {
1472 AGDomain = isl_set_union(AGDomain, MADomain);
1473 AGI++;
1474 }
1475 }
1476 if (NewAG.size() > 1)
1477 AliasGroups.push_back(std::move(NewAG));
1478 isl_set_free(AGDomain);
1479 }
1480
Johannes Doerfert13771732014-10-01 12:40:46 +00001481 DenseMap<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
1482 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
1483 for (AliasGroupTy &AG : AliasGroups) {
1484 NonReadOnlyBaseValues.clear();
1485 ReadOnlyPairs.clear();
1486
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001487 if (AG.size() < 2) {
1488 AG.clear();
1489 continue;
1490 }
1491
Johannes Doerfert13771732014-10-01 12:40:46 +00001492 for (auto II = AG.begin(); II != AG.end();) {
1493 Value *BaseAddr = (*II)->getBaseAddr();
1494 if (HasWriteAccess.count(BaseAddr)) {
1495 NonReadOnlyBaseValues.insert(BaseAddr);
1496 II++;
1497 } else {
1498 ReadOnlyPairs[BaseAddr].insert(*II);
1499 II = AG.erase(II);
1500 }
1501 }
1502
1503 // If we don't have read only pointers check if there are at least two
1504 // non read only pointers, otherwise clear the alias group.
1505 if (ReadOnlyPairs.empty()) {
1506 if (NonReadOnlyBaseValues.size() <= 1)
1507 AG.clear();
1508 continue;
1509 }
1510
1511 // If we don't have non read only pointers clear the alias group.
1512 if (NonReadOnlyBaseValues.empty()) {
1513 AG.clear();
1514 continue;
1515 }
1516
1517 // If we have both read only and non read only base pointers we combine
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001518 // the non read only ones with exactly one read only one at a time into a
Johannes Doerfert13771732014-10-01 12:40:46 +00001519 // new alias group and clear the old alias group in the end.
1520 for (const auto &ReadOnlyPair : ReadOnlyPairs) {
1521 AliasGroupTy AGNonReadOnly = AG;
1522 for (MemoryAccess *MA : ReadOnlyPair.second)
1523 AGNonReadOnly.push_back(MA);
1524 AliasGroups.push_back(std::move(AGNonReadOnly));
1525 }
1526 AG.clear();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001527 }
1528
Johannes Doerfert9143d672014-09-27 11:02:39 +00001529 bool Valid = true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001530 for (AliasGroupTy &AG : AliasGroups) {
Johannes Doerfert13771732014-10-01 12:40:46 +00001531 if (AG.empty())
1532 continue;
1533
Johannes Doerfertb164c792014-09-18 11:17:17 +00001534 MinMaxVectorTy *MinMaxAccesses = new MinMaxVectorTy();
1535 MinMaxAccesses->reserve(AG.size());
1536
1537 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
1538 for (MemoryAccess *MA : AG)
1539 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
1540 Accesses = isl_union_map_intersect_domain(Accesses, getDomains());
1541
1542 isl_union_set *Locations = isl_union_map_range(Accesses);
1543 Locations = isl_union_set_intersect_params(Locations, getAssumedContext());
1544 Locations = isl_union_set_coalesce(Locations);
1545 Locations = isl_union_set_detect_equalities(Locations);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001546 Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
1547 MinMaxAccesses));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001548 isl_union_set_free(Locations);
Johannes Doerfertb164c792014-09-18 11:17:17 +00001549 MinMaxAliasGroups.push_back(MinMaxAccesses);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001550
1551 if (!Valid)
1552 break;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001553 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001554
1555 return Valid;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001556}
1557
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001558static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI) {
1559 unsigned MinLD = INT_MAX, MaxLD = 0;
1560 for (BasicBlock *BB : R.blocks()) {
1561 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00001562 if (!R.contains(L))
1563 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001564 unsigned LD = L->getLoopDepth();
1565 MinLD = std::min(MinLD, LD);
1566 MaxLD = std::max(MaxLD, LD);
1567 }
1568 }
1569
1570 // Handle the case that there is no loop in the SCoP first.
1571 if (MaxLD == 0)
1572 return 1;
1573
1574 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
1575 assert(MaxLD >= MinLD &&
1576 "Maximal loop depth was smaller than mininaml loop depth?");
1577 return MaxLD - MinLD + 1;
1578}
1579
Tobias Grosser3f296192015-01-01 23:01:11 +00001580void Scop::dropConstantScheduleDims() {
1581 isl_union_map *FullSchedule = getSchedule();
1582
1583 if (isl_union_map_n_map(FullSchedule) == 0) {
1584 isl_union_map_free(FullSchedule);
1585 return;
1586 }
1587
1588 isl_set *ScheduleSpace =
1589 isl_set_from_union_set(isl_union_map_range(FullSchedule));
1590 isl_map *DropDimMap = isl_set_identity(isl_set_copy(ScheduleSpace));
1591
1592 int NumDimsDropped = 0;
1593 for (unsigned i = 0; i < isl_set_dim(ScheduleSpace, isl_dim_set); i++)
1594 if (i % 2 == 0) {
1595 isl_val *FixedVal =
1596 isl_set_plain_get_val_if_fixed(ScheduleSpace, isl_dim_set, i);
1597 if (isl_val_is_int(FixedVal)) {
1598 DropDimMap =
1599 isl_map_project_out(DropDimMap, isl_dim_out, i - NumDimsDropped, 1);
1600 NumDimsDropped++;
1601 }
1602 isl_val_free(FixedVal);
1603 }
1604
Tobias Grosser3f296192015-01-01 23:01:11 +00001605 for (auto *S : *this) {
1606 isl_map *Schedule = S->getScattering();
1607 Schedule = isl_map_apply_range(Schedule, isl_map_copy(DropDimMap));
1608 S->setScattering(Schedule);
1609 }
1610 isl_set_free(ScheduleSpace);
1611 isl_map_free(DropDimMap);
1612}
1613
Tobias Grosser0e27e242011-10-06 00:03:48 +00001614Scop::Scop(TempScop &tempScop, LoopInfo &LI, ScalarEvolution &ScalarEvolution,
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001615 ScopDetection &SD, isl_ctx *Context)
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001616 : SE(&ScalarEvolution), R(tempScop.getMaxRegion()), IsOptimized(false),
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001617 MaxLoopDepth(getMaxLoopDepthInRegion(tempScop.getMaxRegion(), LI)) {
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001618 IslCtx = Context;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001619
Tobias Grosser6be480c2011-11-08 15:41:13 +00001620 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001621
Tobias Grosserabfbe632013-02-05 12:09:06 +00001622 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001623 SmallVector<unsigned, 8> Scatter;
1624
1625 Scatter.assign(MaxLoopDepth + 1, 0);
1626
1627 // Build the iteration domain, access functions and scattering functions
1628 // traversing the region tree.
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001629 buildScop(tempScop, getRegion(), NestLoops, Scatter, LI, SD);
Tobias Grosser75805372011-04-29 06:27:02 +00001630
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001631 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001632 addParameterBounds();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001633 simplifyAssumedContext();
Tobias Grosser3f296192015-01-01 23:01:11 +00001634 dropConstantScheduleDims();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001635
Tobias Grosser75805372011-04-29 06:27:02 +00001636 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1637}
1638
1639Scop::~Scop() {
1640 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001641 isl_set_free(AssumedContext);
Tobias Grosser75805372011-04-29 06:27:02 +00001642
1643 // Free the statements;
Tobias Grosser083d3d32014-06-28 08:59:45 +00001644 for (ScopStmt *Stmt : *this)
1645 delete Stmt;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001646
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001647 // Free the ScopArrayInfo objects.
1648 for (auto &ScopArrayInfoPair : ScopArrayInfoMap)
1649 delete ScopArrayInfoPair.second;
1650
Johannes Doerfertb164c792014-09-18 11:17:17 +00001651 // Free the alias groups
1652 for (MinMaxVectorTy *MinMaxAccesses : MinMaxAliasGroups) {
1653 for (MinMaxAccessTy &MMA : *MinMaxAccesses) {
1654 isl_pw_multi_aff_free(MMA.first);
1655 isl_pw_multi_aff_free(MMA.second);
1656 }
1657 delete MinMaxAccesses;
1658 }
Tobias Grosser75805372011-04-29 06:27:02 +00001659}
1660
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001661const ScopArrayInfo *
1662Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
1663 const SmallVector<const SCEV *, 4> &Sizes) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001664 const ScopArrayInfo *&SAI = ScopArrayInfoMap[BasePtr];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001665 if (!SAI)
1666 SAI = new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001667 return SAI;
1668}
1669
1670const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr) {
1671 const SCEV *PtrSCEV = SE->getSCEV(BasePtr);
1672 const SCEVUnknown *PtrBaseSCEV =
1673 cast<SCEVUnknown>(SE->getPointerBase(PtrSCEV));
1674 const ScopArrayInfo *SAI = ScopArrayInfoMap[PtrBaseSCEV->getValue()];
1675 assert(SAI && "No ScopArrayInfo available for this base pointer");
1676 return SAI;
1677}
1678
Tobias Grosser74394f02013-01-14 22:40:23 +00001679std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001680std::string Scop::getAssumedContextStr() const {
1681 return stringFromIslObj(AssumedContext);
1682}
Tobias Grosser75805372011-04-29 06:27:02 +00001683
1684std::string Scop::getNameStr() const {
1685 std::string ExitName, EntryName;
1686 raw_string_ostream ExitStr(ExitName);
1687 raw_string_ostream EntryStr(EntryName);
1688
Tobias Grosserf240b482014-01-09 10:42:15 +00001689 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001690 EntryStr.str();
1691
1692 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001693 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001694 ExitStr.str();
1695 } else
1696 ExitName = "FunctionExit";
1697
1698 return EntryName + "---" + ExitName;
1699}
1700
Tobias Grosser74394f02013-01-14 22:40:23 +00001701__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001702__isl_give isl_space *Scop::getParamSpace() const {
1703 return isl_set_get_space(this->Context);
1704}
1705
Tobias Grossere86109f2013-10-29 21:05:49 +00001706__isl_give isl_set *Scop::getAssumedContext() const {
1707 return isl_set_copy(AssumedContext);
1708}
1709
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001710void Scop::addAssumption(__isl_take isl_set *Set) {
1711 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001712 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001713}
1714
Tobias Grosser75805372011-04-29 06:27:02 +00001715void Scop::printContext(raw_ostream &OS) const {
1716 OS << "Context:\n";
1717
1718 if (!Context) {
1719 OS.indent(4) << "n/a\n\n";
1720 return;
1721 }
1722
1723 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001724
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001725 OS.indent(4) << "Assumed Context:\n";
1726 if (!AssumedContext) {
1727 OS.indent(4) << "n/a\n\n";
1728 return;
1729 }
1730
1731 OS.indent(4) << getAssumedContextStr() << "\n";
1732
Tobias Grosser083d3d32014-06-28 08:59:45 +00001733 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001734 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001735 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1736 }
Tobias Grosser75805372011-04-29 06:27:02 +00001737}
1738
Johannes Doerfertb164c792014-09-18 11:17:17 +00001739void Scop::printAliasAssumptions(raw_ostream &OS) const {
1740 OS.indent(4) << "Alias Groups (" << MinMaxAliasGroups.size() << "):\n";
1741 if (MinMaxAliasGroups.empty()) {
1742 OS.indent(8) << "n/a\n";
1743 return;
1744 }
1745 for (MinMaxVectorTy *MinMaxAccesses : MinMaxAliasGroups) {
1746 OS.indent(8) << "[[";
1747 for (MinMaxAccessTy &MinMacAccess : *MinMaxAccesses)
1748 OS << " <" << MinMacAccess.first << ", " << MinMacAccess.second << ">";
1749 OS << " ]]\n";
1750 }
1751}
1752
Tobias Grosser75805372011-04-29 06:27:02 +00001753void Scop::printStatements(raw_ostream &OS) const {
1754 OS << "Statements {\n";
1755
Tobias Grosser083d3d32014-06-28 08:59:45 +00001756 for (ScopStmt *Stmt : *this)
1757 OS.indent(4) << *Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001758
1759 OS.indent(4) << "}\n";
1760}
1761
Tobias Grosser75805372011-04-29 06:27:02 +00001762void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00001763 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
1764 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00001765 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00001766 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001767 printContext(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001768 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001769 printStatements(OS.indent(4));
1770}
1771
1772void Scop::dump() const { print(dbgs()); }
1773
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001774isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00001775
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001776__isl_give isl_union_set *Scop::getDomains() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001777 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001778
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001779 for (ScopStmt *Stmt : *this)
1780 Domain = isl_union_set_add_set(Domain, Stmt->getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001781
1782 return Domain;
1783}
1784
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001785__isl_give isl_union_map *Scop::getMustWrites() {
1786 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1787
1788 for (ScopStmt *Stmt : *this) {
1789 for (MemoryAccess *MA : *Stmt) {
1790 if (!MA->isMustWrite())
1791 continue;
1792
1793 isl_set *Domain = Stmt->getDomain();
1794 isl_map *AccessDomain = MA->getAccessRelation();
1795 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1796 Write = isl_union_map_add_map(Write, AccessDomain);
1797 }
1798 }
1799 return isl_union_map_coalesce(Write);
1800}
1801
1802__isl_give isl_union_map *Scop::getMayWrites() {
1803 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1804
1805 for (ScopStmt *Stmt : *this) {
1806 for (MemoryAccess *MA : *Stmt) {
1807 if (!MA->isMayWrite())
1808 continue;
1809
1810 isl_set *Domain = Stmt->getDomain();
1811 isl_map *AccessDomain = MA->getAccessRelation();
1812 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1813 Write = isl_union_map_add_map(Write, AccessDomain);
1814 }
1815 }
1816 return isl_union_map_coalesce(Write);
1817}
1818
Tobias Grosser37eb4222014-02-20 21:43:54 +00001819__isl_give isl_union_map *Scop::getWrites() {
1820 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1821
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001822 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001823 for (MemoryAccess *MA : *Stmt) {
1824 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001825 continue;
1826
1827 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001828 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001829 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1830 Write = isl_union_map_add_map(Write, AccessDomain);
1831 }
1832 }
1833 return isl_union_map_coalesce(Write);
1834}
1835
1836__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001837 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001838
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001839 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001840 for (MemoryAccess *MA : *Stmt) {
1841 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001842 continue;
1843
1844 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001845 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001846
1847 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1848 Read = isl_union_map_add_map(Read, AccessDomain);
1849 }
1850 }
1851 return isl_union_map_coalesce(Read);
1852}
1853
1854__isl_give isl_union_map *Scop::getSchedule() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001855 isl_union_map *Schedule = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001856
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001857 for (ScopStmt *Stmt : *this)
Tobias Grosser37eb4222014-02-20 21:43:54 +00001858 Schedule = isl_union_map_add_map(Schedule, Stmt->getScattering());
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001859
Tobias Grosser37eb4222014-02-20 21:43:54 +00001860 return isl_union_map_coalesce(Schedule);
1861}
1862
1863bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
1864 bool Changed = false;
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001865 for (ScopStmt *Stmt : *this) {
Tobias Grosser37eb4222014-02-20 21:43:54 +00001866 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt->getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001867 isl_union_set *NewStmtDomain = isl_union_set_intersect(
1868 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
1869
1870 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
1871 isl_union_set_free(StmtDomain);
1872 isl_union_set_free(NewStmtDomain);
1873 continue;
1874 }
1875
1876 Changed = true;
1877
1878 isl_union_set_free(StmtDomain);
1879 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
1880
1881 if (isl_union_set_is_empty(NewStmtDomain)) {
1882 Stmt->restrictDomain(isl_set_empty(Stmt->getDomainSpace()));
1883 isl_union_set_free(NewStmtDomain);
1884 } else
1885 Stmt->restrictDomain(isl_set_from_union_set(NewStmtDomain));
1886 }
1887 isl_union_set_free(Domain);
1888 return Changed;
1889}
1890
Tobias Grosser75805372011-04-29 06:27:02 +00001891ScalarEvolution *Scop::getSE() const { return SE; }
1892
1893bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
1894 if (tempScop.getAccessFunctions(BB))
1895 return false;
1896
1897 return true;
1898}
1899
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001900void Scop::addScopStmt(BasicBlock *BB, Region *R, TempScop &tempScop,
1901 const Region &CurRegion,
1902 SmallVectorImpl<Loop *> &NestLoops,
1903 SmallVectorImpl<unsigned> &Scatter) {
1904 ScopStmt *Stmt;
1905
1906 if (BB) {
1907 Stmt = new ScopStmt(*this, tempScop, CurRegion, *BB, NestLoops, Scatter);
1908 StmtMap[BB] = Stmt;
1909 } else {
1910 assert(R && "Either a basic block or a region is needed to "
1911 "create a new SCoP stmt.");
1912 Stmt = new ScopStmt(*this, tempScop, CurRegion, *R, NestLoops, Scatter);
1913 for (BasicBlock *BB : R->blocks())
1914 StmtMap[BB] = Stmt;
1915 }
1916
1917 // Insert all statements into the statement map and the statement vector.
1918 Stmts.push_back(Stmt);
1919
1920 // Increasing the Scattering function is OK for the moment, because
1921 // we are using a depth first iterator and the program is well structured.
1922 ++Scatter[NestLoops.size()];
1923}
1924
Tobias Grosser74394f02013-01-14 22:40:23 +00001925void Scop::buildScop(TempScop &tempScop, const Region &CurRegion,
1926 SmallVectorImpl<Loop *> &NestLoops,
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001927 SmallVectorImpl<unsigned> &Scatter, LoopInfo &LI,
1928 ScopDetection &SD) {
1929 if (SD.isNonAffineSubRegion(&CurRegion, &getRegion()))
1930 return addScopStmt(nullptr, const_cast<Region *>(&CurRegion), tempScop,
1931 CurRegion, NestLoops, Scatter);
1932
Tobias Grosser75805372011-04-29 06:27:02 +00001933 Loop *L = castToLoop(CurRegion, LI);
1934
1935 if (L)
1936 NestLoops.push_back(L);
1937
1938 unsigned loopDepth = NestLoops.size();
1939 assert(Scatter.size() > loopDepth && "Scatter not big enough!");
1940
1941 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00001942 E = CurRegion.element_end();
1943 I != E; ++I)
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001944 if (I->isSubRegion()) {
1945 buildScop(tempScop, *I->getNodeAs<Region>(), NestLoops, Scatter, LI, SD);
1946 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001947 BasicBlock *BB = I->getNodeAs<BasicBlock>();
1948
1949 if (isTrivialBB(BB, tempScop))
1950 continue;
1951
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001952 addScopStmt(BB, nullptr, tempScop, CurRegion, NestLoops, Scatter);
Tobias Grosser75805372011-04-29 06:27:02 +00001953 }
1954
1955 if (!L)
1956 return;
1957
1958 // Exiting a loop region.
1959 Scatter[loopDepth] = 0;
1960 NestLoops.pop_back();
Tobias Grosser74394f02013-01-14 22:40:23 +00001961 ++Scatter[loopDepth - 1];
Tobias Grosser75805372011-04-29 06:27:02 +00001962}
1963
Johannes Doerfert7c494212014-10-31 23:13:39 +00001964ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
1965 const auto &StmtMapIt = StmtMap.find(BB);
1966 if (StmtMapIt == StmtMap.end())
1967 return nullptr;
1968 return StmtMapIt->second;
1969}
1970
Tobias Grosser75805372011-04-29 06:27:02 +00001971//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00001972ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
1973 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00001974 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001975}
1976
1977ScopInfo::~ScopInfo() {
1978 clear();
1979 isl_ctx_free(ctx);
1980}
1981
Tobias Grosser75805372011-04-29 06:27:02 +00001982void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001983 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001984 AU.addRequired<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001985 AU.addRequired<ScalarEvolution>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001986 AU.addRequired<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00001987 AU.addRequired<TempScopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001988 AU.addRequired<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00001989 AU.setPreservesAll();
1990}
1991
1992bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001993 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001994 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001995 ScopDetection &SD = getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00001996 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1997
1998 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop(R);
1999
2000 // This region is no Scop.
2001 if (!tempScop) {
Tobias Grosserc98a8fc2014-11-14 11:12:31 +00002002 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002003 return false;
2004 }
2005
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002006 scop = new Scop(*tempScop, LI, SE, SD, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00002007
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002008 if (!PollyUseRuntimeAliasChecks) {
2009 // Statistics.
2010 ++ScopFound;
2011 if (scop->getMaxLoopDepth() > 0)
2012 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002013 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002014 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002015
Johannes Doerfert9143d672014-09-27 11:02:39 +00002016 // If a problem occurs while building the alias groups we need to delete
2017 // this SCoP and pretend it wasn't valid in the first place.
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002018 if (scop->buildAliasGroups(AA)) {
2019 // Statistics.
2020 ++ScopFound;
2021 if (scop->getMaxLoopDepth() > 0)
2022 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002023 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002024 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002025
2026 DEBUG(dbgs()
2027 << "\n\nNOTE: Run time checks for " << scop->getNameStr()
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002028 << " could not be created as the number of parameters involved is too "
Johannes Doerfert9143d672014-09-27 11:02:39 +00002029 "high. The SCoP will be "
2030 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust the "
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002031 "maximal number of parameters but be advised that the compile time "
Johannes Doerfert9143d672014-09-27 11:02:39 +00002032 "might increase exponentially.\n\n");
2033
2034 delete scop;
2035 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002036 return false;
2037}
2038
2039char ScopInfo::ID = 0;
2040
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002041Pass *polly::createScopInfoPass() { return new ScopInfo(); }
2042
Tobias Grosser73600b82011-10-08 00:30:40 +00002043INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
2044 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002045 false);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002046INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Chandler Carruthf5579872015-01-17 14:16:56 +00002047INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00002048INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002049INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002050INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002051INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Tobias Grosser73600b82011-10-08 00:30:40 +00002052INITIALIZE_PASS_END(ScopInfo, "polly-scops",
2053 "Polly - Create polyhedral description of Scops", false,
2054 false)