blob: 9c0e44c6b536d2c54625685a98c18059dfbfa1f4 [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
20#include "polly/ScopInfo.h"
21
22#include "polly/TempScopInfo.h"
23#include "polly/LinkAllPasses.h"
24#include "polly/Support/GICHelper.h"
25#include "polly/Support/ScopHelper.h"
26
27#include "llvm/Analysis/LoopInfo.h"
28#include "llvm/Analysis/ScalarEvolutionExpressions.h"
29#include "llvm/Analysis/RegionIterator.h"
30#include "llvm/Assembly/Writer.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/ADT/SetVector.h"
33#include "llvm/Support/CommandLine.h"
34
35#define DEBUG_TYPE "polly-scops"
36#include "llvm/Support/Debug.h"
37
38#include "isl/constraint.h"
39#include "isl/set.h"
40#include "isl/map.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000041#include "isl/aff.h"
42#include "isl/printer.h"
Tobias Grosser75805372011-04-29 06:27:02 +000043#include <sstream>
44#include <string>
45#include <vector>
46
47using namespace llvm;
48using namespace polly;
49
50STATISTIC(ScopFound, "Number of valid Scops");
51STATISTIC(RichScopFound, "Number of Scops containing a loop");
52
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000053/// Convert an int into a string.
54static std::string convertInt(int number)
55{
56 if (number == 0)
57 return "0";
58 std::string temp = "";
59 std::string returnvalue = "";
60 while (number > 0)
61 {
62 temp += number % 10 + 48;
63 number /= 10;
64 }
65 for (unsigned i = 0; i < temp.length(); i++)
66 returnvalue+=temp[temp.length() - i - 1];
67 return returnvalue;
Tobias Grosser75805372011-04-29 06:27:02 +000068}
69
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000070/// Translate a SCEVExpression into an isl_pw_aff object.
71struct SCEVAffinator : public SCEVVisitor<SCEVAffinator, isl_pw_aff*> {
72private:
73 isl_ctx *ctx;
74 int NbLoopDims;
75 const Scop *scop;
76
77 /// baseAdress is set if we analyze a memory access. It holds the base address
78 /// of this memory access.
79 const Value *baseAddress;
80
81public:
82 static isl_pw_aff *getPwAff(const ScopStmt *stmt, const SCEV *scev,
83 const Value *baseAddress) {
84 SCEVAffinator Affinator(stmt, baseAddress);
85 return Affinator.visit(scev);
86 }
87
88 isl_pw_aff *visit(const SCEV *scev) {
89 // In case the scev is contained in our list of parameters, we do not
90 // further analyze this expression, but create a new parameter in the
91 // isl_pw_aff. This allows us to treat subexpressions that we cannot
92 // translate into an piecewise affine expression, as constant parameters of
93 // the piecewise affine expression.
94 int i = 0;
95 for (Scop::const_param_iterator PI = scop->param_begin(),
96 PE = scop->param_end(); PI != PE; ++PI) {
97 if (*PI == scev) {
98 isl_id *ID = isl_id_alloc(ctx, ("p" + convertInt(i)).c_str(),
99 (void *) scev);
100 isl_dim *Dim = isl_dim_set_alloc(ctx, 1, NbLoopDims);
101 Dim = isl_dim_set_dim_id(Dim, isl_dim_param, 0, ID);
102
103 isl_set *Domain = isl_set_universe(isl_dim_copy(Dim));
104 isl_aff *Affine = isl_aff_zero(isl_local_space_from_dim(Dim));
105 Affine = isl_aff_add_coefficient_si(Affine, isl_dim_param, 0, 1);
106
107 return isl_pw_aff_alloc(Domain, Affine);
108 }
109 i++;
110 }
111
112 return SCEVVisitor<SCEVAffinator, isl_pw_aff*>::visit(scev);
113 }
114
115 SCEVAffinator(const ScopStmt *stmt, const Value *baseAddress) :
116 ctx(stmt->getParent()->getCtx()),
117 NbLoopDims(stmt->getNumIterators()),
118 scop(stmt->getParent()),
119 baseAddress(baseAddress) {};
120
121 __isl_give isl_pw_aff *visitConstant(const SCEVConstant *Constant) {
122 ConstantInt *Value = Constant->getValue();
123 isl_int v;
124 isl_int_init(v);
125
126 // LLVM does not define if an integer value is interpreted as a signed or
127 // unsigned value. Hence, without further information, it is unknown how
128 // this value needs to be converted to GMP. At the moment, we only support
129 // signed operations. So we just interpret it as signed. Later, there are
130 // two options:
131 //
132 // 1. We always interpret any value as signed and convert the values on
133 // demand.
134 // 2. We pass down the signedness of the calculation and use it to interpret
135 // this constant correctly.
136 MPZ_from_APInt(v, Value->getValue(), /* isSigned */ true);
137
138 isl_dim *dim = isl_dim_set_alloc(ctx, 0, NbLoopDims);
139 isl_local_space *ls = isl_local_space_from_dim(isl_dim_copy(dim));
140 isl_aff *Affine = isl_aff_zero(ls);
141 isl_set *Domain = isl_set_universe(dim);
142
143 Affine = isl_aff_add_constant(Affine, v);
144 isl_int_clear(v);
145
146 return isl_pw_aff_alloc(Domain, Affine);
147 }
148
149 __isl_give isl_pw_aff *visitTruncateExpr(const SCEVTruncateExpr* Expr) {
150 assert(0 && "Not yet supported");
151 }
152
153 __isl_give isl_pw_aff *visitZeroExtendExpr(const SCEVZeroExtendExpr * Expr) {
154 assert(0 && "Not yet supported");
155 }
156
157 __isl_give isl_pw_aff *visitSignExtendExpr(const SCEVSignExtendExpr* Expr) {
158 // Assuming the value is signed, a sign extension is basically a noop.
159 // TODO: Reconsider this as soon as we support unsigned values.
160 return visit(Expr->getOperand());
161 }
162
163 __isl_give isl_pw_aff *visitAddExpr(const SCEVAddExpr* Expr) {
164 isl_pw_aff *Sum = visit(Expr->getOperand(0));
165
166 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
167 isl_pw_aff *NextSummand = visit(Expr->getOperand(i));
168 Sum = isl_pw_aff_add(Sum, NextSummand);
169 }
170
171 // TODO: Check for NSW and NUW.
172
173 return Sum;
174 }
175
176 __isl_give isl_pw_aff *visitMulExpr(const SCEVMulExpr* Expr) {
177 isl_pw_aff *Product = visit(Expr->getOperand(0));
178
179 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
180 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
181
182 if (!isl_pw_aff_is_cst(Product) && !isl_pw_aff_is_cst(NextOperand)) {
183 isl_pw_aff_free(Product);
184 isl_pw_aff_free(NextOperand);
185 return NULL;
186 }
187
188 Product = isl_pw_aff_mul(Product, NextOperand);
189 }
190
191 // TODO: Check for NSW and NUW.
192 return Product;
193 }
194
195 __isl_give isl_pw_aff *visitUDivExpr(const SCEVUDivExpr* Expr) {
196 assert(0 && "Not yet supported");
197 }
198
199 int getLoopDepth(const Loop *L) {
200 Loop *outerLoop =
201 scop->getRegion().outermostLoopInRegion(const_cast<Loop*>(L));
202 return L->getLoopDepth() - outerLoop->getLoopDepth();
203 }
204
205 __isl_give isl_pw_aff *visitAddRecExpr(const SCEVAddRecExpr* Expr) {
206 assert(Expr->isAffine() && "Only affine AddRecurrences allowed");
207
208 isl_pw_aff *Start = visit(Expr->getStart());
209 isl_pw_aff *Step = visit(Expr->getOperand(1));
210 isl_dim *Dim = isl_dim_set_alloc (ctx, 0, NbLoopDims);
211 isl_local_space *LocalSpace = isl_local_space_from_dim (Dim);
212
213 int loopDimension = getLoopDepth(Expr->getLoop());
214
215 isl_aff *LAff = isl_aff_set_coefficient_si (isl_aff_zero (LocalSpace),
216 isl_dim_set, loopDimension, 1);
217 isl_pw_aff *LPwAff = isl_pw_aff_from_aff(LAff);
218
219 // TODO: Do we need to check for NSW and NUW?
220 return isl_pw_aff_add(Start, isl_pw_aff_mul(Step, LPwAff));
221 }
222
223 __isl_give isl_pw_aff *visitSMaxExpr(const SCEVSMaxExpr* Expr) {
224 isl_pw_aff *Max = visit(Expr->getOperand(0));
225
226 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
227 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
228 Max = isl_pw_aff_max(Max, NextOperand);
229 }
230
231 return Max;
232 }
233
234 __isl_give isl_pw_aff *visitUMaxExpr(const SCEVUMaxExpr* Expr) {
235 assert(0 && "Not yet supported");
236 }
237
238 __isl_give isl_pw_aff *visitUnknown(const SCEVUnknown* Expr) {
239 Value *Value = Expr->getValue();
240
241 isl_dim *Dim;
242
243 /// If baseAddress is set, we ignore its Value object in the scev and do not
244 /// add it to the isl_pw_aff. This is because it is regarded as defining the
245 /// name of an array, in contrast to its array subscript.
246 if (baseAddress != Value) {
247 isl_id *ID = isl_id_alloc(ctx, Value->getNameStr().c_str(), Value);
248 Dim = isl_dim_set_alloc(ctx, 1, NbLoopDims);
249 Dim = isl_dim_set_dim_id(Dim, isl_dim_param, 0, ID);
250 } else {
251 Dim = isl_dim_set_alloc(ctx, 0, NbLoopDims);
252 }
253
254 isl_set *Domain = isl_set_universe(isl_dim_copy(Dim));
255 isl_aff *Affine = isl_aff_zero(isl_local_space_from_dim(Dim));
256
257 if (baseAddress != Value)
258 Affine = isl_aff_add_coefficient_si(Affine, isl_dim_param, 0, 1);
259
260 return isl_pw_aff_alloc(Domain, Affine);
261 }
262};
263
Tobias Grosser75805372011-04-29 06:27:02 +0000264//===----------------------------------------------------------------------===//
265
266MemoryAccess::~MemoryAccess() {
Tobias Grosser54a86e62011-08-18 06:31:46 +0000267 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000268 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000269}
270
271static void replace(std::string& str, const std::string& find,
272 const std::string& replace) {
273 size_t pos = 0;
274 while((pos = str.find(find, pos)) != std::string::npos)
275 {
276 str.replace(pos, find.length(), replace);
277 pos += replace.length();
278 }
279}
280
281static void makeIslCompatible(std::string& str) {
282 replace(str, ".", "_");
Tobias Grosser3b660f82011-08-03 00:12:11 +0000283 replace(str, "\"", "_");
Tobias Grosser75805372011-04-29 06:27:02 +0000284}
285
286void MemoryAccess::setBaseName() {
287 raw_string_ostream OS(BaseName);
288 WriteAsOperand(OS, getBaseAddr(), false);
289 BaseName = OS.str();
290
291 // Remove the % in the name. This is not supported by isl.
292 BaseName.erase(0,1);
293 makeIslCompatible(BaseName);
294 BaseName = "MemRef_" + BaseName;
295}
296
297std::string MemoryAccess::getAccessFunctionStr() const {
298 return stringFromIslObj(getAccessFunction());
299}
300
301isl_basic_map *MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosserfa7bc2f2011-08-20 00:03:28 +0000302 isl_dim *dim = isl_dim_alloc(Statement->getIslContext(), 0,
Tobias Grosser75805372011-04-29 06:27:02 +0000303 Statement->getNumIterators(), 1);
304 setBaseName();
305
306 dim = isl_dim_set_tuple_name(dim, isl_dim_out, getBaseName().c_str());
307 dim = isl_dim_set_tuple_name(dim, isl_dim_in, Statement->getBaseName());
308
309 return isl_basic_map_universe(dim);
310}
311
312MemoryAccess::MemoryAccess(const SCEVAffFunc &AffFunc, ScopStmt *Statement) {
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000313 newAccessRelation = NULL;
Tobias Grosser75805372011-04-29 06:27:02 +0000314 BaseAddr = AffFunc.getBaseAddr();
315 Type = AffFunc.isRead() ? Read : Write;
316 statement = Statement;
317
318 setBaseName();
319
Tobias Grosser7d4cee42011-08-19 23:34:28 +0000320 isl_pw_aff *Affine = SCEVAffinator::getPwAff(Statement, AffFunc.OriginalSCEV,
321 AffFunc.getBaseAddr());
Tobias Grosser75805372011-04-29 06:27:02 +0000322
Tobias Grosser7d4cee42011-08-19 23:34:28 +0000323 // Devide the access function by the size of the elements in the array.
324 //
325 // A stride one array access in C expressed as A[i] is expressed in LLVM-IR
326 // as something like A[i * elementsize]. This hides the fact that two
327 // subsequent values of 'i' index two values that are stored next to each
328 // other in memory. By this devision we make this characteristic obvious
329 // again.
Tobias Grosser75805372011-04-29 06:27:02 +0000330 isl_int v;
331 isl_int_init(v);
Tobias Grosser75805372011-04-29 06:27:02 +0000332 isl_int_set_si(v, AffFunc.getElemSizeInBytes());
Tobias Grosser7d4cee42011-08-19 23:34:28 +0000333 Affine = isl_pw_aff_scale_down(Affine, v);
334 isl_int_clear(v);
Tobias Grosser75805372011-04-29 06:27:02 +0000335
Tobias Grosser7d4cee42011-08-19 23:34:28 +0000336 AccessRelation = isl_map_from_pw_aff(Affine);
337 AccessRelation = isl_map_set_tuple_name(AccessRelation, isl_dim_in,
338 Statement->getBaseName());
Tobias Grosser75805372011-04-29 06:27:02 +0000339 AccessRelation = isl_map_set_tuple_name(AccessRelation, isl_dim_out,
340 getBaseName().c_str());
Tobias Grosser30b8a092011-08-18 07:51:37 +0000341
Tobias Grosser7d4cee42011-08-19 23:34:28 +0000342 isl_dim *Model = isl_set_get_dim(Statement->getParent()->getContext());
343 AccessRelation = isl_map_align_params(AccessRelation, Model);
Tobias Grosser75805372011-04-29 06:27:02 +0000344}
345
346MemoryAccess::MemoryAccess(const Value *BaseAddress, ScopStmt *Statement) {
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000347 newAccessRelation = NULL;
Tobias Grosser75805372011-04-29 06:27:02 +0000348 BaseAddr = BaseAddress;
349 Type = Read;
350 statement = Statement;
351
352 isl_basic_map *BasicAccessMap = createBasicAccessMap(Statement);
353 AccessRelation = isl_map_from_basic_map(BasicAccessMap);
Tobias Grosserfa7bc2f2011-08-20 00:03:28 +0000354 isl_dim *Model = isl_set_get_dim(Statement->getParent()->getContext());
355 AccessRelation = isl_map_align_params(AccessRelation, Model);
Tobias Grosser75805372011-04-29 06:27:02 +0000356}
357
358void MemoryAccess::print(raw_ostream &OS) const {
359 OS.indent(12) << (isRead() ? "Read" : "Write") << "Access := \n";
360 OS.indent(16) << getAccessFunctionStr() << ";\n";
361}
362
363void MemoryAccess::dump() const {
364 print(errs());
365}
366
367// Create a map in the size of the provided set domain, that maps from the
368// one element of the provided set domain to another element of the provided
369// set domain.
370// The mapping is limited to all points that are equal in all but the last
371// dimension and for which the last dimension of the input is strict smaller
372// than the last dimension of the output.
373//
374// getEqualAndLarger(set[i0, i1, ..., iX]):
375//
376// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
377// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
378//
379static isl_map *getEqualAndLarger(isl_dim *setDomain) {
380 isl_dim *mapDomain = isl_dim_map_from_set(setDomain);
381 isl_basic_map *bmap = isl_basic_map_universe(mapDomain);
382
383 // Set all but the last dimension to be equal for the input and output
384 //
385 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
386 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
387 for (unsigned i = 0; i < isl_basic_map_n_in(bmap) - 1; ++i) {
388 isl_int v;
389 isl_int_init(v);
390 isl_constraint *c = isl_equality_alloc(isl_basic_map_get_dim(bmap));
391
392 isl_int_set_si(v, 1);
393 isl_constraint_set_coefficient(c, isl_dim_in, i, v);
394 isl_int_set_si(v, -1);
395 isl_constraint_set_coefficient(c, isl_dim_out, i, v);
396
397 bmap = isl_basic_map_add_constraint(bmap, c);
398
399 isl_int_clear(v);
400 }
401
402 // Set the last dimension of the input to be strict smaller than the
403 // last dimension of the output.
404 //
405 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
406 //
407 unsigned lastDimension = isl_basic_map_n_in(bmap) - 1;
408 isl_int v;
409 isl_int_init(v);
410 isl_constraint *c = isl_inequality_alloc(isl_basic_map_get_dim(bmap));
411 isl_int_set_si(v, -1);
412 isl_constraint_set_coefficient(c, isl_dim_in, lastDimension, v);
413 isl_int_set_si(v, 1);
414 isl_constraint_set_coefficient(c, isl_dim_out, lastDimension, v);
415 isl_int_set_si(v, -1);
416 isl_constraint_set_constant(c, v);
417 isl_int_clear(v);
418
419 bmap = isl_basic_map_add_constraint(bmap, c);
420
421 return isl_map_from_basic_map(bmap);
422}
423
424isl_set *MemoryAccess::getStride(const isl_set *domainSubset) const {
425 isl_map *accessRelation = isl_map_copy(getAccessFunction());
426 isl_set *scatteringDomain = isl_set_copy(const_cast<isl_set*>(domainSubset));
427 isl_map *scattering = isl_map_copy(getStatement()->getScattering());
428
429 scattering = isl_map_reverse(scattering);
430 int difference = isl_map_n_in(scattering) - isl_set_n_dim(scatteringDomain);
431 scattering = isl_map_project_out(scattering, isl_dim_in,
432 isl_set_n_dim(scatteringDomain),
433 difference);
434
435 // Remove all names of the scattering dimensions, as the names may be lost
436 // anyways during the project. This leads to consistent results.
437 scattering = isl_map_set_tuple_name(scattering, isl_dim_in, "");
438 scatteringDomain = isl_set_set_tuple_name(scatteringDomain, "");
439
440 isl_map *nextScatt = getEqualAndLarger(isl_set_get_dim(scatteringDomain));
441 nextScatt = isl_map_lexmin(nextScatt);
442
443 scattering = isl_map_intersect_domain(scattering, scatteringDomain);
444
445 nextScatt = isl_map_apply_range(nextScatt, isl_map_copy(scattering));
446 nextScatt = isl_map_apply_range(nextScatt, isl_map_copy(accessRelation));
447 nextScatt = isl_map_apply_domain(nextScatt, scattering);
448 nextScatt = isl_map_apply_domain(nextScatt, accessRelation);
449
450 return isl_map_deltas(nextScatt);
451}
452
453bool MemoryAccess::isStrideZero(const isl_set *domainSubset) const {
454 isl_set *stride = getStride(domainSubset);
455 isl_constraint *c = isl_equality_alloc(isl_set_get_dim(stride));
456
457 isl_int v;
458 isl_int_init(v);
459 isl_int_set_si(v, 1);
460 isl_constraint_set_coefficient(c, isl_dim_set, 0, v);
461 isl_int_set_si(v, 0);
462 isl_constraint_set_constant(c, v);
463 isl_int_clear(v);
464
465 isl_basic_set *bset = isl_basic_set_universe(isl_set_get_dim(stride));
466
467 bset = isl_basic_set_add_constraint(bset, c);
468 isl_set *strideZero = isl_set_from_basic_set(bset);
469
470 return isl_set_is_equal(stride, strideZero);
471}
472
473bool MemoryAccess::isStrideOne(const isl_set *domainSubset) const {
474 isl_set *stride = getStride(domainSubset);
475 isl_constraint *c = isl_equality_alloc(isl_set_get_dim(stride));
476
477 isl_int v;
478 isl_int_init(v);
479 isl_int_set_si(v, 1);
480 isl_constraint_set_coefficient(c, isl_dim_set, 0, v);
481 isl_int_set_si(v, -1);
482 isl_constraint_set_constant(c, v);
483 isl_int_clear(v);
484
485 isl_basic_set *bset = isl_basic_set_universe(isl_set_get_dim(stride));
486
487 bset = isl_basic_set_add_constraint(bset, c);
488 isl_set *strideZero = isl_set_from_basic_set(bset);
489
490 return isl_set_is_equal(stride, strideZero);
491}
492
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000493void MemoryAccess::setNewAccessFunction(isl_map *newAccess) {
494 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000495}
Tobias Grosser75805372011-04-29 06:27:02 +0000496
497//===----------------------------------------------------------------------===//
498void ScopStmt::buildScattering(SmallVectorImpl<unsigned> &Scatter) {
499 unsigned NumberOfIterators = getNumIterators();
500 unsigned ScatDim = Parent.getMaxLoopDepth() * 2 + 1;
Tobias Grosserfa7bc2f2011-08-20 00:03:28 +0000501 isl_dim *dim = isl_dim_alloc(Parent.getCtx(), 0, NumberOfIterators, ScatDim);
Tobias Grosser75805372011-04-29 06:27:02 +0000502 dim = isl_dim_set_tuple_name(dim, isl_dim_out, "scattering");
503 dim = isl_dim_set_tuple_name(dim, isl_dim_in, getBaseName());
504 isl_basic_map *bmap = isl_basic_map_universe(isl_dim_copy(dim));
505 isl_int v;
506 isl_int_init(v);
507
508 // Loop dimensions.
509 for (unsigned i = 0; i < NumberOfIterators; ++i) {
510 isl_constraint *c = isl_equality_alloc(isl_dim_copy(dim));
511 isl_int_set_si(v, 1);
512 isl_constraint_set_coefficient(c, isl_dim_out, 2 * i + 1, v);
513 isl_int_set_si(v, -1);
514 isl_constraint_set_coefficient(c, isl_dim_in, i, v);
515
516 bmap = isl_basic_map_add_constraint(bmap, c);
517 }
518
519 // Constant dimensions
520 for (unsigned i = 0; i < NumberOfIterators + 1; ++i) {
521 isl_constraint *c = isl_equality_alloc(isl_dim_copy(dim));
522 isl_int_set_si(v, -1);
523 isl_constraint_set_coefficient(c, isl_dim_out, 2 * i, v);
524 isl_int_set_si(v, Scatter[i]);
525 isl_constraint_set_constant(c, v);
526
527 bmap = isl_basic_map_add_constraint(bmap, c);
528 }
529
530 // Fill scattering dimensions.
531 for (unsigned i = 2 * NumberOfIterators + 1; i < ScatDim ; ++i) {
532 isl_constraint *c = isl_equality_alloc(isl_dim_copy(dim));
533 isl_int_set_si(v, 1);
534 isl_constraint_set_coefficient(c, isl_dim_out, i, v);
535 isl_int_set_si(v, 0);
536 isl_constraint_set_constant(c, v);
537
538 bmap = isl_basic_map_add_constraint(bmap, c);
539 }
540
541 isl_int_clear(v);
542 isl_dim_free(dim);
543 Scattering = isl_map_from_basic_map(bmap);
Tobias Grosserfa7bc2f2011-08-20 00:03:28 +0000544 isl_dim *Model = isl_set_get_dim(getParent()->getContext());
545 Scattering = isl_map_align_params(Scattering, Model);
Tobias Grosser75805372011-04-29 06:27:02 +0000546}
547
548void ScopStmt::buildAccesses(TempScop &tempScop, const Region &CurRegion) {
549 const AccFuncSetType *AccFuncs = tempScop.getAccessFunctions(BB);
550
551 for (AccFuncSetType::const_iterator I = AccFuncs->begin(),
552 E = AccFuncs->end(); I != E; ++I) {
553 MemAccs.push_back(new MemoryAccess(I->first, this));
554 InstructionToAccess[I->second] = MemAccs.back();
555 }
556}
557
Tobias Grosserd2795d02011-08-18 07:51:40 +0000558isl_set *ScopStmt::toConditionSet(const Comparison &Comp, isl_dim *dim) const {
559 isl_pw_aff *LHS = SCEVAffinator::getPwAff(this, Comp.getLHS()->OriginalSCEV,
560 0);
561 isl_pw_aff *RHS = SCEVAffinator::getPwAff(this, Comp.getRHS()->OriginalSCEV,
562 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000563
Tobias Grosserd2795d02011-08-18 07:51:40 +0000564 isl_set *set;
Tobias Grosser75805372011-04-29 06:27:02 +0000565
Tobias Grosserd2795d02011-08-18 07:51:40 +0000566 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000567 case ICmpInst::ICMP_EQ:
Tobias Grosserd2795d02011-08-18 07:51:40 +0000568 set = isl_pw_aff_eq_set(LHS, RHS);
Tobias Grosser75805372011-04-29 06:27:02 +0000569 break;
570 case ICmpInst::ICMP_NE:
Tobias Grosserd2795d02011-08-18 07:51:40 +0000571 set = isl_pw_aff_ne_set(LHS, RHS);
Tobias Grosser75805372011-04-29 06:27:02 +0000572 break;
573 case ICmpInst::ICMP_SLT:
Tobias Grosserd2795d02011-08-18 07:51:40 +0000574 set = isl_pw_aff_lt_set(LHS, RHS);
Tobias Grosser75805372011-04-29 06:27:02 +0000575 break;
576 case ICmpInst::ICMP_SLE:
Tobias Grosserd2795d02011-08-18 07:51:40 +0000577 set = isl_pw_aff_le_set(LHS, RHS);
Tobias Grosser75805372011-04-29 06:27:02 +0000578 break;
Tobias Grosserd2795d02011-08-18 07:51:40 +0000579 case ICmpInst::ICMP_SGT:
580 set = isl_pw_aff_gt_set(LHS, RHS);
Tobias Grosser75805372011-04-29 06:27:02 +0000581 break;
582 case ICmpInst::ICMP_SGE:
Tobias Grosserd2795d02011-08-18 07:51:40 +0000583 set = isl_pw_aff_ge_set(LHS, RHS);
Tobias Grosser75805372011-04-29 06:27:02 +0000584 break;
Tobias Grosserd2795d02011-08-18 07:51:40 +0000585 case ICmpInst::ICMP_ULT:
586 case ICmpInst::ICMP_UGT:
587 case ICmpInst::ICMP_ULE:
Tobias Grosser75805372011-04-29 06:27:02 +0000588 case ICmpInst::ICMP_UGE:
Tobias Grosserd2795d02011-08-18 07:51:40 +0000589 llvm_unreachable("Unsigned comparisons not yet supported");
Tobias Grosser75805372011-04-29 06:27:02 +0000590 default:
591 llvm_unreachable("Non integer predicate not supported");
592 }
593
Tobias Grosserd2795d02011-08-18 07:51:40 +0000594 set = isl_set_set_tuple_name(set, isl_dim_get_tuple_name(dim, isl_dim_set));
595
596 return set;
Tobias Grosser75805372011-04-29 06:27:02 +0000597}
598
Tobias Grosserd2795d02011-08-18 07:51:40 +0000599isl_set *ScopStmt::toUpperLoopBound(const SCEVAffFunc &UpperBound, isl_dim *Dim,
Tobias Grosser75805372011-04-29 06:27:02 +0000600 unsigned BoundedDimension) const {
Tobias Grosserd2795d02011-08-18 07:51:40 +0000601 // FIXME: We should choose a consistent scheme of when to name the dimensions.
602 isl_dim *UnnamedDim = isl_dim_copy(Dim);
603 UnnamedDim = isl_dim_set_tuple_name(UnnamedDim, isl_dim_set, 0);
604 isl_local_space *LocalSpace = isl_local_space_from_dim (UnnamedDim);
605 isl_aff *LAff = isl_aff_set_coefficient_si (isl_aff_zero (LocalSpace),
606 isl_dim_set, BoundedDimension, 1);
607 isl_pw_aff *BoundedDim = isl_pw_aff_from_aff(LAff);
608 isl_pw_aff *Bound = SCEVAffinator::getPwAff(this, UpperBound.OriginalSCEV, 0);
609 isl_set *set = isl_pw_aff_le_set(BoundedDim, Bound);
610 set = isl_set_set_tuple_name(set, isl_dim_get_tuple_name(Dim, isl_dim_set));
611 return set;
Tobias Grosser75805372011-04-29 06:27:02 +0000612}
613
614void ScopStmt::buildIterationDomainFromLoops(TempScop &tempScop) {
Tobias Grosser30b8a092011-08-18 07:51:37 +0000615 isl_dim *dim = isl_dim_set_alloc(Parent.getCtx(), 0,
Tobias Grosser75805372011-04-29 06:27:02 +0000616 getNumIterators());
617 dim = isl_dim_set_tuple_name(dim, isl_dim_set, getBaseName());
618
619 Domain = isl_set_universe(isl_dim_copy(dim));
Tobias Grosser30b8a092011-08-18 07:51:37 +0000620 Domain = isl_set_align_params(Domain, isl_set_get_dim(Parent.getContext()));
Tobias Grosser75805372011-04-29 06:27:02 +0000621
622 isl_int v;
623 isl_int_init(v);
624
625 for (int i = 0, e = getNumIterators(); i != e; ++i) {
626 // Lower bound: IV >= 0.
627 isl_basic_set *bset = isl_basic_set_universe(isl_dim_copy(dim));
628 isl_constraint *c = isl_inequality_alloc(isl_dim_copy(dim));
629 isl_int_set_si(v, 1);
630 isl_constraint_set_coefficient(c, isl_dim_set, i, v);
631 bset = isl_basic_set_add_constraint(bset, c);
632 Domain = isl_set_intersect(Domain, isl_set_from_basic_set(bset));
633
634 // Upper bound: IV <= NumberOfIterations.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000635 const Loop *L = getLoopForDimension(i);
Tobias Grosser75805372011-04-29 06:27:02 +0000636 const SCEVAffFunc &UpperBound = tempScop.getLoopBound(L);
637 isl_set *UpperBoundSet = toUpperLoopBound(UpperBound, isl_dim_copy(dim), i);
638 Domain = isl_set_intersect(Domain, UpperBoundSet);
639 }
640
641 isl_int_clear(v);
642}
643
644void ScopStmt::addConditionsToDomain(TempScop &tempScop,
645 const Region &CurRegion) {
646 isl_dim *dim = isl_set_get_dim(Domain);
647 const Region *TopR = tempScop.getMaxRegion().getParent(),
648 *CurR = &CurRegion;
649 const BasicBlock *CurEntry = BB;
650
651 // Build BB condition constrains, by traveling up the region tree.
652 do {
653 assert(CurR && "We exceed the top region?");
654 // Skip when multiple regions share the same entry.
655 if (CurEntry != CurR->getEntry()) {
656 if (const BBCond *Cnd = tempScop.getBBCond(CurEntry))
657 for (BBCond::const_iterator I = Cnd->begin(), E = Cnd->end();
658 I != E; ++I) {
659 isl_set *c = toConditionSet(*I, dim);
660 Domain = isl_set_intersect(Domain, c);
661 }
662 }
663 CurEntry = CurR->getEntry();
664 CurR = CurR->getParent();
665 } while (TopR != CurR);
666
667 isl_dim_free(dim);
668}
669
670void ScopStmt::buildIterationDomain(TempScop &tempScop, const Region &CurRegion)
671{
672 buildIterationDomainFromLoops(tempScop);
673 addConditionsToDomain(tempScop, CurRegion);
674}
675
676ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop,
677 const Region &CurRegion, BasicBlock &bb,
678 SmallVectorImpl<Loop*> &NestLoops,
679 SmallVectorImpl<unsigned> &Scatter)
680 : Parent(parent), BB(&bb), IVS(NestLoops.size()) {
681 // Setup the induction variables.
682 for (unsigned i = 0, e = NestLoops.size(); i < e; ++i) {
683 PHINode *PN = NestLoops[i]->getCanonicalInductionVariable();
684 assert(PN && "Non canonical IV in Scop!");
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000685 IVS[i] = std::make_pair(PN, NestLoops[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000686 }
687
688 raw_string_ostream OS(BaseName);
689 WriteAsOperand(OS, &bb, false);
690 BaseName = OS.str();
691
692 // Remove the % in the name. This is not supported by isl.
693 BaseName.erase(0, 1);
694 makeIslCompatible(BaseName);
695 BaseName = "Stmt_" + BaseName;
696
697 buildIterationDomain(tempScop, CurRegion);
698 buildScattering(Scatter);
699 buildAccesses(tempScop, CurRegion);
700
701 IsReduction = tempScop.is_Reduction(*BB);
702}
703
704ScopStmt::ScopStmt(Scop &parent, SmallVectorImpl<unsigned> &Scatter)
705 : Parent(parent), BB(NULL), IVS(0) {
706
707 BaseName = "FinalRead";
708
709 // Build iteration domain.
710 std::string IterationDomainString = "{[i0] : i0 = 0}";
711 Domain = isl_set_read_from_str(Parent.getCtx(), IterationDomainString.c_str(),
712 -1);
Tobias Grosser75805372011-04-29 06:27:02 +0000713 Domain = isl_set_set_tuple_name(Domain, getBaseName());
Tobias Grosserfa7bc2f2011-08-20 00:03:28 +0000714 isl_dim *Model = isl_set_get_dim(getParent()->getContext());
715 Domain = isl_set_align_params(Domain, isl_dim_copy(Model));
Tobias Grosser75805372011-04-29 06:27:02 +0000716
717 // Build scattering.
718 unsigned ScatDim = Parent.getMaxLoopDepth() * 2 + 1;
Tobias Grosserfa7bc2f2011-08-20 00:03:28 +0000719 isl_dim *dim = isl_dim_alloc(Parent.getCtx(), 0, 1, ScatDim);
Tobias Grosser75805372011-04-29 06:27:02 +0000720 dim = isl_dim_set_tuple_name(dim, isl_dim_out, "scattering");
721 dim = isl_dim_set_tuple_name(dim, isl_dim_in, getBaseName());
722 isl_basic_map *bmap = isl_basic_map_universe(isl_dim_copy(dim));
723 isl_int v;
724 isl_int_init(v);
725
726 isl_constraint *c = isl_equality_alloc(dim);
727 isl_int_set_si(v, -1);
728 isl_constraint_set_coefficient(c, isl_dim_out, 0, v);
729
730 // TODO: This is incorrect. We should not use a very large number to ensure
731 // that this statement is executed last.
732 isl_int_set_si(v, 200000000);
733 isl_constraint_set_constant(c, v);
734
735 bmap = isl_basic_map_add_constraint(bmap, c);
736 isl_int_clear(v);
737 Scattering = isl_map_from_basic_map(bmap);
Tobias Grosserfa7bc2f2011-08-20 00:03:28 +0000738 Scattering = isl_map_align_params(Scattering, Model);
Tobias Grosser75805372011-04-29 06:27:02 +0000739
740 // Build memory accesses, use SetVector to keep the order of memory accesses
741 // and prevent the same memory access inserted more than once.
742 SetVector<const Value*> BaseAddressSet;
743
744 for (Scop::const_iterator SI = Parent.begin(), SE = Parent.end(); SI != SE;
745 ++SI) {
746 ScopStmt *Stmt = *SI;
747
748 for (MemoryAccessVec::const_iterator I = Stmt->memacc_begin(),
749 E = Stmt->memacc_end(); I != E; ++I)
750 BaseAddressSet.insert((*I)->getBaseAddr());
751 }
752
753 for (SetVector<const Value*>::iterator BI = BaseAddressSet.begin(),
754 BE = BaseAddressSet.end(); BI != BE; ++BI)
755 MemAccs.push_back(new MemoryAccess(*BI, this));
756
757 IsReduction = false;
758}
759
760std::string ScopStmt::getDomainStr() const {
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +0000761 isl_set *domain = getDomain();
762 std::string string = stringFromIslObj(domain);
763 isl_set_free(domain);
764 return string;
Tobias Grosser75805372011-04-29 06:27:02 +0000765}
766
767std::string ScopStmt::getScatteringStr() const {
768 return stringFromIslObj(getScattering());
769}
770
771unsigned ScopStmt::getNumParams() const {
772 return Parent.getNumParams();
773}
774
775unsigned ScopStmt::getNumIterators() const {
776 // The final read has one dimension with one element.
777 if (!BB)
778 return 1;
779
780 return IVS.size();
781}
782
783unsigned ScopStmt::getNumScattering() const {
784 return isl_map_dim(Scattering, isl_dim_out);
785}
786
787const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
788
789const PHINode *ScopStmt::getInductionVariableForDimension(unsigned Dimension)
790 const {
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000791 return IVS[Dimension].first;
792}
793
794const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
795 return IVS[Dimension].second;
Tobias Grosser75805372011-04-29 06:27:02 +0000796}
797
798const SCEVAddRecExpr *ScopStmt::getSCEVForDimension(unsigned Dimension)
799 const {
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000800 PHINode *PN =
801 const_cast<PHINode*>(getInductionVariableForDimension(Dimension));
Tobias Grosser75805372011-04-29 06:27:02 +0000802 return cast<SCEVAddRecExpr>(getParent()->getSE()->getSCEV(PN));
803}
804
805isl_ctx *ScopStmt::getIslContext() {
806 return Parent.getCtx();
807}
808
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +0000809isl_set *ScopStmt::getDomain() const {
810 return isl_set_copy(Domain);
811}
812
Tobias Grosser75805372011-04-29 06:27:02 +0000813ScopStmt::~ScopStmt() {
814 while (!MemAccs.empty()) {
815 delete MemAccs.back();
816 MemAccs.pop_back();
817 }
818
819 isl_set_free(Domain);
820 isl_map_free(Scattering);
821}
822
823void ScopStmt::print(raw_ostream &OS) const {
824 OS << "\t" << getBaseName() << "\n";
825
826 OS.indent(12) << "Domain :=\n";
827
828 if (Domain) {
829 OS.indent(16) << getDomainStr() << ";\n";
830 } else
831 OS.indent(16) << "n/a\n";
832
833 OS.indent(12) << "Scattering :=\n";
834
835 if (Domain) {
836 OS.indent(16) << getScatteringStr() << ";\n";
837 } else
838 OS.indent(16) << "n/a\n";
839
840 for (MemoryAccessVec::const_iterator I = MemAccs.begin(), E = MemAccs.end();
841 I != E; ++I)
842 (*I)->print(OS);
843}
844
845void ScopStmt::dump() const { print(dbgs()); }
846
847//===----------------------------------------------------------------------===//
848/// Scop class implement
849Scop::Scop(TempScop &tempScop, LoopInfo &LI, ScalarEvolution &ScalarEvolution)
850 : SE(&ScalarEvolution), R(tempScop.getMaxRegion()),
851 MaxLoopDepth(tempScop.getMaxLoopDepth()) {
852 isl_ctx *ctx = isl_ctx_alloc();
853
854 ParamSetType &Params = tempScop.getParamSet();
855 Parameters.insert(Parameters.begin(), Params.begin(), Params.end());
856
857 isl_dim *dim = isl_dim_set_alloc(ctx, getNumParams(), 0);
858
Tobias Grosser30b8a092011-08-18 07:51:37 +0000859 int i = 0;
860 for (ParamSetType::iterator PI = Params.begin(), PE = Params.end();
861 PI != PE; ++PI) {
862 const SCEV *scev = *PI;
863 isl_id *id = isl_id_alloc(ctx,
864 ("p" + convertInt(i)).c_str(),
865 (void *) scev);
866 dim = isl_dim_set_dim_id(dim, isl_dim_param, i, id);
867 i++;
868 }
869
Tobias Grosser75805372011-04-29 06:27:02 +0000870 // TODO: Insert relations between parameters.
871 // TODO: Insert constraints on parameters.
872 Context = isl_set_universe (dim);
873
874 SmallVector<Loop*, 8> NestLoops;
875 SmallVector<unsigned, 8> Scatter;
876
877 Scatter.assign(MaxLoopDepth + 1, 0);
878
879 // Build the iteration domain, access functions and scattering functions
880 // traversing the region tree.
881 buildScop(tempScop, getRegion(), NestLoops, Scatter, LI);
882 Stmts.push_back(new ScopStmt(*this, Scatter));
883
Tobias Grosser75805372011-04-29 06:27:02 +0000884 assert(NestLoops.empty() && "NestLoops not empty at top level!");
885}
886
887Scop::~Scop() {
888 isl_set_free(Context);
889
890 // Free the statements;
891 for (iterator I = begin(), E = end(); I != E; ++I)
892 delete *I;
893
894 // Do we need a singleton to manage this?
895 //isl_ctx_free(ctx);
896}
897
898std::string Scop::getContextStr() const {
899 return stringFromIslObj(getContext());
900}
901
902std::string Scop::getNameStr() const {
903 std::string ExitName, EntryName;
904 raw_string_ostream ExitStr(ExitName);
905 raw_string_ostream EntryStr(EntryName);
906
907 WriteAsOperand(EntryStr, R.getEntry(), false);
908 EntryStr.str();
909
910 if (R.getExit()) {
911 WriteAsOperand(ExitStr, R.getExit(), false);
912 ExitStr.str();
913 } else
914 ExitName = "FunctionExit";
915
916 return EntryName + "---" + ExitName;
917}
918
919void Scop::printContext(raw_ostream &OS) const {
920 OS << "Context:\n";
921
922 if (!Context) {
923 OS.indent(4) << "n/a\n\n";
924 return;
925 }
926
927 OS.indent(4) << getContextStr() << "\n";
928}
929
930void Scop::printStatements(raw_ostream &OS) const {
931 OS << "Statements {\n";
932
933 for (const_iterator SI = begin(), SE = end();SI != SE; ++SI)
934 OS.indent(4) << (**SI);
935
936 OS.indent(4) << "}\n";
937}
938
939
940void Scop::print(raw_ostream &OS) const {
941 printContext(OS.indent(4));
942 printStatements(OS.indent(4));
943}
944
945void Scop::dump() const { print(dbgs()); }
946
947isl_ctx *Scop::getCtx() const { return isl_set_get_ctx(Context); }
948
949ScalarEvolution *Scop::getSE() const { return SE; }
950
951bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
952 if (tempScop.getAccessFunctions(BB))
953 return false;
954
955 return true;
956}
957
958void Scop::buildScop(TempScop &tempScop,
959 const Region &CurRegion,
960 SmallVectorImpl<Loop*> &NestLoops,
961 SmallVectorImpl<unsigned> &Scatter,
962 LoopInfo &LI) {
963 Loop *L = castToLoop(CurRegion, LI);
964
965 if (L)
966 NestLoops.push_back(L);
967
968 unsigned loopDepth = NestLoops.size();
969 assert(Scatter.size() > loopDepth && "Scatter not big enough!");
970
971 for (Region::const_element_iterator I = CurRegion.element_begin(),
972 E = CurRegion.element_end(); I != E; ++I)
973 if (I->isSubRegion())
974 buildScop(tempScop, *(I->getNodeAs<Region>()), NestLoops, Scatter, LI);
975 else {
976 BasicBlock *BB = I->getNodeAs<BasicBlock>();
977
978 if (isTrivialBB(BB, tempScop))
979 continue;
980
981 Stmts.push_back(new ScopStmt(*this, tempScop, CurRegion, *BB, NestLoops,
982 Scatter));
983
984 // Increasing the Scattering function is OK for the moment, because
985 // we are using a depth first iterator and the program is well structured.
986 ++Scatter[loopDepth];
987 }
988
989 if (!L)
990 return;
991
992 // Exiting a loop region.
993 Scatter[loopDepth] = 0;
994 NestLoops.pop_back();
995 ++Scatter[loopDepth-1];
996}
997
998//===----------------------------------------------------------------------===//
999
1000void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1001 AU.addRequired<LoopInfo>();
1002 AU.addRequired<RegionInfo>();
1003 AU.addRequired<ScalarEvolution>();
1004 AU.addRequired<TempScopInfo>();
1005 AU.setPreservesAll();
1006}
1007
1008bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
1009 LoopInfo &LI = getAnalysis<LoopInfo>();
1010 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1011
1012 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop(R);
1013
1014 // This region is no Scop.
1015 if (!tempScop) {
1016 scop = 0;
1017 return false;
1018 }
1019
1020 // Statistics.
1021 ++ScopFound;
1022 if (tempScop->getMaxLoopDepth() > 0) ++RichScopFound;
1023
1024 scop = new Scop(*tempScop, LI, SE);
1025
1026 return false;
1027}
1028
1029char ScopInfo::ID = 0;
1030
1031
1032static RegisterPass<ScopInfo>
1033X("polly-scops", "Polly - Create polyhedral description of Scops");
1034
1035Pass *polly::createScopInfoPass() {
1036 return new ScopInfo();
1037}