blob: 1ecf1a295d2124bfd040c38321e0e05ab4054aca [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"
Johannes Doerfertb164c792014-09-18 11:17:17 +000032#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser83628182013-05-07 08:11:54 +000033#include "llvm/Analysis/RegionIterator.h"
34#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000035#include "llvm/Support/Debug.h"
36
37#include "isl/constraint.h"
38#include "isl/set.h"
39#include "isl/map.h"
Tobias Grosser37eb4222014-02-20 21:43:54 +000040#include "isl/union_map.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000041#include "isl/aff.h"
42#include "isl/printer.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000043#include "isl/local_space.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000044#include "isl/options.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000045#include "isl/val.h"
Chandler Carruth95fef942014-04-22 03:30:19 +000046
Tobias Grosser75805372011-04-29 06:27:02 +000047#include <sstream>
48#include <string>
49#include <vector>
50
51using namespace llvm;
52using namespace polly;
53
Chandler Carruth95fef942014-04-22 03:30:19 +000054#define DEBUG_TYPE "polly-scops"
55
Tobias Grosser74394f02013-01-14 22:40:23 +000056STATISTIC(ScopFound, "Number of valid Scops");
57STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000058
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000059// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000060// operations can overflow easily. Additive reductions and bit operations
61// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000062static cl::opt<bool> DisableMultiplicativeReductions(
63 "polly-disable-multiplicative-reductions",
64 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
65 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000066
Johannes Doerfert9143d672014-09-27 11:02:39 +000067static cl::opt<unsigned> RunTimeChecksMaxParameters(
68 "polly-rtc-max-parameters",
69 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
70 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
71
Tobias Grosser0695ee42013-09-17 03:30:31 +000072/// Translate a 'const SCEV *' expression in an isl_pw_aff.
Tobias Grosserabfbe632013-02-05 12:09:06 +000073struct SCEVAffinator : public SCEVVisitor<SCEVAffinator, isl_pw_aff *> {
Tobias Grosser0695ee42013-09-17 03:30:31 +000074public:
Tobias Grosser0695ee42013-09-17 03:30:31 +000075 /// @brief Translate a 'const SCEV *' to an isl_pw_aff.
76 ///
77 /// @param Stmt The location at which the scalar evolution expression
78 /// is evaluated.
79 /// @param Expr The expression that is translated.
80 static __isl_give isl_pw_aff *getPwAff(ScopStmt *Stmt, const SCEV *Expr);
81
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000082private:
Tobias Grosser3cc99742012-06-06 16:33:15 +000083 isl_ctx *Ctx;
Tobias Grosserf5338802011-10-06 00:03:35 +000084 int NbLoopSpaces;
Tobias Grosser3cc99742012-06-06 16:33:15 +000085 const Scop *S;
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000086
Tobias Grosser0695ee42013-09-17 03:30:31 +000087 SCEVAffinator(const ScopStmt *Stmt);
88 int getLoopDepth(const Loop *L);
Tobias Grosser60b54f12011-11-08 15:41:28 +000089
Tobias Grosser0695ee42013-09-17 03:30:31 +000090 __isl_give isl_pw_aff *visit(const SCEV *Expr);
91 __isl_give isl_pw_aff *visitConstant(const SCEVConstant *Expr);
92 __isl_give isl_pw_aff *visitTruncateExpr(const SCEVTruncateExpr *Expr);
93 __isl_give isl_pw_aff *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr);
94 __isl_give isl_pw_aff *visitSignExtendExpr(const SCEVSignExtendExpr *Expr);
95 __isl_give isl_pw_aff *visitAddExpr(const SCEVAddExpr *Expr);
96 __isl_give isl_pw_aff *visitMulExpr(const SCEVMulExpr *Expr);
97 __isl_give isl_pw_aff *visitUDivExpr(const SCEVUDivExpr *Expr);
98 __isl_give isl_pw_aff *visitAddRecExpr(const SCEVAddRecExpr *Expr);
99 __isl_give isl_pw_aff *visitSMaxExpr(const SCEVSMaxExpr *Expr);
100 __isl_give isl_pw_aff *visitUMaxExpr(const SCEVUMaxExpr *Expr);
101 __isl_give isl_pw_aff *visitUnknown(const SCEVUnknown *Expr);
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);
157 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(Space));
158 isl_aff *Affine = isl_aff_zero_on_domain(ls);
159 isl_set *Domain = isl_set_universe(Space);
160
161 Affine = isl_aff_add_constant_val(Affine, v);
162
163 return isl_pw_aff_alloc(Domain, Affine);
164}
165
166__isl_give isl_pw_aff *
167SCEVAffinator::visitTruncateExpr(const SCEVTruncateExpr *Expr) {
168 llvm_unreachable("SCEVTruncateExpr not yet supported");
169}
170
171__isl_give isl_pw_aff *
172SCEVAffinator::visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
173 llvm_unreachable("SCEVZeroExtendExpr not yet supported");
174}
175
176__isl_give isl_pw_aff *
177SCEVAffinator::visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
178 // Assuming the value is signed, a sign extension is basically a noop.
179 // TODO: Reconsider this as soon as we support unsigned values.
180 return visit(Expr->getOperand());
181}
182
183__isl_give isl_pw_aff *SCEVAffinator::visitAddExpr(const SCEVAddExpr *Expr) {
184 isl_pw_aff *Sum = visit(Expr->getOperand(0));
185
186 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
187 isl_pw_aff *NextSummand = visit(Expr->getOperand(i));
188 Sum = isl_pw_aff_add(Sum, NextSummand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000189 }
190
Tobias Grosser0695ee42013-09-17 03:30:31 +0000191 // TODO: Check for NSW and NUW.
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000192
Tobias Grosser0695ee42013-09-17 03:30:31 +0000193 return Sum;
194}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000195
Tobias Grosser0695ee42013-09-17 03:30:31 +0000196__isl_give isl_pw_aff *SCEVAffinator::visitMulExpr(const SCEVMulExpr *Expr) {
197 isl_pw_aff *Product = visit(Expr->getOperand(0));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000198
Tobias Grosser0695ee42013-09-17 03:30:31 +0000199 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
200 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
201
202 if (!isl_pw_aff_is_cst(Product) && !isl_pw_aff_is_cst(NextOperand)) {
203 isl_pw_aff_free(Product);
204 isl_pw_aff_free(NextOperand);
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000205 return nullptr;
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000206 }
207
Tobias Grosser0695ee42013-09-17 03:30:31 +0000208 Product = isl_pw_aff_mul(Product, NextOperand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000209 }
210
Tobias Grosser0695ee42013-09-17 03:30:31 +0000211 // TODO: Check for NSW and NUW.
212 return Product;
213}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000214
Tobias Grosser0695ee42013-09-17 03:30:31 +0000215__isl_give isl_pw_aff *SCEVAffinator::visitUDivExpr(const SCEVUDivExpr *Expr) {
216 llvm_unreachable("SCEVUDivExpr not yet supported");
217}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000218
Tobias Grosser0695ee42013-09-17 03:30:31 +0000219__isl_give isl_pw_aff *
220SCEVAffinator::visitAddRecExpr(const SCEVAddRecExpr *Expr) {
221 assert(Expr->isAffine() && "Only affine AddRecurrences allowed");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000222
Tobias Grosser0695ee42013-09-17 03:30:31 +0000223 // Directly generate isl_pw_aff for Expr if 'start' is zero.
224 if (Expr->getStart()->isZero()) {
225 assert(S->getRegion().contains(Expr->getLoop()) &&
226 "Scop does not contain the loop referenced in this AddRec");
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000227
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000228 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser0695ee42013-09-17 03:30:31 +0000229 isl_pw_aff *Step = visit(Expr->getOperand(1));
230 isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
231 isl_local_space *LocalSpace = isl_local_space_from_space(Space);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000232
Tobias Grosser0695ee42013-09-17 03:30:31 +0000233 int loopDimension = getLoopDepth(Expr->getLoop());
234
235 isl_aff *LAff = isl_aff_set_coefficient_si(
236 isl_aff_zero_on_domain(LocalSpace), isl_dim_in, loopDimension, 1);
237 isl_pw_aff *LPwAff = isl_pw_aff_from_aff(LAff);
238
239 // TODO: Do we need to check for NSW and NUW?
240 return isl_pw_aff_add(Start, isl_pw_aff_mul(Step, LPwAff));
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000241 }
242
Tobias Grosser0695ee42013-09-17 03:30:31 +0000243 // Translate AddRecExpr from '{start, +, inc}' into 'start + {0, +, inc}'
244 // if 'start' is not zero.
245 ScalarEvolution &SE = *S->getSE();
246 const SCEV *ZeroStartExpr = SE.getAddRecExpr(
247 SE.getConstant(Expr->getStart()->getType(), 0),
248 Expr->getStepRecurrence(SE), Expr->getLoop(), SCEV::FlagAnyWrap);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000249
Tobias Grosser0695ee42013-09-17 03:30:31 +0000250 isl_pw_aff *ZeroStartResult = visit(ZeroStartExpr);
251 isl_pw_aff *Start = visit(Expr->getStart());
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000252
Tobias Grosser0695ee42013-09-17 03:30:31 +0000253 return isl_pw_aff_add(ZeroStartResult, Start);
254}
255
256__isl_give isl_pw_aff *SCEVAffinator::visitSMaxExpr(const SCEVSMaxExpr *Expr) {
257 isl_pw_aff *Max = visit(Expr->getOperand(0));
258
259 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
260 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
261 Max = isl_pw_aff_max(Max, NextOperand);
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000262 }
263
Tobias Grosser0695ee42013-09-17 03:30:31 +0000264 return Max;
265}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000266
Tobias Grosser0695ee42013-09-17 03:30:31 +0000267__isl_give isl_pw_aff *SCEVAffinator::visitUMaxExpr(const SCEVUMaxExpr *Expr) {
268 llvm_unreachable("SCEVUMaxExpr not yet supported");
269}
270
271__isl_give isl_pw_aff *SCEVAffinator::visitUnknown(const SCEVUnknown *Expr) {
Tobias Grosserf4daf342014-08-16 09:08:55 +0000272 llvm_unreachable("Unknowns are always parameters");
Tobias Grosser0695ee42013-09-17 03:30:31 +0000273}
274
275int SCEVAffinator::getLoopDepth(const Loop *L) {
276 Loop *outerLoop = S->getRegion().outermostLoopInRegion(const_cast<Loop *>(L));
277 assert(outerLoop && "Scop does not contain this loop");
278 return L->getLoopDepth() - outerLoop->getLoopDepth();
279}
Tobias Grosser33ba62ad2011-08-18 06:31:50 +0000280
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000281const std::string
282MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
283 switch (RT) {
284 case MemoryAccess::RT_NONE:
285 llvm_unreachable("Requested a reduction operator string for a memory "
286 "access which isn't a reduction");
287 case MemoryAccess::RT_ADD:
288 return "+";
289 case MemoryAccess::RT_MUL:
290 return "*";
291 case MemoryAccess::RT_BOR:
292 return "|";
293 case MemoryAccess::RT_BXOR:
294 return "^";
295 case MemoryAccess::RT_BAND:
296 return "&";
297 }
298 llvm_unreachable("Unknown reduction type");
299 return "";
300}
301
Johannes Doerfertf6183392014-07-01 20:52:51 +0000302/// @brief Return the reduction type for a given binary operator
303static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
304 const Instruction *Load) {
305 if (!BinOp)
306 return MemoryAccess::RT_NONE;
307 switch (BinOp->getOpcode()) {
308 case Instruction::FAdd:
309 if (!BinOp->hasUnsafeAlgebra())
310 return MemoryAccess::RT_NONE;
311 // Fall through
312 case Instruction::Add:
313 return MemoryAccess::RT_ADD;
314 case Instruction::Or:
315 return MemoryAccess::RT_BOR;
316 case Instruction::Xor:
317 return MemoryAccess::RT_BXOR;
318 case Instruction::And:
319 return MemoryAccess::RT_BAND;
320 case Instruction::FMul:
321 if (!BinOp->hasUnsafeAlgebra())
322 return MemoryAccess::RT_NONE;
323 // Fall through
324 case Instruction::Mul:
325 if (DisableMultiplicativeReductions)
326 return MemoryAccess::RT_NONE;
327 return MemoryAccess::RT_MUL;
328 default:
329 return MemoryAccess::RT_NONE;
330 }
331}
Tobias Grosser75805372011-04-29 06:27:02 +0000332//===----------------------------------------------------------------------===//
333
334MemoryAccess::~MemoryAccess() {
Tobias Grosser54a86e62011-08-18 06:31:46 +0000335 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000336 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000337}
338
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000339static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
340 switch (Access.getType()) {
341 case IRAccess::READ:
342 return MemoryAccess::READ;
343 case IRAccess::MUST_WRITE:
344 return MemoryAccess::MUST_WRITE;
345 case IRAccess::MAY_WRITE:
346 return MemoryAccess::MAY_WRITE;
347 }
348 llvm_unreachable("Unknown IRAccess type!");
349}
350
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000351isl_id *MemoryAccess::getArrayId() const {
352 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
353}
354
Tobias Grosser5d453812011-10-06 00:04:11 +0000355isl_map *MemoryAccess::getAccessRelation() const {
356 return isl_map_copy(AccessRelation);
357}
358
359std::string MemoryAccess::getAccessRelationStr() const {
360 return stringFromIslObj(AccessRelation);
361}
362
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000363__isl_give isl_space *MemoryAccess::getAccessRelationSpace() const {
364 return isl_map_get_space(AccessRelation);
365}
366
Tobias Grosser5d453812011-10-06 00:04:11 +0000367isl_map *MemoryAccess::getNewAccessRelation() const {
368 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000369}
370
371isl_basic_map *MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000372 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000373 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000374
Tobias Grosser084d8f72012-05-29 09:29:44 +0000375 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000376 isl_basic_set_universe(Statement->getDomainSpace()),
377 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000378}
379
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000380// Formalize no out-of-bound access assumption
381//
382// When delinearizing array accesses we optimistically assume that the
383// delinearized accesses do not access out of bound locations (the subscript
384// expression of each array evaluates for each statement instance that is
385// executed to a value that is larger than zero and strictly smaller than the
386// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000387// dimension for which we do not need to assume any upper bound. At this point
388// we formalize this assumption to ensure that at code generation time the
389// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000390//
391// To find the set of constraints necessary to avoid out of bound accesses, we
392// first build the set of data locations that are not within array bounds. We
393// then apply the reverse access relation to obtain the set of iterations that
394// may contain invalid accesses and reduce this set of iterations to the ones
395// that are actually executed by intersecting them with the domain of the
396// statement. If we now project out all loop dimensions, we obtain a set of
397// parameters that may cause statement instances to be executed that may
398// possibly yield out of bound memory accesses. The complement of these
399// constraints is the set of constraints that needs to be assumed to ensure such
400// statement instances are never executed.
401void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
402 isl_space *Space = isl_space_range(getAccessRelationSpace());
403 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000404 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000405 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
406 isl_pw_aff *Var =
407 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
408 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
409
410 isl_set *DimOutside;
411
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000412 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
413 isl_pw_aff *SizeE = SCEVAffinator::getPwAff(Statement, Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000414
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000415 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
416 Statement->getNumIterators());
417 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
418 isl_space_dim(Space, isl_dim_set));
419 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
420 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000421
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000422 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000423
424 Outside = isl_set_union(Outside, DimOutside);
425 }
426
427 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
428 Outside = isl_set_intersect(Outside, Statement->getDomain());
429 Outside = isl_set_params(Outside);
430 Outside = isl_set_complement(Outside);
431 Statement->getParent()->addAssumption(Outside);
432 isl_space_free(Space);
433}
434
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000435MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Tobias Grosserabfbe632013-02-05 12:09:06 +0000436 ScopStmt *Statement)
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000437 : Type(getMemoryAccessType(Access)), Statement(Statement), Inst(AccInst),
438 newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000439
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000440 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000441 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000442 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000443 isl_id *BaseAddrId = isl_id_alloc(Ctx, getBaseName().c_str(), nullptr);
Tobias Grosser5683df42011-11-09 22:34:34 +0000444
Tobias Grossera1879642011-12-20 10:43:14 +0000445 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000446 // We overapproximate non-affine accesses with a possible access to the
447 // whole array. For read accesses it does not make a difference, if an
448 // access must or may happen. However, for write accesses it is important to
449 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000450 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000451 AccessRelation =
452 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000453 return;
454 }
455
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000456 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000457 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000458
Tobias Grosser79baa212014-04-10 08:38:02 +0000459 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Sebastian Pop18016682014-04-08 21:20:44 +0000460 isl_pw_aff *Affine =
461 SCEVAffinator::getPwAff(Statement, Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000462
Sebastian Pop422e33f2014-06-03 18:16:31 +0000463 if (Size == 1) {
464 // For the non delinearized arrays, divide the access function of the last
465 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000466 //
467 // A stride one array access in C expressed as A[i] is expressed in
468 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
469 // two subsequent values of 'i' index two values that are stored next to
470 // each other in memory. By this division we make this characteristic
471 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000472 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000473 Affine = isl_pw_aff_scale_down_val(Affine, v);
474 }
475
476 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
477
Tobias Grosser79baa212014-04-10 08:38:02 +0000478 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000479 }
480
Tobias Grosser79baa212014-04-10 08:38:02 +0000481 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000482 AccessRelation = isl_map_set_tuple_id(
483 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000484 AccessRelation =
485 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
486
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000487 assumeNoOutOfBound(Access);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000488 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000489}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000490
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000491void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000492 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000493 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000494}
495
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000496const std::string MemoryAccess::getReductionOperatorStr() const {
497 return MemoryAccess::getReductionOperatorStr(getReductionType());
498}
499
Johannes Doerfertf6183392014-07-01 20:52:51 +0000500raw_ostream &polly::operator<<(raw_ostream &OS,
501 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000502 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000503 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000504 else
505 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000506 return OS;
507}
508
Tobias Grosser75805372011-04-29 06:27:02 +0000509void MemoryAccess::print(raw_ostream &OS) const {
Tobias Grosser4f967492013-06-23 05:21:18 +0000510 switch (Type) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000511 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000512 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000513 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000514 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000515 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000516 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000517 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000518 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000519 break;
520 }
Johannes Doerfertf6183392014-07-01 20:52:51 +0000521 OS << "[Reduction Type: " << getReductionType() << "]\n";
Tobias Grosser5d453812011-10-06 00:04:11 +0000522 OS.indent(16) << getAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000523}
524
Tobias Grosser74394f02013-01-14 22:40:23 +0000525void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000526
527// Create a map in the size of the provided set domain, that maps from the
528// one element of the provided set domain to another element of the provided
529// set domain.
530// The mapping is limited to all points that are equal in all but the last
531// dimension and for which the last dimension of the input is strict smaller
532// than the last dimension of the output.
533//
534// getEqualAndLarger(set[i0, i1, ..., iX]):
535//
536// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
537// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
538//
Tobias Grosserf5338802011-10-06 00:03:35 +0000539static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000540 isl_space *Space = isl_space_map_from_set(setDomain);
541 isl_map *Map = isl_map_universe(isl_space_copy(Space));
542 isl_local_space *MapLocalSpace = isl_local_space_from_space(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000543 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000544
545 // Set all but the last dimension to be equal for the input and output
546 //
547 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
548 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000549 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000550 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000551
552 // Set the last dimension of the input to be strict smaller than the
553 // last dimension of the output.
554 //
555 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
556 //
Tobias Grosseredab1352013-06-21 06:41:31 +0000557 isl_val *v;
558 isl_ctx *Ctx = isl_map_get_ctx(Map);
Tobias Grosserf5338802011-10-06 00:03:35 +0000559 isl_constraint *c = isl_inequality_alloc(isl_local_space_copy(MapLocalSpace));
Tobias Grosseredab1352013-06-21 06:41:31 +0000560 v = isl_val_int_from_si(Ctx, -1);
561 c = isl_constraint_set_coefficient_val(c, isl_dim_in, lastDimension, v);
562 v = isl_val_int_from_si(Ctx, 1);
563 c = isl_constraint_set_coefficient_val(c, isl_dim_out, lastDimension, v);
564 v = isl_val_int_from_si(Ctx, -1);
565 c = isl_constraint_set_constant_val(c, v);
Tobias Grosser75805372011-04-29 06:27:02 +0000566
Tobias Grosserc327932c2012-02-01 14:23:36 +0000567 Map = isl_map_add_constraint(Map, c);
Tobias Grosser75805372011-04-29 06:27:02 +0000568
Tobias Grosser23b36662011-10-17 08:32:36 +0000569 isl_local_space_free(MapLocalSpace);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000570 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000571}
572
Sebastian Popa00a0292012-12-18 07:46:06 +0000573isl_set *MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000574 isl_map *S = const_cast<isl_map *>(Schedule);
Sebastian Popa00a0292012-12-18 07:46:06 +0000575 isl_map *AccessRelation = getAccessRelation();
576 isl_space *Space = isl_space_range(isl_map_get_space(S));
577 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000578
Sebastian Popa00a0292012-12-18 07:46:06 +0000579 S = isl_map_reverse(S);
580 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000581
Sebastian Popa00a0292012-12-18 07:46:06 +0000582 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
583 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
584 NextScatt = isl_map_apply_domain(NextScatt, S);
585 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000586
Sebastian Popa00a0292012-12-18 07:46:06 +0000587 isl_set *Deltas = isl_map_deltas(NextScatt);
588 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000589}
590
Sebastian Popa00a0292012-12-18 07:46:06 +0000591bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000592 int StrideWidth) const {
593 isl_set *Stride, *StrideX;
594 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000595
Sebastian Popa00a0292012-12-18 07:46:06 +0000596 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000597 StrideX = isl_set_universe(isl_set_get_space(Stride));
598 StrideX = isl_set_fix_si(StrideX, isl_dim_set, 0, StrideWidth);
599 IsStrideX = isl_set_is_equal(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000600
Tobias Grosser28dd4862012-01-24 16:42:16 +0000601 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000602 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000603
Tobias Grosser28dd4862012-01-24 16:42:16 +0000604 return IsStrideX;
605}
606
Sebastian Popa00a0292012-12-18 07:46:06 +0000607bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
608 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000609}
610
Tobias Grosser79baa212014-04-10 08:38:02 +0000611bool MemoryAccess::isScalar() const {
612 return isl_map_n_out(AccessRelation) == 0;
613}
614
Sebastian Popa00a0292012-12-18 07:46:06 +0000615bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
616 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000617}
618
Tobias Grosser5d453812011-10-06 00:04:11 +0000619void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000620 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000621 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000622}
Tobias Grosser75805372011-04-29 06:27:02 +0000623
624//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000625
Tobias Grosser74394f02013-01-14 22:40:23 +0000626isl_map *ScopStmt::getScattering() const { return isl_map_copy(Scattering); }
Tobias Grossercf3942d2011-10-06 00:04:05 +0000627
Tobias Grosser37eb4222014-02-20 21:43:54 +0000628void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
629 assert(isl_set_is_subset(NewDomain, Domain) &&
630 "New domain is not a subset of old domain!");
631 isl_set_free(Domain);
632 Domain = NewDomain;
633 Scattering = isl_map_intersect_domain(Scattering, isl_set_copy(Domain));
634}
635
Tobias Grossercf3942d2011-10-06 00:04:05 +0000636void ScopStmt::setScattering(isl_map *NewScattering) {
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000637 assert(NewScattering && "New scattering is nullptr");
Tobias Grosserb76f38532011-08-20 11:11:25 +0000638 isl_map_free(Scattering);
Tobias Grossercf3942d2011-10-06 00:04:05 +0000639 Scattering = NewScattering;
Tobias Grosserb76f38532011-08-20 11:11:25 +0000640}
641
Tobias Grosser75805372011-04-29 06:27:02 +0000642void ScopStmt::buildScattering(SmallVectorImpl<unsigned> &Scatter) {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000643 unsigned NbIterators = getNumIterators();
644 unsigned NbScatteringDims = Parent.getMaxLoopDepth() * 2 + 1;
645
Tobias Grosser084d8f72012-05-29 09:29:44 +0000646 isl_space *Space = isl_space_set_alloc(getIslCtx(), 0, NbScatteringDims);
Tobias Grosserf5338802011-10-06 00:03:35 +0000647 Space = isl_space_set_tuple_name(Space, isl_dim_out, "scattering");
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000648
Tobias Grosser084d8f72012-05-29 09:29:44 +0000649 Scattering = isl_map_from_domain_and_range(isl_set_universe(getDomainSpace()),
650 isl_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000651
652 // Loop dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000653 for (unsigned i = 0; i < NbIterators; ++i)
Tobias Grosserabfbe632013-02-05 12:09:06 +0000654 Scattering =
655 isl_map_equate(Scattering, isl_dim_out, 2 * i + 1, isl_dim_in, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000656
657 // Constant dimensions
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000658 for (unsigned i = 0; i < NbIterators + 1; ++i)
659 Scattering = isl_map_fix_si(Scattering, isl_dim_out, 2 * i, Scatter[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000660
661 // Fill scattering dimensions.
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000662 for (unsigned i = 2 * NbIterators + 1; i < NbScatteringDims; ++i)
663 Scattering = isl_map_fix_si(Scattering, isl_dim_out, i, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000664
Tobias Grosser37487052011-10-06 00:03:42 +0000665 Scattering = isl_map_align_params(Scattering, Parent.getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000666}
667
668void ScopStmt::buildAccesses(TempScop &tempScop, const Region &CurRegion) {
Tobias Grosser083d3d32014-06-28 08:59:45 +0000669 for (auto &&Access : *tempScop.getAccessFunctions(BB)) {
670 MemAccs.push_back(new MemoryAccess(Access.first, Access.second, this));
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000671
672 // We do not track locations for scalar memory accesses at the moment.
673 //
674 // We do not have a use for this information at the moment. If we need this
675 // at some point, the "instruction -> access" mapping needs to be enhanced
676 // as a single instruction could then possibly perform multiple accesses.
Tobias Grosser083d3d32014-06-28 08:59:45 +0000677 if (!Access.first.isScalar()) {
678 assert(!InstructionToAccess.count(Access.second) &&
Tobias Grosser3fc91542014-02-20 21:43:45 +0000679 "Unexpected 1-to-N mapping on instruction to access map!");
Tobias Grosser083d3d32014-06-28 08:59:45 +0000680 InstructionToAccess[Access.second] = MemAccs.back();
Tobias Grosserd6aafa72014-02-20 21:29:09 +0000681 }
Tobias Grosser75805372011-04-29 06:27:02 +0000682 }
683}
684
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000685void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000686 for (MemoryAccess *MA : *this)
687 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000688
689 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
690 Scattering = isl_map_align_params(Scattering, Parent.getParamSpace());
691}
692
Tobias Grosser65b00582011-11-08 15:41:19 +0000693__isl_give isl_set *ScopStmt::buildConditionSet(const Comparison &Comp) {
Tobias Grossera601fbd2011-11-09 22:34:44 +0000694 isl_pw_aff *L = SCEVAffinator::getPwAff(this, Comp.getLHS());
695 isl_pw_aff *R = SCEVAffinator::getPwAff(this, Comp.getRHS());
Tobias Grosser75805372011-04-29 06:27:02 +0000696
Tobias Grosserd2795d02011-08-18 07:51:40 +0000697 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000698 case ICmpInst::ICMP_EQ:
Tobias Grosser048c8792011-10-23 20:59:20 +0000699 return isl_pw_aff_eq_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000700 case ICmpInst::ICMP_NE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000701 return isl_pw_aff_ne_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000702 case ICmpInst::ICMP_SLT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000703 return isl_pw_aff_lt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000704 case ICmpInst::ICMP_SLE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000705 return isl_pw_aff_le_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000706 case ICmpInst::ICMP_SGT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000707 return isl_pw_aff_gt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000708 case ICmpInst::ICMP_SGE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000709 return isl_pw_aff_ge_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000710 case ICmpInst::ICMP_ULT:
711 case ICmpInst::ICMP_UGT:
712 case ICmpInst::ICMP_ULE:
Tobias Grosser75805372011-04-29 06:27:02 +0000713 case ICmpInst::ICMP_UGE:
Tobias Grosserd2795d02011-08-18 07:51:40 +0000714 llvm_unreachable("Unsigned comparisons not yet supported");
Tobias Grosser75805372011-04-29 06:27:02 +0000715 default:
716 llvm_unreachable("Non integer predicate not supported");
717 }
Tobias Grosser75805372011-04-29 06:27:02 +0000718}
719
Tobias Grossere19661e2011-10-07 08:46:57 +0000720__isl_give isl_set *ScopStmt::addLoopBoundsToDomain(__isl_take isl_set *Domain,
Tobias Grosser60b54f12011-11-08 15:41:28 +0000721 TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000722 isl_space *Space;
723 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000724
Tobias Grossere19661e2011-10-07 08:46:57 +0000725 Space = isl_set_get_space(Domain);
726 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000727
Tobias Grosser75805372011-04-29 06:27:02 +0000728 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000729 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000730 isl_pw_aff *IV =
731 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000732
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000733 // 0 <= IV.
734 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
735 Domain = isl_set_intersect(Domain, LowerBound);
736
737 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000738 const Loop *L = getLoopForDimension(i);
Tobias Grosser1179afa2011-11-02 21:37:51 +0000739 const SCEV *LatchExecutions = tempScop.getLoopBound(L);
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000740 isl_pw_aff *UpperBound = SCEVAffinator::getPwAff(this, LatchExecutions);
741 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
Tobias Grosser75805372011-04-29 06:27:02 +0000742 Domain = isl_set_intersect(Domain, UpperBoundSet);
743 }
744
Tobias Grosserf5338802011-10-06 00:03:35 +0000745 isl_local_space_free(LocalSpace);
Tobias Grossere19661e2011-10-07 08:46:57 +0000746 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000747}
748
Tobias Grossere602a072013-05-07 07:30:56 +0000749__isl_give isl_set *ScopStmt::addConditionsToDomain(__isl_take isl_set *Domain,
750 TempScop &tempScop,
751 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000752 const Region *TopRegion = tempScop.getMaxRegion().getParent(),
Tobias Grosserd7e58642013-04-10 06:55:45 +0000753 *CurrentRegion = &CurRegion;
Tobias Grossere19661e2011-10-07 08:46:57 +0000754 const BasicBlock *BranchingBB = BB;
Tobias Grosser75805372011-04-29 06:27:02 +0000755
Tobias Grosser75805372011-04-29 06:27:02 +0000756 do {
Tobias Grossere19661e2011-10-07 08:46:57 +0000757 if (BranchingBB != CurrentRegion->getEntry()) {
758 if (const BBCond *Condition = tempScop.getBBCond(BranchingBB))
Tobias Grosser083d3d32014-06-28 08:59:45 +0000759 for (const auto &C : *Condition) {
760 isl_set *ConditionSet = buildConditionSet(C);
Tobias Grossere19661e2011-10-07 08:46:57 +0000761 Domain = isl_set_intersect(Domain, ConditionSet);
Tobias Grosser75805372011-04-29 06:27:02 +0000762 }
763 }
Tobias Grossere19661e2011-10-07 08:46:57 +0000764 BranchingBB = CurrentRegion->getEntry();
765 CurrentRegion = CurrentRegion->getParent();
766 } while (TopRegion != CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000767
Tobias Grossere19661e2011-10-07 08:46:57 +0000768 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000769}
770
Tobias Grossere602a072013-05-07 07:30:56 +0000771__isl_give isl_set *ScopStmt::buildDomain(TempScop &tempScop,
772 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000773 isl_space *Space;
774 isl_set *Domain;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000775 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000776
777 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
778
Tobias Grosser084d8f72012-05-29 09:29:44 +0000779 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
780
Tobias Grossere19661e2011-10-07 08:46:57 +0000781 Domain = isl_set_universe(Space);
Tobias Grossere19661e2011-10-07 08:46:57 +0000782 Domain = addLoopBoundsToDomain(Domain, tempScop);
783 Domain = addConditionsToDomain(Domain, tempScop, CurRegion);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000784 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grossere19661e2011-10-07 08:46:57 +0000785
786 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000787}
788
Tobias Grosser74394f02013-01-14 22:40:23 +0000789ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Sebastian Pop860e0212013-02-15 21:26:44 +0000790 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest,
Tobias Grosser75805372011-04-29 06:27:02 +0000791 SmallVectorImpl<unsigned> &Scatter)
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000792 : Parent(parent), BB(&bb), IVS(Nest.size()), NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000793 // Setup the induction variables.
Sebastian Pop860e0212013-02-15 21:26:44 +0000794 for (unsigned i = 0, e = Nest.size(); i < e; ++i) {
Sebastian Pop27c10c62013-03-22 22:07:43 +0000795 if (!SCEVCodegen) {
796 PHINode *PN = Nest[i]->getCanonicalInductionVariable();
797 assert(PN && "Non canonical IV in Scop!");
Tobias Grosser826b2af2013-03-21 16:14:50 +0000798 IVS[i] = PN;
Sebastian Pop27c10c62013-03-22 22:07:43 +0000799 }
Sebastian Pop860e0212013-02-15 21:26:44 +0000800 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +0000801 }
802
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000803 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +0000804
Tobias Grossere19661e2011-10-07 08:46:57 +0000805 Domain = buildDomain(tempScop, CurRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000806 buildScattering(Scatter);
807 buildAccesses(tempScop, CurRegion);
Johannes Doerferte58a0122014-06-27 20:31:28 +0000808 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000809}
810
Johannes Doerferte58a0122014-06-27 20:31:28 +0000811/// @brief Collect loads which might form a reduction chain with @p StoreMA
812///
813/// Check if the stored value for @p StoreMA is a binary operator with one or
814/// two loads as operands. If the binary operand is commutative & associative,
815/// used only once (by @p StoreMA) and its load operands are also used only
816/// once, we have found a possible reduction chain. It starts at an operand
817/// load and includes the binary operator and @p StoreMA.
818///
819/// Note: We allow only one use to ensure the load and binary operator cannot
820/// escape this block or into any other store except @p StoreMA.
821void ScopStmt::collectCandiateReductionLoads(
822 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
823 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
824 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000825 return;
826
827 // Skip if there is not one binary operator between the load and the store
828 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +0000829 if (!BinOp)
830 return;
831
832 // Skip if the binary operators has multiple uses
833 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000834 return;
835
836 // Skip if the opcode of the binary operator is not commutative/associative
837 if (!BinOp->isCommutative() || !BinOp->isAssociative())
838 return;
839
Johannes Doerfert9890a052014-07-01 00:32:29 +0000840 // Skip if the binary operator is outside the current SCoP
841 if (BinOp->getParent() != Store->getParent())
842 return;
843
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000844 // Skip if it is a multiplicative reduction and we disabled them
845 if (DisableMultiplicativeReductions &&
846 (BinOp->getOpcode() == Instruction::Mul ||
847 BinOp->getOpcode() == Instruction::FMul))
848 return;
849
Johannes Doerferte58a0122014-06-27 20:31:28 +0000850 // Check the binary operator operands for a candidate load
851 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
852 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
853 if (!PossibleLoad0 && !PossibleLoad1)
854 return;
855
856 // A load is only a candidate if it cannot escape (thus has only this use)
857 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000858 if (PossibleLoad0->getParent() == Store->getParent())
859 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000860 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000861 if (PossibleLoad1->getParent() == Store->getParent())
862 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000863}
864
865/// @brief Check for reductions in this ScopStmt
866///
867/// Iterate over all store memory accesses and check for valid binary reduction
868/// like chains. For all candidates we check if they have the same base address
869/// and there are no other accesses which overlap with them. The base address
870/// check rules out impossible reductions candidates early. The overlap check,
871/// together with the "only one user" check in collectCandiateReductionLoads,
872/// guarantees that none of the intermediate results will escape during
873/// execution of the loop nest. We basically check here that no other memory
874/// access can access the same memory as the potential reduction.
875void ScopStmt::checkForReductions() {
876 SmallVector<MemoryAccess *, 2> Loads;
877 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
878
879 // First collect candidate load-store reduction chains by iterating over all
880 // stores and collecting possible reduction loads.
881 for (MemoryAccess *StoreMA : MemAccs) {
882 if (StoreMA->isRead())
883 continue;
884
885 Loads.clear();
886 collectCandiateReductionLoads(StoreMA, Loads);
887 for (MemoryAccess *LoadMA : Loads)
888 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
889 }
890
891 // Then check each possible candidate pair.
892 for (const auto &CandidatePair : Candidates) {
893 bool Valid = true;
894 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
895 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
896
897 // Skip those with obviously unequal base addresses.
898 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
899 isl_map_free(LoadAccs);
900 isl_map_free(StoreAccs);
901 continue;
902 }
903
904 // And check if the remaining for overlap with other memory accesses.
905 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
906 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
907 isl_set *AllAccs = isl_map_range(AllAccsRel);
908
909 for (MemoryAccess *MA : MemAccs) {
910 if (MA == CandidatePair.first || MA == CandidatePair.second)
911 continue;
912
913 isl_map *AccRel =
914 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
915 isl_set *Accs = isl_map_range(AccRel);
916
917 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
918 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
919 Valid = Valid && isl_set_is_empty(OverlapAccs);
920 isl_set_free(OverlapAccs);
921 }
922 }
923
924 isl_set_free(AllAccs);
925 if (!Valid)
926 continue;
927
Johannes Doerfertf6183392014-07-01 20:52:51 +0000928 const LoadInst *Load =
929 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
930 MemoryAccess::ReductionType RT =
931 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
932
Johannes Doerferte58a0122014-06-27 20:31:28 +0000933 // If no overlapping access was found we mark the load and store as
934 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000935 CandidatePair.first->markAsReductionLike(RT);
936 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +0000937 }
Tobias Grosser75805372011-04-29 06:27:02 +0000938}
939
Tobias Grosser74394f02013-01-14 22:40:23 +0000940std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +0000941
942std::string ScopStmt::getScatteringStr() const {
Tobias Grossercf3942d2011-10-06 00:04:05 +0000943 return stringFromIslObj(Scattering);
Tobias Grosser75805372011-04-29 06:27:02 +0000944}
945
Tobias Grosser74394f02013-01-14 22:40:23 +0000946unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +0000947
948unsigned ScopStmt::getNumIterators() const {
949 // The final read has one dimension with one element.
950 if (!BB)
951 return 1;
952
Sebastian Pop860e0212013-02-15 21:26:44 +0000953 return NestLoops.size();
Tobias Grosser75805372011-04-29 06:27:02 +0000954}
955
956unsigned ScopStmt::getNumScattering() const {
957 return isl_map_dim(Scattering, isl_dim_out);
958}
959
960const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
961
Tobias Grosserabfbe632013-02-05 12:09:06 +0000962const PHINode *
963ScopStmt::getInductionVariableForDimension(unsigned Dimension) const {
Sebastian Popf30d3b22013-02-15 21:26:48 +0000964 return IVS[Dimension];
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000965}
966
967const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +0000968 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +0000969}
970
Tobias Grosser74394f02013-01-14 22:40:23 +0000971isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +0000972
Tobias Grosser74394f02013-01-14 22:40:23 +0000973isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +0000974
Tobias Grosser78d8a3d2012-01-17 20:34:23 +0000975isl_space *ScopStmt::getDomainSpace() const {
976 return isl_set_get_space(Domain);
977}
978
Tobias Grosser74394f02013-01-14 22:40:23 +0000979isl_id *ScopStmt::getDomainId() const { return isl_set_get_tuple_id(Domain); }
Tobias Grossercd95b772012-08-30 11:49:38 +0000980
Tobias Grosser75805372011-04-29 06:27:02 +0000981ScopStmt::~ScopStmt() {
982 while (!MemAccs.empty()) {
983 delete MemAccs.back();
984 MemAccs.pop_back();
985 }
986
987 isl_set_free(Domain);
988 isl_map_free(Scattering);
989}
990
991void ScopStmt::print(raw_ostream &OS) const {
992 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000993 OS.indent(12) << "Domain :=\n";
994
995 if (Domain) {
996 OS.indent(16) << getDomainStr() << ";\n";
997 } else
998 OS.indent(16) << "n/a\n";
999
1000 OS.indent(12) << "Scattering :=\n";
1001
1002 if (Domain) {
1003 OS.indent(16) << getScatteringStr() << ";\n";
1004 } else
1005 OS.indent(16) << "n/a\n";
1006
Tobias Grosser083d3d32014-06-28 08:59:45 +00001007 for (MemoryAccess *Access : MemAccs)
1008 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001009}
1010
1011void ScopStmt::dump() const { print(dbgs()); }
1012
1013//===----------------------------------------------------------------------===//
1014/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001015
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001016void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001017 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1018 isl_set_free(Context);
1019 Context = NewContext;
1020}
1021
Tobias Grosserabfbe632013-02-05 12:09:06 +00001022void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001023 for (const SCEV *Parameter : NewParameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001024 if (ParameterIds.find(Parameter) != ParameterIds.end())
1025 continue;
1026
1027 int dimension = Parameters.size();
1028
1029 Parameters.push_back(Parameter);
1030 ParameterIds[Parameter] = dimension;
1031 }
1032}
1033
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001034__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1035 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001036
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001037 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001038 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001039
Tobias Grosser8f99c162011-11-15 11:38:55 +00001040 std::string ParameterName;
1041
1042 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1043 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001044 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001045 }
1046
1047 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001048 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001049
Tobias Grosser20532b82014-04-11 17:56:49 +00001050 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1051 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001052}
Tobias Grosser75805372011-04-29 06:27:02 +00001053
Tobias Grosser6be480c2011-11-08 15:41:13 +00001054void Scop::buildContext() {
1055 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001056 Context = isl_set_universe(isl_space_copy(Space));
1057 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001058}
1059
Tobias Grosser18daaca2012-05-22 10:47:27 +00001060void Scop::addParameterBounds() {
1061 for (unsigned i = 0; i < isl_set_dim(Context, isl_dim_param); ++i) {
Tobias Grosseredab1352013-06-21 06:41:31 +00001062 isl_val *V;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001063 isl_id *Id;
1064 const SCEV *Scev;
1065 const IntegerType *T;
1066
1067 Id = isl_set_get_dim_id(Context, isl_dim_param, i);
Tobias Grosserabfbe632013-02-05 12:09:06 +00001068 Scev = (const SCEV *)isl_id_get_user(Id);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001069 T = dyn_cast<IntegerType>(Scev->getType());
1070 isl_id_free(Id);
1071
1072 assert(T && "Not an integer type");
1073 int Width = T->getBitWidth();
1074
Tobias Grosseredab1352013-06-21 06:41:31 +00001075 V = isl_val_int_from_si(IslCtx, Width - 1);
1076 V = isl_val_2exp(V);
1077 V = isl_val_neg(V);
1078 Context = isl_set_lower_bound_val(Context, isl_dim_param, i, V);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001079
Tobias Grosseredab1352013-06-21 06:41:31 +00001080 V = isl_val_int_from_si(IslCtx, Width - 1);
1081 V = isl_val_2exp(V);
1082 V = isl_val_sub_ui(V, 1);
1083 Context = isl_set_upper_bound_val(Context, isl_dim_param, i, V);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001084 }
1085}
1086
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001087void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001088 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001089 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001090
Tobias Grosser083d3d32014-06-28 08:59:45 +00001091 for (const auto &ParamID : ParameterIds) {
1092 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001093 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001094 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001095 }
1096
1097 // Align the parameters of all data structures to the model.
1098 Context = isl_set_align_params(Context, Space);
1099
Tobias Grosser083d3d32014-06-28 08:59:45 +00001100 for (ScopStmt *Stmt : *this)
1101 Stmt->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001102}
1103
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001104void Scop::simplifyAssumedContext() {
1105 // The parameter constraints of the iteration domains give us a set of
1106 // constraints that need to hold for all cases where at least a single
1107 // statement iteration is executed in the whole scop. We now simplify the
1108 // assumed context under the assumption that such constraints hold and at
1109 // least a single statement iteration is executed. For cases where no
1110 // statement instances are executed, the assumptions we have taken about
1111 // the executed code do not matter and can be changed.
1112 //
1113 // WARNING: This only holds if the assumptions we have taken do not reduce
1114 // the set of statement instances that are executed. Otherwise we
1115 // may run into a case where the iteration domains suggest that
1116 // for a certain set of parameter constraints no code is executed,
1117 // but in the original program some computation would have been
1118 // performed. In such a case, modifying the run-time conditions and
1119 // possibly influencing the run-time check may cause certain scops
1120 // to not be executed.
1121 //
1122 // Example:
1123 //
1124 // When delinearizing the following code:
1125 //
1126 // for (long i = 0; i < 100; i++)
1127 // for (long j = 0; j < m; j++)
1128 // A[i+p][j] = 1.0;
1129 //
1130 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
1131 // otherwise we would access out of bound data. Now, knowing that code is
1132 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1133 AssumedContext =
1134 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
1135}
1136
Johannes Doerfertb164c792014-09-18 11:17:17 +00001137/// @brief Add the minimal/maximal access in @p Set to @p User.
1138static int buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
1139 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1140 isl_pw_multi_aff *MinPMA, *MaxPMA;
1141 isl_pw_aff *LastDimAff;
1142 isl_aff *OneAff;
1143 unsigned Pos;
1144
Johannes Doerfert9143d672014-09-27 11:02:39 +00001145 // Restrict the number of parameters involved in the access as the lexmin/
1146 // lexmax computation will take too long if this number is high.
1147 //
1148 // Experiments with a simple test case using an i7 4800MQ:
1149 //
1150 // #Parameters involved | Time (in sec)
1151 // 6 | 0.01
1152 // 7 | 0.04
1153 // 8 | 0.12
1154 // 9 | 0.40
1155 // 10 | 1.54
1156 // 11 | 6.78
1157 // 12 | 30.38
1158 //
1159 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1160 unsigned InvolvedParams = 0;
1161 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1162 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1163 InvolvedParams++;
1164
1165 if (InvolvedParams > RunTimeChecksMaxParameters) {
1166 isl_set_free(Set);
1167 return -1;
1168 }
1169 }
1170
Johannes Doerfertb164c792014-09-18 11:17:17 +00001171 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1172 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1173
1174 // Adjust the last dimension of the maximal access by one as we want to
1175 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1176 // we test during code generation might now point after the end of the
1177 // allocated array but we will never dereference it anyway.
1178 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1179 "Assumed at least one output dimension");
1180 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1181 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1182 OneAff = isl_aff_zero_on_domain(
1183 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1184 OneAff = isl_aff_add_constant_si(OneAff, 1);
1185 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1186 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1187
1188 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1189
1190 isl_set_free(Set);
1191 return 0;
1192}
1193
Johannes Doerfert9143d672014-09-27 11:02:39 +00001194bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001195 // To create sound alias checks we perform the following steps:
1196 // o) Use the alias analysis and an alias set tracker to build alias sets
1197 // for all memory accesses inside the SCoP.
1198 // o) For each alias set we then map the aliasing pointers back to the
1199 // memory accesses we know, thus obtain groups of memory accesses which
1200 // might alias.
1201 // o) For each group with more then one base pointer we then compute minimal
1202 // and maximal accesses to each array in this group.
1203 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1204
1205 AliasSetTracker AST(AA);
1206
1207 DenseMap<Value *, MemoryAccess *> PtrToAcc;
1208 for (ScopStmt *Stmt : *this) {
1209 for (MemoryAccess *MA : *Stmt) {
1210 if (MA->isScalar())
1211 continue;
1212 Instruction *Acc = MA->getAccessInstruction();
1213 PtrToAcc[getPointerOperand(*Acc)] = MA;
1214 AST.add(Acc);
1215 }
1216 }
1217
1218 SmallVector<AliasGroupTy, 4> AliasGroups;
1219 for (AliasSet &AS : AST) {
1220 if (AS.isMustAlias())
1221 continue;
1222 AliasGroupTy AG;
1223 for (auto PR : AS)
1224 AG.push_back(PtrToAcc[PR.getValue()]);
1225 assert(AG.size() > 1 &&
1226 "Alias groups should contain at least two accesses");
1227 AliasGroups.push_back(std::move(AG));
1228 }
1229
1230 SmallPtrSet<const Value *, 4> BaseValues;
1231 for (auto I = AliasGroups.begin(); I != AliasGroups.end();) {
1232 BaseValues.clear();
1233 for (MemoryAccess *MA : *I)
1234 BaseValues.insert(MA->getBaseAddr());
1235 if (BaseValues.size() > 1)
1236 I++;
1237 else
1238 I = AliasGroups.erase(I);
1239 }
1240
Johannes Doerfert9143d672014-09-27 11:02:39 +00001241 bool Valid = true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001242 for (AliasGroupTy &AG : AliasGroups) {
1243 MinMaxVectorTy *MinMaxAccesses = new MinMaxVectorTy();
1244 MinMaxAccesses->reserve(AG.size());
1245
1246 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
1247 for (MemoryAccess *MA : AG)
1248 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
1249 Accesses = isl_union_map_intersect_domain(Accesses, getDomains());
1250
1251 isl_union_set *Locations = isl_union_map_range(Accesses);
1252 Locations = isl_union_set_intersect_params(Locations, getAssumedContext());
1253 Locations = isl_union_set_coalesce(Locations);
1254 Locations = isl_union_set_detect_equalities(Locations);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001255 Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
1256 MinMaxAccesses));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001257 isl_union_set_free(Locations);
Johannes Doerfertb164c792014-09-18 11:17:17 +00001258 MinMaxAliasGroups.push_back(MinMaxAccesses);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001259
1260 if (!Valid)
1261 break;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001262 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001263
1264 return Valid;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001265}
1266
Tobias Grosser0e27e242011-10-06 00:03:48 +00001267Scop::Scop(TempScop &tempScop, LoopInfo &LI, ScalarEvolution &ScalarEvolution,
1268 isl_ctx *Context)
Tobias Grosserabfbe632013-02-05 12:09:06 +00001269 : SE(&ScalarEvolution), R(tempScop.getMaxRegion()),
1270 MaxLoopDepth(tempScop.getMaxLoopDepth()) {
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001271 IslCtx = Context;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001272 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001273
Tobias Grosserabfbe632013-02-05 12:09:06 +00001274 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001275 SmallVector<unsigned, 8> Scatter;
1276
1277 Scatter.assign(MaxLoopDepth + 1, 0);
1278
1279 // Build the iteration domain, access functions and scattering functions
1280 // traversing the region tree.
1281 buildScop(tempScop, getRegion(), NestLoops, Scatter, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00001282
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001283 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001284 addParameterBounds();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001285 simplifyAssumedContext();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001286
Tobias Grosser75805372011-04-29 06:27:02 +00001287 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1288}
1289
1290Scop::~Scop() {
1291 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001292 isl_set_free(AssumedContext);
Tobias Grosser75805372011-04-29 06:27:02 +00001293
1294 // Free the statements;
Tobias Grosser083d3d32014-06-28 08:59:45 +00001295 for (ScopStmt *Stmt : *this)
1296 delete Stmt;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001297
1298 // Free the alias groups
1299 for (MinMaxVectorTy *MinMaxAccesses : MinMaxAliasGroups) {
1300 for (MinMaxAccessTy &MMA : *MinMaxAccesses) {
1301 isl_pw_multi_aff_free(MMA.first);
1302 isl_pw_multi_aff_free(MMA.second);
1303 }
1304 delete MinMaxAccesses;
1305 }
Tobias Grosser75805372011-04-29 06:27:02 +00001306}
1307
Tobias Grosser74394f02013-01-14 22:40:23 +00001308std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001309std::string Scop::getAssumedContextStr() const {
1310 return stringFromIslObj(AssumedContext);
1311}
Tobias Grosser75805372011-04-29 06:27:02 +00001312
1313std::string Scop::getNameStr() const {
1314 std::string ExitName, EntryName;
1315 raw_string_ostream ExitStr(ExitName);
1316 raw_string_ostream EntryStr(EntryName);
1317
Tobias Grosserf240b482014-01-09 10:42:15 +00001318 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001319 EntryStr.str();
1320
1321 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001322 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001323 ExitStr.str();
1324 } else
1325 ExitName = "FunctionExit";
1326
1327 return EntryName + "---" + ExitName;
1328}
1329
Tobias Grosser74394f02013-01-14 22:40:23 +00001330__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001331__isl_give isl_space *Scop::getParamSpace() const {
1332 return isl_set_get_space(this->Context);
1333}
1334
Tobias Grossere86109f2013-10-29 21:05:49 +00001335__isl_give isl_set *Scop::getAssumedContext() const {
1336 return isl_set_copy(AssumedContext);
1337}
1338
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001339void Scop::addAssumption(__isl_take isl_set *Set) {
1340 AssumedContext = isl_set_intersect(AssumedContext, Set);
1341}
1342
Tobias Grosser75805372011-04-29 06:27:02 +00001343void Scop::printContext(raw_ostream &OS) const {
1344 OS << "Context:\n";
1345
1346 if (!Context) {
1347 OS.indent(4) << "n/a\n\n";
1348 return;
1349 }
1350
1351 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001352
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001353 OS.indent(4) << "Assumed Context:\n";
1354 if (!AssumedContext) {
1355 OS.indent(4) << "n/a\n\n";
1356 return;
1357 }
1358
1359 OS.indent(4) << getAssumedContextStr() << "\n";
1360
Tobias Grosser083d3d32014-06-28 08:59:45 +00001361 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001362 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001363 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1364 }
Tobias Grosser75805372011-04-29 06:27:02 +00001365}
1366
Johannes Doerfertb164c792014-09-18 11:17:17 +00001367void Scop::printAliasAssumptions(raw_ostream &OS) const {
1368 OS.indent(4) << "Alias Groups (" << MinMaxAliasGroups.size() << "):\n";
1369 if (MinMaxAliasGroups.empty()) {
1370 OS.indent(8) << "n/a\n";
1371 return;
1372 }
1373 for (MinMaxVectorTy *MinMaxAccesses : MinMaxAliasGroups) {
1374 OS.indent(8) << "[[";
1375 for (MinMaxAccessTy &MinMacAccess : *MinMaxAccesses)
1376 OS << " <" << MinMacAccess.first << ", " << MinMacAccess.second << ">";
1377 OS << " ]]\n";
1378 }
1379}
1380
Tobias Grosser75805372011-04-29 06:27:02 +00001381void Scop::printStatements(raw_ostream &OS) const {
1382 OS << "Statements {\n";
1383
Tobias Grosser083d3d32014-06-28 08:59:45 +00001384 for (ScopStmt *Stmt : *this)
1385 OS.indent(4) << *Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001386
1387 OS.indent(4) << "}\n";
1388}
1389
Tobias Grosser75805372011-04-29 06:27:02 +00001390void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00001391 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
1392 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00001393 OS.indent(4) << "Region: " << getNameStr() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001394 printContext(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001395 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001396 printStatements(OS.indent(4));
1397}
1398
1399void Scop::dump() const { print(dbgs()); }
1400
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001401isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00001402
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001403__isl_give isl_union_set *Scop::getDomains() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001404 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001405
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001406 for (ScopStmt *Stmt : *this)
1407 Domain = isl_union_set_add_set(Domain, Stmt->getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001408
1409 return Domain;
1410}
1411
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001412__isl_give isl_union_map *Scop::getMustWrites() {
1413 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1414
1415 for (ScopStmt *Stmt : *this) {
1416 for (MemoryAccess *MA : *Stmt) {
1417 if (!MA->isMustWrite())
1418 continue;
1419
1420 isl_set *Domain = Stmt->getDomain();
1421 isl_map *AccessDomain = MA->getAccessRelation();
1422 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1423 Write = isl_union_map_add_map(Write, AccessDomain);
1424 }
1425 }
1426 return isl_union_map_coalesce(Write);
1427}
1428
1429__isl_give isl_union_map *Scop::getMayWrites() {
1430 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1431
1432 for (ScopStmt *Stmt : *this) {
1433 for (MemoryAccess *MA : *Stmt) {
1434 if (!MA->isMayWrite())
1435 continue;
1436
1437 isl_set *Domain = Stmt->getDomain();
1438 isl_map *AccessDomain = MA->getAccessRelation();
1439 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1440 Write = isl_union_map_add_map(Write, AccessDomain);
1441 }
1442 }
1443 return isl_union_map_coalesce(Write);
1444}
1445
Tobias Grosser37eb4222014-02-20 21:43:54 +00001446__isl_give isl_union_map *Scop::getWrites() {
1447 isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1448
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001449 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001450 for (MemoryAccess *MA : *Stmt) {
1451 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001452 continue;
1453
1454 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001455 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001456 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1457 Write = isl_union_map_add_map(Write, AccessDomain);
1458 }
1459 }
1460 return isl_union_map_coalesce(Write);
1461}
1462
1463__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001464 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001465
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001466 for (ScopStmt *Stmt : *this) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001467 for (MemoryAccess *MA : *Stmt) {
1468 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001469 continue;
1470
1471 isl_set *Domain = Stmt->getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001472 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001473
1474 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1475 Read = isl_union_map_add_map(Read, AccessDomain);
1476 }
1477 }
1478 return isl_union_map_coalesce(Read);
1479}
1480
1481__isl_give isl_union_map *Scop::getSchedule() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001482 isl_union_map *Schedule = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001483
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001484 for (ScopStmt *Stmt : *this)
Tobias Grosser37eb4222014-02-20 21:43:54 +00001485 Schedule = isl_union_map_add_map(Schedule, Stmt->getScattering());
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001486
Tobias Grosser37eb4222014-02-20 21:43:54 +00001487 return isl_union_map_coalesce(Schedule);
1488}
1489
1490bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
1491 bool Changed = false;
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001492 for (ScopStmt *Stmt : *this) {
Tobias Grosser37eb4222014-02-20 21:43:54 +00001493 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt->getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001494 isl_union_set *NewStmtDomain = isl_union_set_intersect(
1495 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
1496
1497 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
1498 isl_union_set_free(StmtDomain);
1499 isl_union_set_free(NewStmtDomain);
1500 continue;
1501 }
1502
1503 Changed = true;
1504
1505 isl_union_set_free(StmtDomain);
1506 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
1507
1508 if (isl_union_set_is_empty(NewStmtDomain)) {
1509 Stmt->restrictDomain(isl_set_empty(Stmt->getDomainSpace()));
1510 isl_union_set_free(NewStmtDomain);
1511 } else
1512 Stmt->restrictDomain(isl_set_from_union_set(NewStmtDomain));
1513 }
1514 isl_union_set_free(Domain);
1515 return Changed;
1516}
1517
Tobias Grosser75805372011-04-29 06:27:02 +00001518ScalarEvolution *Scop::getSE() const { return SE; }
1519
1520bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
1521 if (tempScop.getAccessFunctions(BB))
1522 return false;
1523
1524 return true;
1525}
1526
Tobias Grosser74394f02013-01-14 22:40:23 +00001527void Scop::buildScop(TempScop &tempScop, const Region &CurRegion,
1528 SmallVectorImpl<Loop *> &NestLoops,
1529 SmallVectorImpl<unsigned> &Scatter, LoopInfo &LI) {
Tobias Grosser75805372011-04-29 06:27:02 +00001530 Loop *L = castToLoop(CurRegion, LI);
1531
1532 if (L)
1533 NestLoops.push_back(L);
1534
1535 unsigned loopDepth = NestLoops.size();
1536 assert(Scatter.size() > loopDepth && "Scatter not big enough!");
1537
1538 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00001539 E = CurRegion.element_end();
1540 I != E; ++I)
Tobias Grosser75805372011-04-29 06:27:02 +00001541 if (I->isSubRegion())
1542 buildScop(tempScop, *(I->getNodeAs<Region>()), NestLoops, Scatter, LI);
1543 else {
1544 BasicBlock *BB = I->getNodeAs<BasicBlock>();
1545
1546 if (isTrivialBB(BB, tempScop))
1547 continue;
1548
Tobias Grosserabfbe632013-02-05 12:09:06 +00001549 Stmts.push_back(
1550 new ScopStmt(*this, tempScop, CurRegion, *BB, NestLoops, Scatter));
Tobias Grosser75805372011-04-29 06:27:02 +00001551
1552 // Increasing the Scattering function is OK for the moment, because
1553 // we are using a depth first iterator and the program is well structured.
1554 ++Scatter[loopDepth];
1555 }
1556
1557 if (!L)
1558 return;
1559
1560 // Exiting a loop region.
1561 Scatter[loopDepth] = 0;
1562 NestLoops.pop_back();
Tobias Grosser74394f02013-01-14 22:40:23 +00001563 ++Scatter[loopDepth - 1];
Tobias Grosser75805372011-04-29 06:27:02 +00001564}
1565
1566//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00001567ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
1568 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00001569 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001570}
1571
1572ScopInfo::~ScopInfo() {
1573 clear();
1574 isl_ctx_free(ctx);
1575}
1576
Tobias Grosser75805372011-04-29 06:27:02 +00001577void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1578 AU.addRequired<LoopInfo>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001579 AU.addRequired<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001580 AU.addRequired<ScalarEvolution>();
1581 AU.addRequired<TempScopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001582 AU.addRequired<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00001583 AU.setPreservesAll();
1584}
1585
1586bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
1587 LoopInfo &LI = getAnalysis<LoopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001588 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00001589 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1590
1591 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop(R);
1592
1593 // This region is no Scop.
1594 if (!tempScop) {
1595 scop = 0;
1596 return false;
1597 }
1598
1599 // Statistics.
1600 ++ScopFound;
Tobias Grosser74394f02013-01-14 22:40:23 +00001601 if (tempScop->getMaxLoopDepth() > 0)
1602 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00001603
Tobias Grosserb76f38532011-08-20 11:11:25 +00001604 scop = new Scop(*tempScop, LI, SE, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001605
Johannes Doerfert9143d672014-09-27 11:02:39 +00001606 if (!PollyUseRuntimeAliasChecks)
1607 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001608
Johannes Doerfert9143d672014-09-27 11:02:39 +00001609 // If a problem occurs while building the alias groups we need to delete
1610 // this SCoP and pretend it wasn't valid in the first place.
1611 if (scop->buildAliasGroups(AA))
1612 return false;
1613
1614 --ScopFound;
1615 if (tempScop->getMaxLoopDepth() > 0)
1616 --RichScopFound;
1617
1618 DEBUG(dbgs()
1619 << "\n\nNOTE: Run time checks for " << scop->getNameStr()
1620 << " could not be created as the number of parameters involved is too "
1621 "high. The SCoP will be "
1622 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust the "
1623 "maximal number of parameters but be advised that the compile time "
1624 "might increase exponentially.\n\n");
1625
1626 delete scop;
1627 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00001628 return false;
1629}
1630
1631char ScopInfo::ID = 0;
1632
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001633Pass *polly::createScopInfoPass() { return new ScopInfo(); }
1634
Tobias Grosser73600b82011-10-08 00:30:40 +00001635INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
1636 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001637 false);
Johannes Doerfertb164c792014-09-18 11:17:17 +00001638INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001639INITIALIZE_PASS_DEPENDENCY(LoopInfo);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001640INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001641INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1642INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Tobias Grosser73600b82011-10-08 00:30:40 +00001643INITIALIZE_PASS_END(ScopInfo, "polly-scops",
1644 "Polly - Create polyhedral description of Scops", false,
1645 false)