blob: 6fa73f061d00a047b27e294c3b8f2554abf11fed [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
15// This represantation is shared among several tools in the polyhedral
16// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Sebastian Pop27c10c62013-03-22 22:07:43 +000020#include "polly/CodeGen/BlockGenerators.h"
Tobias Grosser75805372011-04-29 06:27:02 +000021#include "polly/LinkAllPasses.h"
Sebastian Pop27c10c62013-03-22 22:07:43 +000022#include "polly/ScopInfo.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000023#include "polly/Options.h"
Tobias Grosser75805372011-04-29 06:27:02 +000024#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000025#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000026#include "polly/Support/ScopHelper.h"
Sebastian Pop27c10c62013-03-22 22:07:43 +000027#include "polly/TempScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000028#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000029#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000030#include "llvm/ADT/StringExtras.h"
Tobias Grosser83628182013-05-07 08:11:54 +000031#include "llvm/Analysis/LoopInfo.h"
32#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 Doerfert0ee1f212014-06-17 17:31:36 +000058// Multiplicative reductions can be disabled seperately as these kind of
59// 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
Tobias Grosser0695ee42013-09-17 03:30:31 +000066/// Translate a 'const SCEV *' expression in an isl_pw_aff.
Tobias Grosserabfbe632013-02-05 12:09:06 +000067struct SCEVAffinator : public SCEVVisitor<SCEVAffinator, isl_pw_aff *> {
Tobias Grosser0695ee42013-09-17 03:30:31 +000068public:
Tobias Grosser0695ee42013-09-17 03:30:31 +000069 /// @brief Translate a 'const SCEV *' to an isl_pw_aff.
70 ///
71 /// @param Stmt The location at which the scalar evolution expression
72 /// is evaluated.
73 /// @param Expr The expression that is translated.
74 static __isl_give isl_pw_aff *getPwAff(ScopStmt *Stmt, const SCEV *Expr);
75
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000076private:
Tobias Grosser3cc99742012-06-06 16:33:15 +000077 isl_ctx *Ctx;
Tobias Grosserf5338802011-10-06 00:03:35 +000078 int NbLoopSpaces;
Tobias Grosser3cc99742012-06-06 16:33:15 +000079 const Scop *S;
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000080
Tobias Grosser0695ee42013-09-17 03:30:31 +000081 SCEVAffinator(const ScopStmt *Stmt);
82 int getLoopDepth(const Loop *L);
Tobias Grosser60b54f12011-11-08 15:41:28 +000083
Tobias Grosser0695ee42013-09-17 03:30:31 +000084 __isl_give isl_pw_aff *visit(const SCEV *Expr);
85 __isl_give isl_pw_aff *visitConstant(const SCEVConstant *Expr);
86 __isl_give isl_pw_aff *visitTruncateExpr(const SCEVTruncateExpr *Expr);
87 __isl_give isl_pw_aff *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr);
88 __isl_give isl_pw_aff *visitSignExtendExpr(const SCEVSignExtendExpr *Expr);
89 __isl_give isl_pw_aff *visitAddExpr(const SCEVAddExpr *Expr);
90 __isl_give isl_pw_aff *visitMulExpr(const SCEVMulExpr *Expr);
91 __isl_give isl_pw_aff *visitUDivExpr(const SCEVUDivExpr *Expr);
92 __isl_give isl_pw_aff *visitAddRecExpr(const SCEVAddRecExpr *Expr);
93 __isl_give isl_pw_aff *visitSMaxExpr(const SCEVSMaxExpr *Expr);
94 __isl_give isl_pw_aff *visitUMaxExpr(const SCEVUMaxExpr *Expr);
95 __isl_give isl_pw_aff *visitUnknown(const SCEVUnknown *Expr);
Tobias Grosser60b54f12011-11-08 15:41:28 +000096
Tobias Grosser0695ee42013-09-17 03:30:31 +000097 friend struct SCEVVisitor<SCEVAffinator, isl_pw_aff *>;
98};
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000099
Tobias Grosser0695ee42013-09-17 03:30:31 +0000100SCEVAffinator::SCEVAffinator(const ScopStmt *Stmt)
101 : Ctx(Stmt->getIslCtx()), NbLoopSpaces(Stmt->getNumIterators()),
102 S(Stmt->getParent()) {}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000103
Tobias Grosser0695ee42013-09-17 03:30:31 +0000104__isl_give isl_pw_aff *SCEVAffinator::getPwAff(ScopStmt *Stmt,
105 const SCEV *Scev) {
106 Scop *S = Stmt->getParent();
107 const Region *Reg = &S->getRegion();
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000108
Tobias Grosser0695ee42013-09-17 03:30:31 +0000109 S->addParams(getParamsInAffineExpr(Reg, Scev, *S->getSE()));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000110
Tobias Grosser0695ee42013-09-17 03:30:31 +0000111 SCEVAffinator Affinator(Stmt);
112 return Affinator.visit(Scev);
113}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000114
Tobias Grosser0695ee42013-09-17 03:30:31 +0000115__isl_give isl_pw_aff *SCEVAffinator::visit(const SCEV *Expr) {
116 // In case the scev is a valid parameter, we do not further analyze this
117 // expression, but create a new parameter in the isl_pw_aff. This allows us
118 // to treat subexpressions that we cannot translate into an piecewise affine
119 // expression, as constant parameters of the piecewise affine expression.
120 if (isl_id *Id = S->getIdForParam(Expr)) {
121 isl_space *Space = isl_space_set_alloc(Ctx, 1, NbLoopSpaces);
122 Space = isl_space_set_dim_id(Space, isl_dim_param, 0, Id);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000123
Tobias Grosser0695ee42013-09-17 03:30:31 +0000124 isl_set *Domain = isl_set_universe(isl_space_copy(Space));
125 isl_aff *Affine = isl_aff_zero_on_domain(isl_local_space_from_space(Space));
126 Affine = isl_aff_add_coefficient_si(Affine, isl_dim_param, 0, 1);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000127
128 return isl_pw_aff_alloc(Domain, Affine);
129 }
130
Tobias Grosser0695ee42013-09-17 03:30:31 +0000131 return SCEVVisitor<SCEVAffinator, isl_pw_aff *>::visit(Expr);
132}
133
Tobias Grosser0d170132013-10-03 13:09:19 +0000134__isl_give isl_pw_aff *SCEVAffinator::visitConstant(const SCEVConstant *Expr) {
Tobias Grosser0695ee42013-09-17 03:30:31 +0000135 ConstantInt *Value = Expr->getValue();
136 isl_val *v;
137
138 // LLVM does not define if an integer value is interpreted as a signed or
139 // unsigned value. Hence, without further information, it is unknown how
140 // this value needs to be converted to GMP. At the moment, we only support
141 // signed operations. So we just interpret it as signed. Later, there are
142 // two options:
143 //
144 // 1. We always interpret any value as signed and convert the values on
145 // demand.
146 // 2. We pass down the signedness of the calculation and use it to interpret
147 // this constant correctly.
148 v = isl_valFromAPInt(Ctx, Value->getValue(), /* isSigned */ true);
149
150 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
151 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(Space));
152 isl_aff *Affine = isl_aff_zero_on_domain(ls);
153 isl_set *Domain = isl_set_universe(Space);
154
155 Affine = isl_aff_add_constant_val(Affine, v);
156
157 return isl_pw_aff_alloc(Domain, Affine);
158}
159
160__isl_give isl_pw_aff *
161SCEVAffinator::visitTruncateExpr(const SCEVTruncateExpr *Expr) {
162 llvm_unreachable("SCEVTruncateExpr not yet supported");
163}
164
165__isl_give isl_pw_aff *
166SCEVAffinator::visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
167 llvm_unreachable("SCEVZeroExtendExpr not yet supported");
168}
169
170__isl_give isl_pw_aff *
171SCEVAffinator::visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
172 // Assuming the value is signed, a sign extension is basically a noop.
173 // TODO: Reconsider this as soon as we support unsigned values.
174 return visit(Expr->getOperand());
175}
176
177__isl_give isl_pw_aff *SCEVAffinator::visitAddExpr(const SCEVAddExpr *Expr) {
178 isl_pw_aff *Sum = visit(Expr->getOperand(0));
179
180 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
181 isl_pw_aff *NextSummand = visit(Expr->getOperand(i));
182 Sum = isl_pw_aff_add(Sum, NextSummand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000183 }
184
Tobias Grosser0695ee42013-09-17 03:30:31 +0000185 // TODO: Check for NSW and NUW.
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000186
Tobias Grosser0695ee42013-09-17 03:30:31 +0000187 return Sum;
188}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000189
Tobias Grosser0695ee42013-09-17 03:30:31 +0000190__isl_give isl_pw_aff *SCEVAffinator::visitMulExpr(const SCEVMulExpr *Expr) {
191 isl_pw_aff *Product = visit(Expr->getOperand(0));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000192
Tobias Grosser0695ee42013-09-17 03:30:31 +0000193 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
194 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
195
196 if (!isl_pw_aff_is_cst(Product) && !isl_pw_aff_is_cst(NextOperand)) {
197 isl_pw_aff_free(Product);
198 isl_pw_aff_free(NextOperand);
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000199 return nullptr;
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000200 }
201
Tobias Grosser0695ee42013-09-17 03:30:31 +0000202 Product = isl_pw_aff_mul(Product, NextOperand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000203 }
204
Tobias Grosser0695ee42013-09-17 03:30:31 +0000205 // TODO: Check for NSW and NUW.
206 return Product;
207}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000208
Tobias Grosser0695ee42013-09-17 03:30:31 +0000209__isl_give isl_pw_aff *SCEVAffinator::visitUDivExpr(const SCEVUDivExpr *Expr) {
210 llvm_unreachable("SCEVUDivExpr not yet supported");
211}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000212
Tobias Grosser0695ee42013-09-17 03:30:31 +0000213__isl_give isl_pw_aff *
214SCEVAffinator::visitAddRecExpr(const SCEVAddRecExpr *Expr) {
215 assert(Expr->isAffine() && "Only affine AddRecurrences allowed");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000216
Tobias Grosser0695ee42013-09-17 03:30:31 +0000217 // Directly generate isl_pw_aff for Expr if 'start' is zero.
218 if (Expr->getStart()->isZero()) {
219 assert(S->getRegion().contains(Expr->getLoop()) &&
220 "Scop does not contain the loop referenced in this AddRec");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000221
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000222 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser0695ee42013-09-17 03:30:31 +0000223 isl_pw_aff *Step = visit(Expr->getOperand(1));
224 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
225 isl_local_space *LocalSpace = isl_local_space_from_space(Space);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000226
Tobias Grosser0695ee42013-09-17 03:30:31 +0000227 int loopDimension = getLoopDepth(Expr->getLoop());
228
229 isl_aff *LAff = isl_aff_set_coefficient_si(
230 isl_aff_zero_on_domain(LocalSpace), isl_dim_in, loopDimension, 1);
231 isl_pw_aff *LPwAff = isl_pw_aff_from_aff(LAff);
232
233 // TODO: Do we need to check for NSW and NUW?
234 return isl_pw_aff_add(Start, isl_pw_aff_mul(Step, LPwAff));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000235 }
236
Tobias Grosser0695ee42013-09-17 03:30:31 +0000237 // Translate AddRecExpr from '{start, +, inc}' into 'start + {0, +, inc}'
238 // if 'start' is not zero.
239 ScalarEvolution &SE = *S->getSE();
240 const SCEV *ZeroStartExpr = SE.getAddRecExpr(
241 SE.getConstant(Expr->getStart()->getType(), 0),
242 Expr->getStepRecurrence(SE), Expr->getLoop(), SCEV::FlagAnyWrap);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000243
Tobias Grosser0695ee42013-09-17 03:30:31 +0000244 isl_pw_aff *ZeroStartResult = visit(ZeroStartExpr);
245 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000246
Tobias Grosser0695ee42013-09-17 03:30:31 +0000247 return isl_pw_aff_add(ZeroStartResult, Start);
248}
249
250__isl_give isl_pw_aff *SCEVAffinator::visitSMaxExpr(const SCEVSMaxExpr *Expr) {
251 isl_pw_aff *Max = visit(Expr->getOperand(0));
252
253 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
254 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
255 Max = isl_pw_aff_max(Max, NextOperand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000256 }
257
Tobias Grosser0695ee42013-09-17 03:30:31 +0000258 return Max;
259}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000260
Tobias Grosser0695ee42013-09-17 03:30:31 +0000261__isl_give isl_pw_aff *SCEVAffinator::visitUMaxExpr(const SCEVUMaxExpr *Expr) {
262 llvm_unreachable("SCEVUMaxExpr not yet supported");
263}
264
265__isl_give isl_pw_aff *SCEVAffinator::visitUnknown(const SCEVUnknown *Expr) {
266 llvm_unreachable("Unknowns are always parameters");
267}
268
269int SCEVAffinator::getLoopDepth(const Loop *L) {
270 Loop *outerLoop = S->getRegion().outermostLoopInRegion(const_cast<Loop *>(L));
271 assert(outerLoop && "Scop does not contain this loop");
272 return L->getLoopDepth() - outerLoop->getLoopDepth();
273}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000274
Johannes Doerfertf6183392014-07-01 20:52:51 +0000275/// @brief Return the reduction type for a given binary operator
276static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
277 const Instruction *Load) {
278 if (!BinOp)
279 return MemoryAccess::RT_NONE;
280 switch (BinOp->getOpcode()) {
281 case Instruction::FAdd:
282 if (!BinOp->hasUnsafeAlgebra())
283 return MemoryAccess::RT_NONE;
284 // Fall through
285 case Instruction::Add:
286 return MemoryAccess::RT_ADD;
287 case Instruction::Or:
288 return MemoryAccess::RT_BOR;
289 case Instruction::Xor:
290 return MemoryAccess::RT_BXOR;
291 case Instruction::And:
292 return MemoryAccess::RT_BAND;
293 case Instruction::FMul:
294 if (!BinOp->hasUnsafeAlgebra())
295 return MemoryAccess::RT_NONE;
296 // Fall through
297 case Instruction::Mul:
298 if (DisableMultiplicativeReductions)
299 return MemoryAccess::RT_NONE;
300 return MemoryAccess::RT_MUL;
301 default:
302 return MemoryAccess::RT_NONE;
303 }
304}
Tobias Grosser75805372011-04-29 06:27:02 +0000305//===----------------------------------------------------------------------===//
306
307MemoryAccess::~MemoryAccess() {
Tobias Grosser54a86e62011-08-18 06:31:46 +0000308 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000309 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000310}
311
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000312isl_id *MemoryAccess::getArrayId() const {
313 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
314}
315
Tobias Grosser5d453812011-10-06 00:04:11 +0000316isl_map *MemoryAccess::getAccessRelation() const {
317 return isl_map_copy(AccessRelation);
318}
319
320std::string MemoryAccess::getAccessRelationStr() const {
321 return stringFromIslObj(AccessRelation);
322}
323
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000324__isl_give isl_space *MemoryAccess::getAccessRelationSpace() const {
325 return isl_map_get_space(AccessRelation);
326}
327
Tobias Grosser5d453812011-10-06 00:04:11 +0000328isl_map *MemoryAccess::getNewAccessRelation() const {
329 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000330}
331
332isl_basic_map *MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000333 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000334 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000335
Tobias Grosser084d8f72012-05-29 09:29:44 +0000336 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000337 isl_basic_set_universe(Statement->getDomainSpace()),
338 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000339}
340
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000341// Formalize no out-of-bound access assumption
342//
343// When delinearizing array accesses we optimistically assume that the
344// delinearized accesses do not access out of bound locations (the subscript
345// expression of each array evaluates for each statement instance that is
346// executed to a value that is larger than zero and strictly smaller than the
347// size of the corresponding dimension). The only exception is the outermost
348// dimension for which we do not assume any upper bound. At this point we
349// formalize this assumption to ensure that at code generation time the relevant
350// run-time checks can be generated.
351//
352// To find the set of constraints necessary to avoid out of bound accesses, we
353// first build the set of data locations that are not within array bounds. We
354// then apply the reverse access relation to obtain the set of iterations that
355// may contain invalid accesses and reduce this set of iterations to the ones
356// that are actually executed by intersecting them with the domain of the
357// statement. If we now project out all loop dimensions, we obtain a set of
358// parameters that may cause statement instances to be executed that may
359// possibly yield out of bound memory accesses. The complement of these
360// constraints is the set of constraints that needs to be assumed to ensure such
361// statement instances are never executed.
362void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
363 isl_space *Space = isl_space_range(getAccessRelationSpace());
364 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
365 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
366 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
367 isl_pw_aff *Var =
368 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
369 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
370
371 isl_set *DimOutside;
372
373 if (i == 0) {
374 DimOutside = isl_pw_aff_lt_set(Var, Zero);
375 } else {
376 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
377 isl_pw_aff *SizeE =
378 SCEVAffinator::getPwAff(Statement, Access.Sizes[i - 1]);
379
380 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
381 Statement->getNumIterators());
382 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
383 isl_space_dim(Space, isl_dim_set));
384 SizeE = isl_pw_aff_set_tuple_id(
385 SizeE, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
386
387 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
388 }
389
390 Outside = isl_set_union(Outside, DimOutside);
391 }
392
393 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
394 Outside = isl_set_intersect(Outside, Statement->getDomain());
395 Outside = isl_set_params(Outside);
396 Outside = isl_set_complement(Outside);
397 Statement->getParent()->addAssumption(Outside);
398 isl_space_free(Space);
399}
400
Hongbin Zhengcea35f62012-07-06 06:47:03 +0000401MemoryAccess::MemoryAccess(const IRAccess &Access, const Instruction *AccInst,
Tobias Grosserabfbe632013-02-05 12:09:06 +0000402 ScopStmt *Statement)
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000403 : Statement(Statement), Inst(AccInst), newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000404
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000405 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000406 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000407 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000408 isl_id *BaseAddrId = isl_id_alloc(Ctx, getBaseName().c_str(), nullptr);
Tobias Grosser5683df42011-11-09 22:34:34 +0000409
Tobias Grossera1879642011-12-20 10:43:14 +0000410 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000411 // We overapproximate non-affine accesses with a possible access to the
412 // whole array. For read accesses it does not make a difference, if an
413 // access must or may happen. However, for write accesses it is important to
414 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000415 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000416 AccessRelation =
417 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000418 Type = Access.isRead() ? READ : MAY_WRITE;
Tobias Grossera1879642011-12-20 10:43:14 +0000419 return;
420 }
421
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000422 Type = Access.isRead() ? READ : MUST_WRITE;
Tobias Grosser4f967492013-06-23 05:21:18 +0000423
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000424 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000425 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000426
Tobias Grosser79baa212014-04-10 08:38:02 +0000427 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Sebastian Pop18016682014-04-08 21:20:44 +0000428 isl_pw_aff *Affine =
429 SCEVAffinator::getPwAff(Statement, Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000430
Sebastian Pop422e33f2014-06-03 18:16:31 +0000431 if (Size == 1) {
432 // For the non delinearized arrays, divide the access function of the last
433 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000434 //
435 // A stride one array access in C expressed as A[i] is expressed in
436 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
437 // two subsequent values of 'i' index two values that are stored next to
438 // each other in memory. By this division we make this characteristic
439 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000440 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000441 Affine = isl_pw_aff_scale_down_val(Affine, v);
442 }
443
444 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
445
Tobias Grosser79baa212014-04-10 08:38:02 +0000446 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000447 }
448
Tobias Grosser79baa212014-04-10 08:38:02 +0000449 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000450 AccessRelation = isl_map_set_tuple_id(
451 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000452 AccessRelation =
453 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
454
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000455 assumeNoOutOfBound(Access);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000456 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000457}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000458
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000459void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000460 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000461 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000462}
463
Johannes Doerfertf6183392014-07-01 20:52:51 +0000464raw_ostream &polly::operator<<(raw_ostream &OS,
465 MemoryAccess::ReductionType RT) {
466 switch (RT) {
467 case MemoryAccess::RT_NONE:
468 OS << "NONE";
469 break;
470 case MemoryAccess::RT_ADD:
471 OS << "ADD";
472 break;
473 case MemoryAccess::RT_MUL:
474 OS << "MUL";
475 break;
476 case MemoryAccess::RT_BOR:
477 OS << "BOR";
478 break;
479 case MemoryAccess::RT_BXOR:
480 OS << "BXOR";
481 break;
482 case MemoryAccess::RT_BAND:
483 OS << "BAND";
484 break;
485 }
486 return OS;
487}
488
Tobias Grosser75805372011-04-29 06:27:02 +0000489void MemoryAccess::print(raw_ostream &OS) const {
Tobias Grosser4f967492013-06-23 05:21:18 +0000490 switch (Type) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000491 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000492 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000493 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000494 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000495 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000496 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000497 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000498 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000499 break;
500 }
Johannes Doerfertf6183392014-07-01 20:52:51 +0000501 OS << "[Reduction Type: " << getReductionType() << "]\n";
Tobias Grosser5d453812011-10-06 00:04:11 +0000502 OS.indent(16) << getAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000503}
504
Tobias Grosser74394f02013-01-14 22:40:23 +0000505void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000506
507// Create a map in the size of the provided set domain, that maps from the
508// one element of the provided set domain to another element of the provided
509// set domain.
510// The mapping is limited to all points that are equal in all but the last
511// dimension and for which the last dimension of the input is strict smaller
512// than the last dimension of the output.
513//
514// getEqualAndLarger(set[i0, i1, ..., iX]):
515//
516// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
517// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
518//
Tobias Grosserf5338802011-10-06 00:03:35 +0000519static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000520 isl_space *Space = isl_space_map_from_set(setDomain);
521 isl_map *Map = isl_map_universe(isl_space_copy(Space));
522 isl_local_space *MapLocalSpace = isl_local_space_from_space(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000523 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000524
525 // Set all but the last dimension to be equal for the input and output
526 //
527 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
528 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000529 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000530 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000531
532 // Set the last dimension of the input to be strict smaller than the
533 // last dimension of the output.
534 //
535 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
536 //
Tobias Grosseredab1352013-06-21 06:41:31 +0000537 isl_val *v;
538 isl_ctx *Ctx = isl_map_get_ctx(Map);
Tobias Grosserf5338802011-10-06 00:03:35 +0000539 isl_constraint *c = isl_inequality_alloc(isl_local_space_copy(MapLocalSpace));
Tobias Grosseredab1352013-06-21 06:41:31 +0000540 v = isl_val_int_from_si(Ctx, -1);
541 c = isl_constraint_set_coefficient_val(c, isl_dim_in, lastDimension, v);
542 v = isl_val_int_from_si(Ctx, 1);
543 c = isl_constraint_set_coefficient_val(c, isl_dim_out, lastDimension, v);
544 v = isl_val_int_from_si(Ctx, -1);
545 c = isl_constraint_set_constant_val(c, v);
Tobias Grosser75805372011-04-29 06:27:02 +0000546
Tobias Grosserc327932c2012-02-01 14:23:36 +0000547 Map = isl_map_add_constraint(Map, c);
Tobias Grosser75805372011-04-29 06:27:02 +0000548
Tobias Grosser23b36662011-10-17 08:32:36 +0000549 isl_local_space_free(MapLocalSpace);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000550 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000551}
552
Sebastian Popa00a0292012-12-18 07:46:06 +0000553isl_set *MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000554 isl_map *S = const_cast<isl_map *>(Schedule);
Sebastian Popa00a0292012-12-18 07:46:06 +0000555 isl_map *AccessRelation = getAccessRelation();
556 isl_space *Space = isl_space_range(isl_map_get_space(S));
557 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000558
Sebastian Popa00a0292012-12-18 07:46:06 +0000559 S = isl_map_reverse(S);
560 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000561
Sebastian Popa00a0292012-12-18 07:46:06 +0000562 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
563 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
564 NextScatt = isl_map_apply_domain(NextScatt, S);
565 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000566
Sebastian Popa00a0292012-12-18 07:46:06 +0000567 isl_set *Deltas = isl_map_deltas(NextScatt);
568 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000569}
570
Sebastian Popa00a0292012-12-18 07:46:06 +0000571bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000572 int StrideWidth) const {
573 isl_set *Stride, *StrideX;
574 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000575
Sebastian Popa00a0292012-12-18 07:46:06 +0000576 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000577 StrideX = isl_set_universe(isl_set_get_space(Stride));
578 StrideX = isl_set_fix_si(StrideX, isl_dim_set, 0, StrideWidth);
579 IsStrideX = isl_set_is_equal(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000580
Tobias Grosser28dd4862012-01-24 16:42:16 +0000581 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000582 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000583
Tobias Grosser28dd4862012-01-24 16:42:16 +0000584 return IsStrideX;
585}
586
Sebastian Popa00a0292012-12-18 07:46:06 +0000587bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
588 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000589}
590
Tobias Grosser79baa212014-04-10 08:38:02 +0000591bool MemoryAccess::isScalar() const {
592 return isl_map_n_out(AccessRelation) == 0;
593}
594
Sebastian Popa00a0292012-12-18 07:46:06 +0000595bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
596 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000597}
598
Tobias Grosser5d453812011-10-06 00:04:11 +0000599void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000600 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000601 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000602}
Tobias Grosser75805372011-04-29 06:27:02 +0000603
604//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000605
Tobias Grosser74394f02013-01-14 22:40:23 +0000606isl_map *ScopStmt::getScattering() const { return isl_map_copy(Scattering); }
Tobias Grossercf3942d2011-10-06 00:04:05 +0000607
Tobias Grosser37eb4222014-02-20 21:43:54 +0000608void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
609 assert(isl_set_is_subset(NewDomain, Domain) &&
610 "New domain is not a subset of old domain!");
611 isl_set_free(Domain);
612 Domain = NewDomain;
613 Scattering = isl_map_intersect_domain(Scattering, isl_set_copy(Domain));
614}
615
Tobias Grossercf3942d2011-10-06 00:04:05 +0000616void ScopStmt::setScattering(isl_map *NewScattering) {
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000617 assert(NewScattering && "New scattering is nullptr");
Tobias Grosserb76f38532011-08-20 11:11:25 +0000618 isl_map_free(Scattering);
Tobias Grossercf3942d2011-10-06 00:04:05 +0000619 Scattering = NewScattering;
Tobias Grosserb76f38532011-08-20 11:11:25 +0000620}
621
Tobias Grosser75805372011-04-29 06:27:02 +0000622void ScopStmt::buildScattering(SmallVectorImpl<unsigned> &Scatter) {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000623 unsigned NbIterators = getNumIterators();
624 unsigned NbScatteringDims = Parent.getMaxLoopDepth() * 2 + 1;
625
Tobias Grosser084d8f72012-05-29 09:29:44 +0000626 isl_space *Space = isl_space_set_alloc(getIslCtx(), 0, NbScatteringDims);
Tobias Grosserf5338802011-10-06 00:03:35 +0000627 Space = isl_space_set_tuple_name(Space, isl_dim_out, "scattering");
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000628
Tobias Grosser084d8f72012-05-29 09:29:44 +0000629 Scattering = isl_map_from_domain_and_range(isl_set_universe(getDomainSpace()),
630 isl_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000631
632 // Loop dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000633 for (unsigned i = 0; i < NbIterators; ++i)
Tobias Grosserabfbe632013-02-05 12:09:06 +0000634 Scattering =
635 isl_map_equate(Scattering, isl_dim_out, 2 * i + 1, isl_dim_in, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000636
637 // Constant dimensions
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000638 for (unsigned i = 0; i < NbIterators + 1; ++i)
639 Scattering = isl_map_fix_si(Scattering, isl_dim_out, 2 * i, Scatter[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000640
641 // Fill scattering dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000642 for (unsigned i = 2 * NbIterators + 1; i < NbScatteringDims; ++i)
643 Scattering = isl_map_fix_si(Scattering, isl_dim_out, i, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000644
Tobias Grosser37487052011-10-06 00:03:42 +0000645 Scattering = isl_map_align_params(Scattering, Parent.getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000646}
647
648void ScopStmt::buildAccesses(TempScop &tempScop, const Region &CurRegion) {
Tobias Grosser083d3d32014-06-28 08:59:45 +0000649 for (auto &&Access : *tempScop.getAccessFunctions(BB)) {
650 MemAccs.push_back(new MemoryAccess(Access.first, Access.second, this));
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000651
652 // We do not track locations for scalar memory accesses at the moment.
653 //
654 // We do not have a use for this information at the moment. If we need this
655 // at some point, the "instruction -> access" mapping needs to be enhanced
656 // as a single instruction could then possibly perform multiple accesses.
Tobias Grosser083d3d32014-06-28 08:59:45 +0000657 if (!Access.first.isScalar()) {
658 assert(!InstructionToAccess.count(Access.second) &&
Tobias Grosser3fc91542014-02-20 21:43:45 +0000659 "Unexpected 1-to-N mapping on instruction to access map!");
Tobias Grosser083d3d32014-06-28 08:59:45 +0000660 InstructionToAccess[Access.second] = MemAccs.back();
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000661 }
Tobias Grosser75805372011-04-29 06:27:02 +0000662 }
663}
664
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000665void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000666 for (MemoryAccess *MA : *this)
667 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000668
669 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
670 Scattering = isl_map_align_params(Scattering, Parent.getParamSpace());
671}
672
Tobias Grosser65b00582011-11-08 15:41:19 +0000673__isl_give isl_set *ScopStmt::buildConditionSet(const Comparison &Comp) {
Tobias Grossera601fbd2011-11-09 22:34:44 +0000674 isl_pw_aff *L = SCEVAffinator::getPwAff(this, Comp.getLHS());
675 isl_pw_aff *R = SCEVAffinator::getPwAff(this, Comp.getRHS());
Tobias Grosser75805372011-04-29 06:27:02 +0000676
Tobias Grosserd2795d02011-08-18 07:51:40 +0000677 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000678 case ICmpInst::ICMP_EQ:
Tobias Grosser048c8792011-10-23 20:59:20 +0000679 return isl_pw_aff_eq_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000680 case ICmpInst::ICMP_NE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000681 return isl_pw_aff_ne_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000682 case ICmpInst::ICMP_SLT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000683 return isl_pw_aff_lt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000684 case ICmpInst::ICMP_SLE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000685 return isl_pw_aff_le_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000686 case ICmpInst::ICMP_SGT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000687 return isl_pw_aff_gt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000688 case ICmpInst::ICMP_SGE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000689 return isl_pw_aff_ge_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000690 case ICmpInst::ICMP_ULT:
691 case ICmpInst::ICMP_UGT:
692 case ICmpInst::ICMP_ULE:
Tobias Grosser75805372011-04-29 06:27:02 +0000693 case ICmpInst::ICMP_UGE:
Tobias Grosserd2795d02011-08-18 07:51:40 +0000694 llvm_unreachable("Unsigned comparisons not yet supported");
Tobias Grosser75805372011-04-29 06:27:02 +0000695 default:
696 llvm_unreachable("Non integer predicate not supported");
697 }
Tobias Grosser75805372011-04-29 06:27:02 +0000698}
699
Tobias Grossere19661e2011-10-07 08:46:57 +0000700__isl_give isl_set *ScopStmt::addLoopBoundsToDomain(__isl_take isl_set *Domain,
Tobias Grosser60b54f12011-11-08 15:41:28 +0000701 TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000702 isl_space *Space;
703 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000704
Tobias Grossere19661e2011-10-07 08:46:57 +0000705 Space = isl_set_get_space(Domain);
706 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000707
Tobias Grosser75805372011-04-29 06:27:02 +0000708 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000709 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000710 isl_pw_aff *IV =
711 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000712
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000713 // 0 <= IV.
714 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
715 Domain = isl_set_intersect(Domain, LowerBound);
716
717 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000718 const Loop *L = getLoopForDimension(i);
Tobias Grosser1179afa2011-11-02 21:37:51 +0000719 const SCEV *LatchExecutions = tempScop.getLoopBound(L);
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000720 isl_pw_aff *UpperBound = SCEVAffinator::getPwAff(this, LatchExecutions);
721 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
Tobias Grosser75805372011-04-29 06:27:02 +0000722 Domain = isl_set_intersect(Domain, UpperBoundSet);
723 }
724
Tobias Grosserf5338802011-10-06 00:03:35 +0000725 isl_local_space_free(LocalSpace);
Tobias Grossere19661e2011-10-07 08:46:57 +0000726 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000727}
728
Tobias Grossere602a072013-05-07 07:30:56 +0000729__isl_give isl_set *ScopStmt::addConditionsToDomain(__isl_take isl_set *Domain,
730 TempScop &tempScop,
731 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000732 const Region *TopRegion = tempScop.getMaxRegion().getParent(),
Tobias Grosserd7e58642013-04-10 06:55:45 +0000733 *CurrentRegion = &CurRegion;
Tobias Grossere19661e2011-10-07 08:46:57 +0000734 const BasicBlock *BranchingBB = BB;
Tobias Grosser75805372011-04-29 06:27:02 +0000735
Tobias Grosser75805372011-04-29 06:27:02 +0000736 do {
Tobias Grossere19661e2011-10-07 08:46:57 +0000737 if (BranchingBB != CurrentRegion->getEntry()) {
738 if (const BBCond *Condition = tempScop.getBBCond(BranchingBB))
Tobias Grosser083d3d32014-06-28 08:59:45 +0000739 for (const auto &C : *Condition) {
740 isl_set *ConditionSet = buildConditionSet(C);
Tobias Grossere19661e2011-10-07 08:46:57 +0000741 Domain = isl_set_intersect(Domain, ConditionSet);
Tobias Grosser75805372011-04-29 06:27:02 +0000742 }
743 }
Tobias Grossere19661e2011-10-07 08:46:57 +0000744 BranchingBB = CurrentRegion->getEntry();
745 CurrentRegion = CurrentRegion->getParent();
746 } while (TopRegion != CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000747
Tobias Grossere19661e2011-10-07 08:46:57 +0000748 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000749}
750
Tobias Grossere602a072013-05-07 07:30:56 +0000751__isl_give isl_set *ScopStmt::buildDomain(TempScop &tempScop,
752 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000753 isl_space *Space;
754 isl_set *Domain;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000755 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000756
757 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
758
Tobias Grosser084d8f72012-05-29 09:29:44 +0000759 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
760
Tobias Grossere19661e2011-10-07 08:46:57 +0000761 Domain = isl_set_universe(Space);
Tobias Grossere19661e2011-10-07 08:46:57 +0000762 Domain = addLoopBoundsToDomain(Domain, tempScop);
763 Domain = addConditionsToDomain(Domain, tempScop, CurRegion);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000764 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grossere19661e2011-10-07 08:46:57 +0000765
766 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000767}
768
Tobias Grosser74394f02013-01-14 22:40:23 +0000769ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Sebastian Pop860e0212013-02-15 21:26:44 +0000770 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest,
Tobias Grosser75805372011-04-29 06:27:02 +0000771 SmallVectorImpl<unsigned> &Scatter)
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000772 : Parent(parent), BB(&bb), IVS(Nest.size()), NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000773 // Setup the induction variables.
Sebastian Pop860e0212013-02-15 21:26:44 +0000774 for (unsigned i = 0, e = Nest.size(); i < e; ++i) {
Sebastian Pop27c10c62013-03-22 22:07:43 +0000775 if (!SCEVCodegen) {
776 PHINode *PN = Nest[i]->getCanonicalInductionVariable();
777 assert(PN && "Non canonical IV in Scop!");
Tobias Grosser826b2af2013-03-21 16:14:50 +0000778 IVS[i] = PN;
Sebastian Pop27c10c62013-03-22 22:07:43 +0000779 }
Sebastian Pop860e0212013-02-15 21:26:44 +0000780 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +0000781 }
782
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000783 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +0000784
Tobias Grossere19661e2011-10-07 08:46:57 +0000785 Domain = buildDomain(tempScop, CurRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000786 buildScattering(Scatter);
787 buildAccesses(tempScop, CurRegion);
Johannes Doerferte58a0122014-06-27 20:31:28 +0000788 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000789}
790
Johannes Doerferte58a0122014-06-27 20:31:28 +0000791/// @brief Collect loads which might form a reduction chain with @p StoreMA
792///
793/// Check if the stored value for @p StoreMA is a binary operator with one or
794/// two loads as operands. If the binary operand is commutative & associative,
795/// used only once (by @p StoreMA) and its load operands are also used only
796/// once, we have found a possible reduction chain. It starts at an operand
797/// load and includes the binary operator and @p StoreMA.
798///
799/// Note: We allow only one use to ensure the load and binary operator cannot
800/// escape this block or into any other store except @p StoreMA.
801void ScopStmt::collectCandiateReductionLoads(
802 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
803 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
804 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000805 return;
806
807 // Skip if there is not one binary operator between the load and the store
808 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +0000809 if (!BinOp)
810 return;
811
812 // Skip if the binary operators has multiple uses
813 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000814 return;
815
816 // Skip if the opcode of the binary operator is not commutative/associative
817 if (!BinOp->isCommutative() || !BinOp->isAssociative())
818 return;
819
Johannes Doerfert9890a052014-07-01 00:32:29 +0000820 // Skip if the binary operator is outside the current SCoP
821 if (BinOp->getParent() != Store->getParent())
822 return;
823
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000824 // Skip if it is a multiplicative reduction and we disabled them
825 if (DisableMultiplicativeReductions &&
826 (BinOp->getOpcode() == Instruction::Mul ||
827 BinOp->getOpcode() == Instruction::FMul))
828 return;
829
Johannes Doerferte58a0122014-06-27 20:31:28 +0000830 // Check the binary operator operands for a candidate load
831 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
832 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
833 if (!PossibleLoad0 && !PossibleLoad1)
834 return;
835
836 // A load is only a candidate if it cannot escape (thus has only this use)
837 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000838 if (PossibleLoad0->getParent() == Store->getParent())
839 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000840 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000841 if (PossibleLoad1->getParent() == Store->getParent())
842 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000843}
844
845/// @brief Check for reductions in this ScopStmt
846///
847/// Iterate over all store memory accesses and check for valid binary reduction
848/// like chains. For all candidates we check if they have the same base address
849/// and there are no other accesses which overlap with them. The base address
850/// check rules out impossible reductions candidates early. The overlap check,
851/// together with the "only one user" check in collectCandiateReductionLoads,
852/// guarantees that none of the intermediate results will escape during
853/// execution of the loop nest. We basically check here that no other memory
854/// access can access the same memory as the potential reduction.
855void ScopStmt::checkForReductions() {
856 SmallVector<MemoryAccess *, 2> Loads;
857 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
858
859 // First collect candidate load-store reduction chains by iterating over all
860 // stores and collecting possible reduction loads.
861 for (MemoryAccess *StoreMA : MemAccs) {
862 if (StoreMA->isRead())
863 continue;
864
865 Loads.clear();
866 collectCandiateReductionLoads(StoreMA, Loads);
867 for (MemoryAccess *LoadMA : Loads)
868 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
869 }
870
871 // Then check each possible candidate pair.
872 for (const auto &CandidatePair : Candidates) {
873 bool Valid = true;
874 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
875 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
876
877 // Skip those with obviously unequal base addresses.
878 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
879 isl_map_free(LoadAccs);
880 isl_map_free(StoreAccs);
881 continue;
882 }
883
884 // And check if the remaining for overlap with other memory accesses.
885 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
886 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
887 isl_set *AllAccs = isl_map_range(AllAccsRel);
888
889 for (MemoryAccess *MA : MemAccs) {
890 if (MA == CandidatePair.first || MA == CandidatePair.second)
891 continue;
892
893 isl_map *AccRel =
894 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
895 isl_set *Accs = isl_map_range(AccRel);
896
897 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
898 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
899 Valid = Valid && isl_set_is_empty(OverlapAccs);
900 isl_set_free(OverlapAccs);
901 }
902 }
903
904 isl_set_free(AllAccs);
905 if (!Valid)
906 continue;
907
Johannes Doerfertf6183392014-07-01 20:52:51 +0000908 const LoadInst *Load =
909 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
910 MemoryAccess::ReductionType RT =
911 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
912
Johannes Doerferte58a0122014-06-27 20:31:28 +0000913 // If no overlapping access was found we mark the load and store as
914 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000915 CandidatePair.first->markAsReductionLike(RT);
916 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +0000917 }
Tobias Grosser75805372011-04-29 06:27:02 +0000918}
919
Tobias Grosser74394f02013-01-14 22:40:23 +0000920std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +0000921
922std::string ScopStmt::getScatteringStr() const {
Tobias Grossercf3942d2011-10-06 00:04:05 +0000923 return stringFromIslObj(Scattering);
Tobias Grosser75805372011-04-29 06:27:02 +0000924}
925
Tobias Grosser74394f02013-01-14 22:40:23 +0000926unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +0000927
928unsigned ScopStmt::getNumIterators() const {
929 // The final read has one dimension with one element.
930 if (!BB)
931 return 1;
932
Sebastian Pop860e0212013-02-15 21:26:44 +0000933 return NestLoops.size();
Tobias Grosser75805372011-04-29 06:27:02 +0000934}
935
936unsigned ScopStmt::getNumScattering() const {
937 return isl_map_dim(Scattering, isl_dim_out);
938}
939
940const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
941
Tobias Grosserabfbe632013-02-05 12:09:06 +0000942const PHINode *
943ScopStmt::getInductionVariableForDimension(unsigned Dimension) const {
Sebastian Popf30d3b22013-02-15 21:26:48 +0000944 return IVS[Dimension];
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000945}
946
947const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +0000948 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +0000949}
950
Tobias Grosser74394f02013-01-14 22:40:23 +0000951isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +0000952
Tobias Grosser74394f02013-01-14 22:40:23 +0000953isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +0000954
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000955isl_space *ScopStmt::getDomainSpace() const {
956 return isl_set_get_space(Domain);
957}
958
Tobias Grosser74394f02013-01-14 22:40:23 +0000959isl_id *ScopStmt::getDomainId() const { return isl_set_get_tuple_id(Domain); }
Tobias Grossercd95b772012-08-30 11:49:38 +0000960
Tobias Grosser75805372011-04-29 06:27:02 +0000961ScopStmt::~ScopStmt() {
962 while (!MemAccs.empty()) {
963 delete MemAccs.back();
964 MemAccs.pop_back();
965 }
966
967 isl_set_free(Domain);
968 isl_map_free(Scattering);
969}
970
971void ScopStmt::print(raw_ostream &OS) const {
972 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000973 OS.indent(12) << "Domain :=\n";
974
975 if (Domain) {
976 OS.indent(16) << getDomainStr() << ";\n";
977 } else
978 OS.indent(16) << "n/a\n";
979
980 OS.indent(12) << "Scattering :=\n";
981
982 if (Domain) {
983 OS.indent(16) << getScatteringStr() << ";\n";
984 } else
985 OS.indent(16) << "n/a\n";
986
Tobias Grosser083d3d32014-06-28 08:59:45 +0000987 for (MemoryAccess *Access : MemAccs)
988 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +0000989}
990
991void ScopStmt::dump() const { print(dbgs()); }
992
993//===----------------------------------------------------------------------===//
994/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +0000995
Tobias Grosser7ffe4e82011-11-17 12:56:10 +0000996void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +0000997 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
998 isl_set_free(Context);
999 Context = NewContext;
1000}
1001
Tobias Grosserabfbe632013-02-05 12:09:06 +00001002void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001003 for (const SCEV *Parameter : NewParameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001004 if (ParameterIds.find(Parameter) != ParameterIds.end())
1005 continue;
1006
1007 int dimension = Parameters.size();
1008
1009 Parameters.push_back(Parameter);
1010 ParameterIds[Parameter] = dimension;
1011 }
1012}
1013
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001014__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1015 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001016
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001017 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001018 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001019
Tobias Grosser8f99c162011-11-15 11:38:55 +00001020 std::string ParameterName;
1021
1022 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1023 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001024 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001025 }
1026
1027 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001028 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001029
Tobias Grosser20532b82014-04-11 17:56:49 +00001030 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1031 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001032}
Tobias Grosser75805372011-04-29 06:27:02 +00001033
Tobias Grosser6be480c2011-11-08 15:41:13 +00001034void Scop::buildContext() {
1035 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001036 Context = isl_set_universe(isl_space_copy(Space));
1037 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001038}
1039
Tobias Grosser18daaca2012-05-22 10:47:27 +00001040void Scop::addParameterBounds() {
1041 for (unsigned i = 0; i < isl_set_dim(Context, isl_dim_param); ++i) {
Tobias Grosseredab1352013-06-21 06:41:31 +00001042 isl_val *V;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001043 isl_id *Id;
1044 const SCEV *Scev;
1045 const IntegerType *T;
1046
1047 Id = isl_set_get_dim_id(Context, isl_dim_param, i);
Tobias Grosserabfbe632013-02-05 12:09:06 +00001048 Scev = (const SCEV *)isl_id_get_user(Id);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001049 T = dyn_cast<IntegerType>(Scev->getType());
1050 isl_id_free(Id);
1051
1052 assert(T && "Not an integer type");
1053 int Width = T->getBitWidth();
1054
Tobias Grosseredab1352013-06-21 06:41:31 +00001055 V = isl_val_int_from_si(IslCtx, Width - 1);
1056 V = isl_val_2exp(V);
1057 V = isl_val_neg(V);
1058 Context = isl_set_lower_bound_val(Context, isl_dim_param, i, V);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001059
Tobias Grosseredab1352013-06-21 06:41:31 +00001060 V = isl_val_int_from_si(IslCtx, Width - 1);
1061 V = isl_val_2exp(V);
1062 V = isl_val_sub_ui(V, 1);
1063 Context = isl_set_upper_bound_val(Context, isl_dim_param, i, V);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001064 }
1065}
1066
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001067void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001068 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001069 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001070
Tobias Grosser083d3d32014-06-28 08:59:45 +00001071 for (const auto &ParamID : ParameterIds) {
1072 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001073 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001074 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001075 }
1076
1077 // Align the parameters of all data structures to the model.
1078 Context = isl_set_align_params(Context, Space);
1079
Tobias Grosser083d3d32014-06-28 08:59:45 +00001080 for (ScopStmt *Stmt : *this)
1081 Stmt->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001082}
1083
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001084void Scop::simplifyAssumedContext() {
1085 // The parameter constraints of the iteration domains give us a set of
1086 // constraints that need to hold for all cases where at least a single
1087 // statement iteration is executed in the whole scop. We now simplify the
1088 // assumed context under the assumption that such constraints hold and at
1089 // least a single statement iteration is executed. For cases where no
1090 // statement instances are executed, the assumptions we have taken about
1091 // the executed code do not matter and can be changed.
1092 //
1093 // WARNING: This only holds if the assumptions we have taken do not reduce
1094 // the set of statement instances that are executed. Otherwise we
1095 // may run into a case where the iteration domains suggest that
1096 // for a certain set of parameter constraints no code is executed,
1097 // but in the original program some computation would have been
1098 // performed. In such a case, modifying the run-time conditions and
1099 // possibly influencing the run-time check may cause certain scops
1100 // to not be executed.
1101 //
1102 // Example:
1103 //
1104 // When delinearizing the following code:
1105 //
1106 // for (long i = 0; i < 100; i++)
1107 // for (long j = 0; j < m; j++)
1108 // A[i+p][j] = 1.0;
1109 //
1110 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
1111 // otherwise we would access out of bound data. Now, knowing that code is
1112 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1113 AssumedContext =
1114 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
1115}
1116
Tobias Grosser0e27e242011-10-06 00:03:48 +00001117Scop::Scop(TempScop &tempScop, LoopInfo &LI, ScalarEvolution &ScalarEvolution,
1118 isl_ctx *Context)
Tobias Grosserabfbe632013-02-05 12:09:06 +00001119 : SE(&ScalarEvolution), R(tempScop.getMaxRegion()),
1120 MaxLoopDepth(tempScop.getMaxLoopDepth()) {
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001121 IslCtx = Context;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001122 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001123
Tobias Grosserabfbe632013-02-05 12:09:06 +00001124 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001125 SmallVector<unsigned, 8> Scatter;
1126
1127 Scatter.assign(MaxLoopDepth + 1, 0);
1128
1129 // Build the iteration domain, access functions and scattering functions
1130 // traversing the region tree.
1131 buildScop(tempScop, getRegion(), NestLoops, Scatter, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00001132
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001133 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001134 addParameterBounds();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001135 simplifyAssumedContext();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001136
Tobias Grosser75805372011-04-29 06:27:02 +00001137 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1138}
1139
1140Scop::~Scop() {
1141 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001142 isl_set_free(AssumedContext);
Tobias Grosser75805372011-04-29 06:27:02 +00001143
1144 // Free the statements;
Tobias Grosser083d3d32014-06-28 08:59:45 +00001145 for (ScopStmt *Stmt : *this)
1146 delete Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001147}
1148
Tobias Grosser74394f02013-01-14 22:40:23 +00001149std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001150std::string Scop::getAssumedContextStr() const {
1151 return stringFromIslObj(AssumedContext);
1152}
Tobias Grosser75805372011-04-29 06:27:02 +00001153
1154std::string Scop::getNameStr() const {
1155 std::string ExitName, EntryName;
1156 raw_string_ostream ExitStr(ExitName);
1157 raw_string_ostream EntryStr(EntryName);
1158
Tobias Grosserf240b482014-01-09 10:42:15 +00001159 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001160 EntryStr.str();
1161
1162 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001163 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001164 ExitStr.str();
1165 } else
1166 ExitName = "FunctionExit";
1167
1168 return EntryName + "---" + ExitName;
1169}
1170
Tobias Grosser74394f02013-01-14 22:40:23 +00001171__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001172__isl_give isl_space *Scop::getParamSpace() const {
1173 return isl_set_get_space(this->Context);
1174}
1175
Tobias Grossere86109f2013-10-29 21:05:49 +00001176__isl_give isl_set *Scop::getAssumedContext() const {
1177 return isl_set_copy(AssumedContext);
1178}
1179
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001180void Scop::addAssumption(__isl_take isl_set *Set) {
1181 AssumedContext = isl_set_intersect(AssumedContext, Set);
1182}
1183
Tobias Grosser75805372011-04-29 06:27:02 +00001184void Scop::printContext(raw_ostream &OS) const {
1185 OS << "Context:\n";
1186
1187 if (!Context) {
1188 OS.indent(4) << "n/a\n\n";
1189 return;
1190 }
1191
1192 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001193
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001194 OS.indent(4) << "Assumed Context:\n";
1195 if (!AssumedContext) {
1196 OS.indent(4) << "n/a\n\n";
1197 return;
1198 }
1199
1200 OS.indent(4) << getAssumedContextStr() << "\n";
1201
Tobias Grosser083d3d32014-06-28 08:59:45 +00001202 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001203 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001204 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1205 }
Tobias Grosser75805372011-04-29 06:27:02 +00001206}
1207
1208void Scop::printStatements(raw_ostream &OS) const {
1209 OS << "Statements {\n";
1210
Tobias Grosser083d3d32014-06-28 08:59:45 +00001211 for (ScopStmt *Stmt : *this)
1212 OS.indent(4) << *Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001213
1214 OS.indent(4) << "}\n";
1215}
1216
Tobias Grosser75805372011-04-29 06:27:02 +00001217void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00001218 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
1219 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00001220 OS.indent(4) << "Region: " << getNameStr() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001221 printContext(OS.indent(4));
1222 printStatements(OS.indent(4));
1223}
1224
1225void Scop::dump() const { print(dbgs()); }
1226
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001227isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00001228
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001229__isl_give isl_union_set *Scop::getDomains() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001230 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001231
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001232 for (ScopStmt *Stmt : *this)
1233 Domain = isl_union_set_add_set(Domain, Stmt->getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001234
1235 return Domain;
1236}
1237
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001238__isl_give isl_union_map *Scop::getMustWrites() {
1239 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1240
1241 for (ScopStmt *Stmt : *this) {
1242 for (MemoryAccess *MA : *Stmt) {
1243 if (!MA->isMustWrite())
1244 continue;
1245
1246 isl_set *Domain = Stmt->getDomain();
1247 isl_map *AccessDomain = MA->getAccessRelation();
1248 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1249 Write = isl_union_map_add_map(Write, AccessDomain);
1250 }
1251 }
1252 return isl_union_map_coalesce(Write);
1253}
1254
1255__isl_give isl_union_map *Scop::getMayWrites() {
1256 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1257
1258 for (ScopStmt *Stmt : *this) {
1259 for (MemoryAccess *MA : *Stmt) {
1260 if (!MA->isMayWrite())
1261 continue;
1262
1263 isl_set *Domain = Stmt->getDomain();
1264 isl_map *AccessDomain = MA->getAccessRelation();
1265 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1266 Write = isl_union_map_add_map(Write, AccessDomain);
1267 }
1268 }
1269 return isl_union_map_coalesce(Write);
1270}
1271
Tobias Grosser37eb4222014-02-20 21:43:54 +00001272__isl_give isl_union_map *Scop::getWrites() {
1273 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1274
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001275 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001276 for (MemoryAccess *MA : *Stmt) {
1277 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001278 continue;
1279
1280 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001281 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001282 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1283 Write = isl_union_map_add_map(Write, AccessDomain);
1284 }
1285 }
1286 return isl_union_map_coalesce(Write);
1287}
1288
1289__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001290 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001291
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001292 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001293 for (MemoryAccess *MA : *Stmt) {
1294 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001295 continue;
1296
1297 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001298 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001299
1300 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1301 Read = isl_union_map_add_map(Read, AccessDomain);
1302 }
1303 }
1304 return isl_union_map_coalesce(Read);
1305}
1306
1307__isl_give isl_union_map *Scop::getSchedule() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001308 isl_union_map *Schedule = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001309
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001310 for (ScopStmt *Stmt : *this)
Tobias Grosser37eb4222014-02-20 21:43:54 +00001311 Schedule = isl_union_map_add_map(Schedule, Stmt->getScattering());
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001312
Tobias Grosser37eb4222014-02-20 21:43:54 +00001313 return isl_union_map_coalesce(Schedule);
1314}
1315
1316bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
1317 bool Changed = false;
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001318 for (ScopStmt *Stmt : *this) {
Tobias Grosser37eb4222014-02-20 21:43:54 +00001319 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt->getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001320 isl_union_set *NewStmtDomain = isl_union_set_intersect(
1321 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
1322
1323 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
1324 isl_union_set_free(StmtDomain);
1325 isl_union_set_free(NewStmtDomain);
1326 continue;
1327 }
1328
1329 Changed = true;
1330
1331 isl_union_set_free(StmtDomain);
1332 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
1333
1334 if (isl_union_set_is_empty(NewStmtDomain)) {
1335 Stmt->restrictDomain(isl_set_empty(Stmt->getDomainSpace()));
1336 isl_union_set_free(NewStmtDomain);
1337 } else
1338 Stmt->restrictDomain(isl_set_from_union_set(NewStmtDomain));
1339 }
1340 isl_union_set_free(Domain);
1341 return Changed;
1342}
1343
Tobias Grosser75805372011-04-29 06:27:02 +00001344ScalarEvolution *Scop::getSE() const { return SE; }
1345
1346bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
1347 if (tempScop.getAccessFunctions(BB))
1348 return false;
1349
1350 return true;
1351}
1352
Tobias Grosser74394f02013-01-14 22:40:23 +00001353void Scop::buildScop(TempScop &tempScop, const Region &CurRegion,
1354 SmallVectorImpl<Loop *> &NestLoops,
1355 SmallVectorImpl<unsigned> &Scatter, LoopInfo &LI) {
Tobias Grosser75805372011-04-29 06:27:02 +00001356 Loop *L = castToLoop(CurRegion, LI);
1357
1358 if (L)
1359 NestLoops.push_back(L);
1360
1361 unsigned loopDepth = NestLoops.size();
1362 assert(Scatter.size() > loopDepth && "Scatter not big enough!");
1363
1364 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00001365 E = CurRegion.element_end();
1366 I != E; ++I)
Tobias Grosser75805372011-04-29 06:27:02 +00001367 if (I->isSubRegion())
1368 buildScop(tempScop, *(I->getNodeAs<Region>()), NestLoops, Scatter, LI);
1369 else {
1370 BasicBlock *BB = I->getNodeAs<BasicBlock>();
1371
1372 if (isTrivialBB(BB, tempScop))
1373 continue;
1374
Tobias Grosserabfbe632013-02-05 12:09:06 +00001375 Stmts.push_back(
1376 new ScopStmt(*this, tempScop, CurRegion, *BB, NestLoops, Scatter));
Tobias Grosser75805372011-04-29 06:27:02 +00001377
1378 // Increasing the Scattering function is OK for the moment, because
1379 // we are using a depth first iterator and the program is well structured.
1380 ++Scatter[loopDepth];
1381 }
1382
1383 if (!L)
1384 return;
1385
1386 // Exiting a loop region.
1387 Scatter[loopDepth] = 0;
1388 NestLoops.pop_back();
Tobias Grosser74394f02013-01-14 22:40:23 +00001389 ++Scatter[loopDepth - 1];
Tobias Grosser75805372011-04-29 06:27:02 +00001390}
1391
1392//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00001393ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
1394 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00001395 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001396}
1397
1398ScopInfo::~ScopInfo() {
1399 clear();
1400 isl_ctx_free(ctx);
1401}
1402
Tobias Grosser75805372011-04-29 06:27:02 +00001403void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1404 AU.addRequired<LoopInfo>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001405 AU.addRequired<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001406 AU.addRequired<ScalarEvolution>();
1407 AU.addRequired<TempScopInfo>();
1408 AU.setPreservesAll();
1409}
1410
1411bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
1412 LoopInfo &LI = getAnalysis<LoopInfo>();
1413 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1414
1415 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop(R);
1416
1417 // This region is no Scop.
1418 if (!tempScop) {
1419 scop = 0;
1420 return false;
1421 }
1422
1423 // Statistics.
1424 ++ScopFound;
Tobias Grosser74394f02013-01-14 22:40:23 +00001425 if (tempScop->getMaxLoopDepth() > 0)
1426 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00001427
Tobias Grosserb76f38532011-08-20 11:11:25 +00001428 scop = new Scop(*tempScop, LI, SE, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001429
1430 return false;
1431}
1432
1433char ScopInfo::ID = 0;
1434
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001435Pass *polly::createScopInfoPass() { return new ScopInfo(); }
1436
Tobias Grosser73600b82011-10-08 00:30:40 +00001437INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
1438 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001439 false);
1440INITIALIZE_PASS_DEPENDENCY(LoopInfo);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001441INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001442INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1443INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Tobias Grosser73600b82011-10-08 00:30:40 +00001444INITIALIZE_PASS_END(ScopInfo, "polly-scops",
1445 "Polly - Create polyhedral description of Scops", false,
1446 false)