pass value_bounds to PetScan
[pet.git] / scan.cc
blobd35380a194ed58b3e667e90f6b9010921e07bfc7
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following
13 * disclaimer in the documentation and/or other materials provided
14 * with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
20 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
23 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 * The views and conclusions contained in the software and documentation
29 * are those of the authors and should not be interpreted as
30 * representing official policies, either expressed or implied, of
31 * Leiden University.
32 */
34 #include <set>
35 #include <map>
36 #include <iostream>
37 #include <clang/AST/ASTDiagnostic.h>
38 #include <clang/AST/Expr.h>
39 #include <clang/AST/RecursiveASTVisitor.h>
41 #include <isl/id.h>
42 #include <isl/space.h>
43 #include <isl/aff.h>
44 #include <isl/set.h>
46 #include "scan.h"
47 #include "scop.h"
48 #include "scop_plus.h"
50 #include "config.h"
52 using namespace std;
53 using namespace clang;
55 #ifdef DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION
56 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
58 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
59 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
60 VK_LValue);
62 #else
63 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
65 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
66 var, var->getInnerLocStart(), var->getType(), VK_LValue);
68 #endif
70 /* Check if the element type corresponding to the given array type
71 * has a const qualifier.
73 static bool const_base(QualType qt)
75 const Type *type = qt.getTypePtr();
77 if (type->isPointerType())
78 return const_base(type->getPointeeType());
79 if (type->isArrayType()) {
80 const ArrayType *atype;
81 type = type->getCanonicalTypeInternal().getTypePtr();
82 atype = cast<ArrayType>(type);
83 return const_base(atype->getElementType());
86 return qt.isConstQualified();
89 /* Mark "decl" as having an unknown value in "assigned_value".
91 * If no (known or unknown) value was assigned to "decl" before,
92 * then it may have been treated as a parameter before and may
93 * therefore appear in a value assigned to another variable.
94 * If so, this assignment needs to be turned into an unknown value too.
96 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
97 ValueDecl *decl)
99 map<ValueDecl *, isl_pw_aff *>::iterator it;
101 it = assigned_value.find(decl);
103 assigned_value[decl] = NULL;
105 if (it == assigned_value.end())
106 return;
108 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
109 isl_pw_aff *pa = it->second;
110 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
112 for (int i = 0; i < nparam; ++i) {
113 isl_id *id;
115 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
116 continue;
117 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
118 if (isl_id_get_user(id) == decl)
119 it->second = NULL;
120 isl_id_free(id);
125 /* Look for any assignments to scalar variables in part of the parse
126 * tree and set assigned_value to NULL for each of them.
127 * Also reset assigned_value if the address of a scalar variable
128 * is being taken. As an exception, if the address is passed to a function
129 * that is declared to receive a const pointer, then assigned_value is
130 * not reset.
132 * This ensures that we won't use any previously stored value
133 * in the current subtree and its parents.
135 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
136 map<ValueDecl *, isl_pw_aff *> &assigned_value;
137 set<UnaryOperator *> skip;
139 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
140 assigned_value(assigned_value) {}
142 /* Check for "address of" operators whose value is passed
143 * to a const pointer argument and add them to "skip", so that
144 * we can skip them in VisitUnaryOperator.
146 bool VisitCallExpr(CallExpr *expr) {
147 FunctionDecl *fd;
148 fd = expr->getDirectCallee();
149 if (!fd)
150 return true;
151 for (int i = 0; i < expr->getNumArgs(); ++i) {
152 Expr *arg = expr->getArg(i);
153 UnaryOperator *op;
154 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
155 ImplicitCastExpr *ice;
156 ice = cast<ImplicitCastExpr>(arg);
157 arg = ice->getSubExpr();
159 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
160 continue;
161 op = cast<UnaryOperator>(arg);
162 if (op->getOpcode() != UO_AddrOf)
163 continue;
164 if (const_base(fd->getParamDecl(i)->getType()))
165 skip.insert(op);
167 return true;
170 bool VisitUnaryOperator(UnaryOperator *expr) {
171 Expr *arg;
172 DeclRefExpr *ref;
173 ValueDecl *decl;
175 if (expr->getOpcode() != UO_AddrOf)
176 return true;
177 if (skip.find(expr) != skip.end())
178 return true;
180 arg = expr->getSubExpr();
181 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
182 return true;
183 ref = cast<DeclRefExpr>(arg);
184 decl = ref->getDecl();
185 clear_assignment(assigned_value, decl);
186 return true;
189 bool VisitBinaryOperator(BinaryOperator *expr) {
190 Expr *lhs;
191 DeclRefExpr *ref;
192 ValueDecl *decl;
194 if (!expr->isAssignmentOp())
195 return true;
196 lhs = expr->getLHS();
197 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
198 return true;
199 ref = cast<DeclRefExpr>(lhs);
200 decl = ref->getDecl();
201 clear_assignment(assigned_value, decl);
202 return true;
206 /* Keep a copy of the currently assigned values.
208 * Any variable that is assigned a value inside the current scope
209 * is removed again when we leave the scope (either because it wasn't
210 * stored in the cache or because it has a different value in the cache).
212 struct assigned_value_cache {
213 map<ValueDecl *, isl_pw_aff *> &assigned_value;
214 map<ValueDecl *, isl_pw_aff *> cache;
216 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
217 assigned_value(assigned_value), cache(assigned_value) {}
218 ~assigned_value_cache() {
219 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
220 for (it = assigned_value.begin(); it != assigned_value.end();
221 ++it) {
222 if (!it->second ||
223 (cache.find(it->first) != cache.end() &&
224 cache[it->first] != it->second))
225 cache[it->first] = NULL;
227 assigned_value = cache;
231 /* Insert an expression into the collection of expressions,
232 * provided it is not already in there.
233 * The isl_pw_affs are freed in the destructor.
235 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
237 std::set<isl_pw_aff *>::iterator it;
239 if (expressions.find(expr) == expressions.end())
240 expressions.insert(expr);
241 else
242 isl_pw_aff_free(expr);
245 PetScan::~PetScan()
247 std::set<isl_pw_aff *>::iterator it;
249 for (it = expressions.begin(); it != expressions.end(); ++it)
250 isl_pw_aff_free(*it);
252 isl_union_map_free(value_bounds);
255 /* Called if we found something we (currently) cannot handle.
256 * We'll provide more informative warnings later.
258 * We only actually complain if autodetect is false.
260 void PetScan::unsupported(Stmt *stmt, const char *msg)
262 if (autodetect)
263 return;
265 SourceLocation loc = stmt->getLocStart();
266 DiagnosticsEngine &diag = PP.getDiagnostics();
267 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
268 msg ? msg : "unsupported");
269 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
272 /* Extract an integer from "expr" and store it in "v".
274 int PetScan::extract_int(IntegerLiteral *expr, isl_int *v)
276 const Type *type = expr->getType().getTypePtr();
277 int is_signed = type->hasSignedIntegerRepresentation();
279 if (is_signed) {
280 int64_t i = expr->getValue().getSExtValue();
281 isl_int_set_si(*v, i);
282 } else {
283 uint64_t i = expr->getValue().getZExtValue();
284 isl_int_set_ui(*v, i);
287 return 0;
290 /* Extract an integer from "expr" and store it in "v".
291 * Return -1 if "expr" does not (obviously) represent an integer.
293 int PetScan::extract_int(clang::ParenExpr *expr, isl_int *v)
295 return extract_int(expr->getSubExpr(), v);
298 /* Extract an integer from "expr" and store it in "v".
299 * Return -1 if "expr" does not (obviously) represent an integer.
301 int PetScan::extract_int(clang::Expr *expr, isl_int *v)
303 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
304 return extract_int(cast<IntegerLiteral>(expr), v);
305 if (expr->getStmtClass() == Stmt::ParenExprClass)
306 return extract_int(cast<ParenExpr>(expr), v);
308 unsupported(expr);
309 return -1;
312 /* Extract an affine expression from the IntegerLiteral "expr".
314 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
316 isl_space *dim = isl_space_params_alloc(ctx, 0);
317 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
318 isl_aff *aff = isl_aff_zero_on_domain(ls);
319 isl_set *dom = isl_set_universe(dim);
320 isl_int v;
322 isl_int_init(v);
323 extract_int(expr, &v);
324 aff = isl_aff_add_constant(aff, v);
325 isl_int_clear(v);
327 return isl_pw_aff_alloc(dom, aff);
330 /* Extract an affine expression from the APInt "val".
332 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
334 isl_space *dim = isl_space_params_alloc(ctx, 0);
335 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
336 isl_aff *aff = isl_aff_zero_on_domain(ls);
337 isl_set *dom = isl_set_universe(dim);
338 isl_int v;
340 isl_int_init(v);
341 isl_int_set_ui(v, val.getZExtValue());
342 aff = isl_aff_add_constant(aff, v);
343 isl_int_clear(v);
345 return isl_pw_aff_alloc(dom, aff);
348 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
350 return extract_affine(expr->getSubExpr());
353 /* Extract an affine expression from the DeclRefExpr "expr".
355 * If the variable has been assigned a value, then we check whether
356 * we know what (affine) value was assigned.
357 * If so, we return this value. Otherwise we convert "expr"
358 * to an extra parameter (provided nesting_enabled is set).
360 * Otherwise, we simply return an expression that is equal
361 * to a parameter corresponding to the referenced variable.
363 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
365 ValueDecl *decl = expr->getDecl();
366 const Type *type = decl->getType().getTypePtr();
367 isl_id *id;
368 isl_space *dim;
369 isl_aff *aff;
370 isl_set *dom;
372 if (!type->isIntegerType()) {
373 unsupported(expr);
374 return NULL;
377 if (assigned_value.find(decl) != assigned_value.end()) {
378 if (assigned_value[decl])
379 return isl_pw_aff_copy(assigned_value[decl]);
380 else
381 return nested_access(expr);
384 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
385 dim = isl_space_params_alloc(ctx, 1);
387 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
389 dom = isl_set_universe(isl_space_copy(dim));
390 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
391 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
393 return isl_pw_aff_alloc(dom, aff);
396 /* Extract an affine expression from an integer division operation.
397 * In particular, if "expr" is lhs/rhs, then return
399 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
401 * The second argument (rhs) is required to be a (positive) integer constant.
403 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
405 Expr *rhs_expr;
406 isl_pw_aff *lhs, *lhs_f, *lhs_c;
407 isl_pw_aff *res;
408 isl_int v;
409 isl_set *cond;
411 rhs_expr = expr->getRHS();
412 isl_int_init(v);
413 if (extract_int(rhs_expr, &v) < 0) {
414 isl_int_clear(v);
415 return NULL;
418 lhs = extract_affine(expr->getLHS());
419 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
421 lhs = isl_pw_aff_scale_down(lhs, v);
422 isl_int_clear(v);
424 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(lhs));
425 lhs_c = isl_pw_aff_ceil(lhs);
426 res = isl_pw_aff_cond(cond, lhs_f, lhs_c);
428 return res;
431 /* Extract an affine expression from a modulo operation.
432 * In particular, if "expr" is lhs/rhs, then return
434 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
436 * The second argument (rhs) is required to be a (positive) integer constant.
438 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
440 Expr *rhs_expr;
441 isl_pw_aff *lhs, *lhs_f, *lhs_c;
442 isl_pw_aff *res;
443 isl_int v;
444 isl_set *cond;
446 rhs_expr = expr->getRHS();
447 if (rhs_expr->getStmtClass() != Stmt::IntegerLiteralClass) {
448 unsupported(expr);
449 return NULL;
452 lhs = extract_affine(expr->getLHS());
453 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
455 isl_int_init(v);
456 extract_int(cast<IntegerLiteral>(rhs_expr), &v);
457 res = isl_pw_aff_scale_down(isl_pw_aff_copy(lhs), v);
459 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(res));
460 lhs_c = isl_pw_aff_ceil(res);
461 res = isl_pw_aff_cond(cond, lhs_f, lhs_c);
463 res = isl_pw_aff_scale(res, v);
464 isl_int_clear(v);
466 res = isl_pw_aff_sub(lhs, res);
468 return res;
471 /* Extract an affine expression from a multiplication operation.
472 * This is only allowed if at least one of the two arguments
473 * is a (piecewise) constant.
475 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
477 isl_pw_aff *lhs;
478 isl_pw_aff *rhs;
480 lhs = extract_affine(expr->getLHS());
481 rhs = extract_affine(expr->getRHS());
483 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
484 isl_pw_aff_free(lhs);
485 isl_pw_aff_free(rhs);
486 unsupported(expr);
487 return NULL;
490 return isl_pw_aff_mul(lhs, rhs);
493 /* Extract an affine expression from an addition or subtraction operation.
495 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
497 isl_pw_aff *lhs;
498 isl_pw_aff *rhs;
500 lhs = extract_affine(expr->getLHS());
501 rhs = extract_affine(expr->getRHS());
503 switch (expr->getOpcode()) {
504 case BO_Add:
505 return isl_pw_aff_add(lhs, rhs);
506 case BO_Sub:
507 return isl_pw_aff_sub(lhs, rhs);
508 default:
509 isl_pw_aff_free(lhs);
510 isl_pw_aff_free(rhs);
511 return NULL;
516 /* Compute
518 * pwaff mod 2^width
520 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
521 unsigned width)
523 isl_int mod;
525 isl_int_init(mod);
526 isl_int_set_si(mod, 1);
527 isl_int_mul_2exp(mod, mod, width);
529 pwaff = isl_pw_aff_mod(pwaff, mod);
531 isl_int_clear(mod);
533 return pwaff;
536 /* Extract an affine expression from a boolean expression.
537 * In particular, return the expression "expr ? 1 : 0".
539 __isl_give isl_pw_aff *PetScan::extract_implicit_affine(Expr *expr)
541 isl_set *cond = extract_condition(expr);
542 isl_space *space = isl_set_get_space(cond);
543 isl_local_space *ls = isl_local_space_from_space(space);
544 isl_aff *zero = isl_aff_zero_on_domain(isl_local_space_copy(ls));
545 isl_aff *one = isl_aff_zero_on_domain(ls);
546 one = isl_aff_add_constant_si(one, 1);
547 return isl_pw_aff_cond(cond, isl_pw_aff_from_aff(one),
548 isl_pw_aff_from_aff(zero));
551 /* Extract an affine expression from some binary operations.
552 * If the result of the expression is unsigned, then we wrap it
553 * based on the size of the type.
555 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
557 isl_pw_aff *res;
559 switch (expr->getOpcode()) {
560 case BO_Add:
561 case BO_Sub:
562 res = extract_affine_add(expr);
563 break;
564 case BO_Div:
565 res = extract_affine_div(expr);
566 break;
567 case BO_Rem:
568 res = extract_affine_mod(expr);
569 break;
570 case BO_Mul:
571 res = extract_affine_mul(expr);
572 break;
573 case BO_LT:
574 case BO_LE:
575 case BO_GT:
576 case BO_GE:
577 case BO_EQ:
578 case BO_NE:
579 case BO_LAnd:
580 case BO_LOr:
581 res = extract_implicit_affine(expr);
582 break;
583 default:
584 unsupported(expr);
585 return NULL;
588 if (expr->getType()->isUnsignedIntegerType())
589 res = wrap(res, ast_context.getIntWidth(expr->getType()));
591 return res;
594 /* Extract an affine expression from a negation operation.
596 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
598 if (expr->getOpcode() == UO_Minus)
599 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
600 if (expr->getOpcode() == UO_LNot)
601 return extract_implicit_affine(expr);
603 unsupported(expr);
604 return NULL;
607 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
609 return extract_affine(expr->getSubExpr());
612 /* Extract an affine expression from some special function calls.
613 * In particular, we handle "min", "max", "ceild" and "floord".
614 * In case of the latter two, the second argument needs to be
615 * a (positive) integer constant.
617 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
619 FunctionDecl *fd;
620 string name;
621 isl_pw_aff *aff1, *aff2;
623 fd = expr->getDirectCallee();
624 if (!fd) {
625 unsupported(expr);
626 return NULL;
629 name = fd->getDeclName().getAsString();
630 if (!(expr->getNumArgs() == 2 && name == "min") &&
631 !(expr->getNumArgs() == 2 && name == "max") &&
632 !(expr->getNumArgs() == 2 && name == "floord") &&
633 !(expr->getNumArgs() == 2 && name == "ceild")) {
634 unsupported(expr);
635 return NULL;
638 if (name == "min" || name == "max") {
639 aff1 = extract_affine(expr->getArg(0));
640 aff2 = extract_affine(expr->getArg(1));
642 if (name == "min")
643 aff1 = isl_pw_aff_min(aff1, aff2);
644 else
645 aff1 = isl_pw_aff_max(aff1, aff2);
646 } else if (name == "floord" || name == "ceild") {
647 isl_int v;
648 Expr *arg2 = expr->getArg(1);
650 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
651 unsupported(expr);
652 return NULL;
654 aff1 = extract_affine(expr->getArg(0));
655 isl_int_init(v);
656 extract_int(cast<IntegerLiteral>(arg2), &v);
657 aff1 = isl_pw_aff_scale_down(aff1, v);
658 isl_int_clear(v);
659 if (name == "floord")
660 aff1 = isl_pw_aff_floor(aff1);
661 else
662 aff1 = isl_pw_aff_ceil(aff1);
663 } else {
664 unsupported(expr);
665 return NULL;
668 return aff1;
672 /* This method is called when we come across an access that is
673 * nested in what is supposed to be an affine expression.
674 * If nesting is allowed, we return a new parameter that corresponds
675 * to this nested access. Otherwise, we simply complain.
677 * The new parameter is resolved in resolve_nested.
679 isl_pw_aff *PetScan::nested_access(Expr *expr)
681 isl_id *id;
682 isl_space *dim;
683 isl_aff *aff;
684 isl_set *dom;
686 if (!nesting_enabled) {
687 unsupported(expr);
688 return NULL;
691 id = isl_id_alloc(ctx, NULL, expr);
692 dim = isl_space_params_alloc(ctx, 1);
694 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
696 dom = isl_set_universe(isl_space_copy(dim));
697 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
698 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
700 return isl_pw_aff_alloc(dom, aff);
703 /* Affine expressions are not supposed to contain array accesses,
704 * but if nesting is allowed, we return a parameter corresponding
705 * to the array access.
707 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
709 return nested_access(expr);
712 /* Extract an affine expression from a conditional operation.
714 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
716 isl_set *cond;
717 isl_pw_aff *lhs, *rhs;
719 cond = extract_condition(expr->getCond());
720 lhs = extract_affine(expr->getTrueExpr());
721 rhs = extract_affine(expr->getFalseExpr());
723 return isl_pw_aff_cond(cond, lhs, rhs);
726 /* Extract an affine expression, if possible, from "expr".
727 * Otherwise return NULL.
729 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
731 switch (expr->getStmtClass()) {
732 case Stmt::ImplicitCastExprClass:
733 return extract_affine(cast<ImplicitCastExpr>(expr));
734 case Stmt::IntegerLiteralClass:
735 return extract_affine(cast<IntegerLiteral>(expr));
736 case Stmt::DeclRefExprClass:
737 return extract_affine(cast<DeclRefExpr>(expr));
738 case Stmt::BinaryOperatorClass:
739 return extract_affine(cast<BinaryOperator>(expr));
740 case Stmt::UnaryOperatorClass:
741 return extract_affine(cast<UnaryOperator>(expr));
742 case Stmt::ParenExprClass:
743 return extract_affine(cast<ParenExpr>(expr));
744 case Stmt::CallExprClass:
745 return extract_affine(cast<CallExpr>(expr));
746 case Stmt::ArraySubscriptExprClass:
747 return extract_affine(cast<ArraySubscriptExpr>(expr));
748 case Stmt::ConditionalOperatorClass:
749 return extract_affine(cast<ConditionalOperator>(expr));
750 default:
751 unsupported(expr);
753 return NULL;
756 __isl_give isl_map *PetScan::extract_access(ImplicitCastExpr *expr)
758 return extract_access(expr->getSubExpr());
761 /* Return the depth of an array of the given type.
763 static int array_depth(const Type *type)
765 if (type->isPointerType())
766 return 1 + array_depth(type->getPointeeType().getTypePtr());
767 if (type->isArrayType()) {
768 const ArrayType *atype;
769 type = type->getCanonicalTypeInternal().getTypePtr();
770 atype = cast<ArrayType>(type);
771 return 1 + array_depth(atype->getElementType().getTypePtr());
773 return 0;
776 /* Return the element type of the given array type.
778 static QualType base_type(QualType qt)
780 const Type *type = qt.getTypePtr();
782 if (type->isPointerType())
783 return base_type(type->getPointeeType());
784 if (type->isArrayType()) {
785 const ArrayType *atype;
786 type = type->getCanonicalTypeInternal().getTypePtr();
787 atype = cast<ArrayType>(type);
788 return base_type(atype->getElementType());
790 return qt;
793 /* Extract an access relation from a reference to a variable.
794 * If the variable has name "A" and its type corresponds to an
795 * array of depth d, then the returned access relation is of the
796 * form
798 * { [] -> A[i_1,...,i_d] }
800 __isl_give isl_map *PetScan::extract_access(DeclRefExpr *expr)
802 ValueDecl *decl = expr->getDecl();
803 int depth = array_depth(decl->getType().getTypePtr());
804 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
805 isl_space *dim = isl_space_alloc(ctx, 0, 0, depth);
806 isl_map *access_rel;
808 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
810 access_rel = isl_map_universe(dim);
812 return access_rel;
815 /* Extract an access relation from an integer contant.
816 * If the value of the constant is "v", then the returned access relation
817 * is
819 * { [] -> [v] }
821 __isl_give isl_map *PetScan::extract_access(IntegerLiteral *expr)
823 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr)));
826 /* Try and extract an access relation from the given Expr.
827 * Return NULL if it doesn't work out.
829 __isl_give isl_map *PetScan::extract_access(Expr *expr)
831 switch (expr->getStmtClass()) {
832 case Stmt::ImplicitCastExprClass:
833 return extract_access(cast<ImplicitCastExpr>(expr));
834 case Stmt::DeclRefExprClass:
835 return extract_access(cast<DeclRefExpr>(expr));
836 case Stmt::ArraySubscriptExprClass:
837 return extract_access(cast<ArraySubscriptExpr>(expr));
838 default:
839 unsupported(expr);
841 return NULL;
844 /* Assign the affine expression "index" to the output dimension "pos" of "map"
845 * and return the result.
847 __isl_give isl_map *set_index(__isl_take isl_map *map, int pos,
848 __isl_take isl_pw_aff *index)
850 isl_map *index_map;
851 int len = isl_map_dim(map, isl_dim_out);
852 isl_id *id;
854 index_map = isl_map_from_range(isl_set_from_pw_aff(index));
855 index_map = isl_map_insert_dims(index_map, isl_dim_out, 0, pos);
856 index_map = isl_map_add_dims(index_map, isl_dim_out, len - pos - 1);
857 id = isl_map_get_tuple_id(map, isl_dim_out);
858 index_map = isl_map_set_tuple_id(index_map, isl_dim_out, id);
860 map = isl_map_intersect(map, index_map);
862 return map;
865 /* Extract an access relation from the given array subscript expression.
866 * If nesting is allowed in general, then we turn it on while
867 * examining the index expression.
869 * We first extract an access relation from the base.
870 * This will result in an access relation with a range that corresponds
871 * to the array being accessed and with earlier indices filled in already.
872 * We then extract the current index and fill that in as well.
873 * The position of the current index is based on the type of base.
874 * If base is the actual array variable, then the depth of this type
875 * will be the same as the depth of the array and we will fill in
876 * the first array index.
877 * Otherwise, the depth of the base type will be smaller and we will fill
878 * in a later index.
880 __isl_give isl_map *PetScan::extract_access(ArraySubscriptExpr *expr)
882 Expr *base = expr->getBase();
883 Expr *idx = expr->getIdx();
884 isl_pw_aff *index;
885 isl_map *base_access;
886 isl_map *access;
887 int depth = array_depth(base->getType().getTypePtr());
888 int pos;
889 bool save_nesting = nesting_enabled;
891 nesting_enabled = allow_nested;
893 base_access = extract_access(base);
894 index = extract_affine(idx);
896 nesting_enabled = save_nesting;
898 pos = isl_map_dim(base_access, isl_dim_out) - depth;
899 access = set_index(base_access, pos, index);
901 return access;
904 /* Check if "expr" calls function "minmax" with two arguments and if so
905 * make lhs and rhs refer to these two arguments.
907 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
909 CallExpr *call;
910 FunctionDecl *fd;
911 string name;
913 if (expr->getStmtClass() != Stmt::CallExprClass)
914 return false;
916 call = cast<CallExpr>(expr);
917 fd = call->getDirectCallee();
918 if (!fd)
919 return false;
921 if (call->getNumArgs() != 2)
922 return false;
924 name = fd->getDeclName().getAsString();
925 if (name != minmax)
926 return false;
928 lhs = call->getArg(0);
929 rhs = call->getArg(1);
931 return true;
934 /* Check if "expr" is of the form min(lhs, rhs) and if so make
935 * lhs and rhs refer to the two arguments.
937 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
939 return is_minmax(expr, "min", lhs, rhs);
942 /* Check if "expr" is of the form max(lhs, rhs) and if so make
943 * lhs and rhs refer to the two arguments.
945 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
947 return is_minmax(expr, "max", lhs, rhs);
950 /* Extract a set of values satisfying the comparison "LHS op RHS"
951 * "comp" is the original statement that "LHS op RHS" is derived from
952 * and is used for diagnostics.
954 * If the comparison is of the form
956 * a <= min(b,c)
958 * then the set is constructed as the intersection of the set corresponding
959 * to the comparisons
961 * a <= b and a <= c
963 * A similar optimization is performed for max(a,b) <= c.
964 * We do this because that will lead to simpler representations of the set.
965 * If isl is ever enhanced to explicitly deal with min and max expressions,
966 * this optimization can be removed.
968 __isl_give isl_set *PetScan::extract_comparison(BinaryOperatorKind op,
969 Expr *LHS, Expr *RHS, Stmt *comp)
971 isl_pw_aff *lhs;
972 isl_pw_aff *rhs;
973 isl_set *cond;
975 if (op == BO_GT)
976 return extract_comparison(BO_LT, RHS, LHS, comp);
977 if (op == BO_GE)
978 return extract_comparison(BO_LE, RHS, LHS, comp);
980 if (op == BO_LT || op == BO_LE) {
981 Expr *expr1, *expr2;
982 isl_set *set1, *set2;
983 if (is_min(RHS, expr1, expr2)) {
984 set1 = extract_comparison(op, LHS, expr1, comp);
985 set2 = extract_comparison(op, LHS, expr2, comp);
986 return isl_set_intersect(set1, set2);
988 if (is_max(LHS, expr1, expr2)) {
989 set1 = extract_comparison(op, expr1, RHS, comp);
990 set2 = extract_comparison(op, expr2, RHS, comp);
991 return isl_set_intersect(set1, set2);
995 lhs = extract_affine(LHS);
996 rhs = extract_affine(RHS);
998 switch (op) {
999 case BO_LT:
1000 cond = isl_pw_aff_lt_set(lhs, rhs);
1001 break;
1002 case BO_LE:
1003 cond = isl_pw_aff_le_set(lhs, rhs);
1004 break;
1005 case BO_EQ:
1006 cond = isl_pw_aff_eq_set(lhs, rhs);
1007 break;
1008 case BO_NE:
1009 cond = isl_pw_aff_ne_set(lhs, rhs);
1010 break;
1011 default:
1012 isl_pw_aff_free(lhs);
1013 isl_pw_aff_free(rhs);
1014 unsupported(comp);
1015 return NULL;
1018 cond = isl_set_coalesce(cond);
1020 return cond;
1023 __isl_give isl_set *PetScan::extract_comparison(BinaryOperator *comp)
1025 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1026 comp->getRHS(), comp);
1029 /* Extract a set of values satisfying the negation (logical not)
1030 * of a subexpression.
1032 __isl_give isl_set *PetScan::extract_boolean(UnaryOperator *op)
1034 isl_set *cond;
1036 cond = extract_condition(op->getSubExpr());
1038 return isl_set_complement(cond);
1041 /* Extract a set of values satisfying the union (logical or)
1042 * or intersection (logical and) of two subexpressions.
1044 __isl_give isl_set *PetScan::extract_boolean(BinaryOperator *comp)
1046 isl_set *lhs;
1047 isl_set *rhs;
1048 isl_set *cond;
1050 lhs = extract_condition(comp->getLHS());
1051 rhs = extract_condition(comp->getRHS());
1053 switch (comp->getOpcode()) {
1054 case BO_LAnd:
1055 cond = isl_set_intersect(lhs, rhs);
1056 break;
1057 case BO_LOr:
1058 cond = isl_set_union(lhs, rhs);
1059 break;
1060 default:
1061 isl_set_free(lhs);
1062 isl_set_free(rhs);
1063 unsupported(comp);
1064 return NULL;
1067 return cond;
1070 __isl_give isl_set *PetScan::extract_condition(UnaryOperator *expr)
1072 switch (expr->getOpcode()) {
1073 case UO_LNot:
1074 return extract_boolean(expr);
1075 default:
1076 unsupported(expr);
1077 return NULL;
1081 /* Extract a set of values satisfying the condition "expr != 0".
1083 __isl_give isl_set *PetScan::extract_implicit_condition(Expr *expr)
1085 return isl_pw_aff_non_zero_set(extract_affine(expr));
1088 /* Extract a set of values satisfying the condition expressed by "expr".
1090 * If the expression doesn't look like a condition, we assume it
1091 * is an affine expression and return the condition "expr != 0".
1093 __isl_give isl_set *PetScan::extract_condition(Expr *expr)
1095 BinaryOperator *comp;
1097 if (!expr)
1098 return isl_set_universe(isl_space_params_alloc(ctx, 0));
1100 if (expr->getStmtClass() == Stmt::ParenExprClass)
1101 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1103 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1104 return extract_condition(cast<UnaryOperator>(expr));
1106 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1107 return extract_implicit_condition(expr);
1109 comp = cast<BinaryOperator>(expr);
1110 switch (comp->getOpcode()) {
1111 case BO_LT:
1112 case BO_LE:
1113 case BO_GT:
1114 case BO_GE:
1115 case BO_EQ:
1116 case BO_NE:
1117 return extract_comparison(comp);
1118 case BO_LAnd:
1119 case BO_LOr:
1120 return extract_boolean(comp);
1121 default:
1122 return extract_implicit_condition(expr);
1126 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1128 switch (kind) {
1129 case UO_Minus:
1130 return pet_op_minus;
1131 default:
1132 return pet_op_last;
1136 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1138 switch (kind) {
1139 case BO_AddAssign:
1140 return pet_op_add_assign;
1141 case BO_SubAssign:
1142 return pet_op_sub_assign;
1143 case BO_MulAssign:
1144 return pet_op_mul_assign;
1145 case BO_DivAssign:
1146 return pet_op_div_assign;
1147 case BO_Assign:
1148 return pet_op_assign;
1149 case BO_Add:
1150 return pet_op_add;
1151 case BO_Sub:
1152 return pet_op_sub;
1153 case BO_Mul:
1154 return pet_op_mul;
1155 case BO_Div:
1156 return pet_op_div;
1157 case BO_EQ:
1158 return pet_op_eq;
1159 case BO_LE:
1160 return pet_op_le;
1161 case BO_LT:
1162 return pet_op_lt;
1163 case BO_GT:
1164 return pet_op_gt;
1165 default:
1166 return pet_op_last;
1170 /* Construct a pet_expr representing a unary operator expression.
1172 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1174 struct pet_expr *arg;
1175 enum pet_op_type op;
1177 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1178 if (op == pet_op_last) {
1179 unsupported(expr);
1180 return NULL;
1183 arg = extract_expr(expr->getSubExpr());
1185 return pet_expr_new_unary(ctx, op, arg);
1188 /* Mark the given access pet_expr as a write.
1189 * If a scalar is being accessed, then mark its value
1190 * as unknown in assigned_value.
1192 void PetScan::mark_write(struct pet_expr *access)
1194 isl_id *id;
1195 ValueDecl *decl;
1197 access->acc.write = 1;
1198 access->acc.read = 0;
1200 if (isl_map_dim(access->acc.access, isl_dim_out) != 0)
1201 return;
1203 id = isl_map_get_tuple_id(access->acc.access, isl_dim_out);
1204 decl = (ValueDecl *) isl_id_get_user(id);
1205 clear_assignment(assigned_value, decl);
1206 isl_id_free(id);
1209 /* Construct a pet_expr representing a binary operator expression.
1211 * If the top level operator is an assignment and the LHS is an access,
1212 * then we mark that access as a write. If the operator is a compound
1213 * assignment, the access is marked as both a read and a write.
1215 * If "expr" assigns something to a scalar variable, then we mark
1216 * the variable as having been assigned. If, furthermore, the expression
1217 * is affine, then keep track of this value in assigned_value
1218 * so that we can plug it in when we later come across the same variable.
1220 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1222 struct pet_expr *lhs, *rhs;
1223 enum pet_op_type op;
1225 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1226 if (op == pet_op_last) {
1227 unsupported(expr);
1228 return NULL;
1231 lhs = extract_expr(expr->getLHS());
1232 rhs = extract_expr(expr->getRHS());
1234 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1235 mark_write(lhs);
1236 if (expr->isCompoundAssignmentOp())
1237 lhs->acc.read = 1;
1240 if (expr->getOpcode() == BO_Assign &&
1241 lhs && lhs->type == pet_expr_access &&
1242 isl_map_dim(lhs->acc.access, isl_dim_out) == 0) {
1243 isl_id *id = isl_map_get_tuple_id(lhs->acc.access, isl_dim_out);
1244 ValueDecl *decl = (ValueDecl *) isl_id_get_user(id);
1245 Expr *rhs = expr->getRHS();
1246 isl_pw_aff *pa = try_extract_affine(rhs);
1247 clear_assignment(assigned_value, decl);
1248 if (pa) {
1249 assigned_value[decl] = pa;
1250 insert_expression(pa);
1252 isl_id_free(id);
1255 return pet_expr_new_binary(ctx, op, lhs, rhs);
1258 /* Construct a pet_expr representing a conditional operation.
1260 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1262 struct pet_expr *cond, *lhs, *rhs;
1264 cond = extract_expr(expr->getCond());
1265 lhs = extract_expr(expr->getTrueExpr());
1266 rhs = extract_expr(expr->getFalseExpr());
1268 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1271 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1273 return extract_expr(expr->getSubExpr());
1276 /* Construct a pet_expr representing a floating point value.
1278 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1280 return pet_expr_new_double(ctx, expr->getValueAsApproximateDouble());
1283 /* Extract an access relation from "expr" and then convert it into
1284 * a pet_expr.
1286 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1288 isl_map *access;
1289 struct pet_expr *pe;
1291 switch (expr->getStmtClass()) {
1292 case Stmt::ArraySubscriptExprClass:
1293 access = extract_access(cast<ArraySubscriptExpr>(expr));
1294 break;
1295 case Stmt::DeclRefExprClass:
1296 access = extract_access(cast<DeclRefExpr>(expr));
1297 break;
1298 case Stmt::IntegerLiteralClass:
1299 access = extract_access(cast<IntegerLiteral>(expr));
1300 break;
1301 default:
1302 unsupported(expr);
1303 return NULL;
1306 pe = pet_expr_from_access(access);
1308 return pe;
1311 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1313 return extract_expr(expr->getSubExpr());
1316 /* Construct a pet_expr representing a function call.
1318 * If we are passing along a pointer to an array element
1319 * or an entire row or even higher dimensional slice of an array,
1320 * then the function being called may write into the array.
1322 * We assume here that if the function is declared to take a pointer
1323 * to a const type, then the function will perform a read
1324 * and that otherwise, it will perform a write.
1326 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1328 struct pet_expr *res = NULL;
1329 FunctionDecl *fd;
1330 string name;
1332 fd = expr->getDirectCallee();
1333 if (!fd) {
1334 unsupported(expr);
1335 return NULL;
1338 name = fd->getDeclName().getAsString();
1339 res = pet_expr_new_call(ctx, name.c_str(), expr->getNumArgs());
1340 if (!res)
1341 return NULL;
1343 for (int i = 0; i < expr->getNumArgs(); ++i) {
1344 Expr *arg = expr->getArg(i);
1345 int is_addr = 0;
1346 pet_expr *main_arg;
1348 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
1349 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(arg);
1350 arg = ice->getSubExpr();
1352 if (arg->getStmtClass() == Stmt::UnaryOperatorClass) {
1353 UnaryOperator *op = cast<UnaryOperator>(arg);
1354 if (op->getOpcode() == UO_AddrOf) {
1355 is_addr = 1;
1356 arg = op->getSubExpr();
1359 res->args[i] = PetScan::extract_expr(arg);
1360 main_arg = res->args[i];
1361 if (is_addr)
1362 res->args[i] = pet_expr_new_unary(ctx,
1363 pet_op_address_of, res->args[i]);
1364 if (!res->args[i])
1365 goto error;
1366 if (arg->getStmtClass() == Stmt::ArraySubscriptExprClass &&
1367 array_depth(arg->getType().getTypePtr()) > 0)
1368 is_addr = 1;
1369 if (is_addr && main_arg->type == pet_expr_access) {
1370 ParmVarDecl *parm;
1371 if (!fd->hasPrototype()) {
1372 unsupported(expr, "prototype required");
1373 goto error;
1375 parm = fd->getParamDecl(i);
1376 if (!const_base(parm->getType()))
1377 mark_write(main_arg);
1381 return res;
1382 error:
1383 pet_expr_free(res);
1384 return NULL;
1387 /* Try and onstruct a pet_expr representing "expr".
1389 struct pet_expr *PetScan::extract_expr(Expr *expr)
1391 switch (expr->getStmtClass()) {
1392 case Stmt::UnaryOperatorClass:
1393 return extract_expr(cast<UnaryOperator>(expr));
1394 case Stmt::CompoundAssignOperatorClass:
1395 case Stmt::BinaryOperatorClass:
1396 return extract_expr(cast<BinaryOperator>(expr));
1397 case Stmt::ImplicitCastExprClass:
1398 return extract_expr(cast<ImplicitCastExpr>(expr));
1399 case Stmt::ArraySubscriptExprClass:
1400 case Stmt::DeclRefExprClass:
1401 case Stmt::IntegerLiteralClass:
1402 return extract_access_expr(expr);
1403 case Stmt::FloatingLiteralClass:
1404 return extract_expr(cast<FloatingLiteral>(expr));
1405 case Stmt::ParenExprClass:
1406 return extract_expr(cast<ParenExpr>(expr));
1407 case Stmt::ConditionalOperatorClass:
1408 return extract_expr(cast<ConditionalOperator>(expr));
1409 case Stmt::CallExprClass:
1410 return extract_expr(cast<CallExpr>(expr));
1411 default:
1412 unsupported(expr);
1414 return NULL;
1417 /* Check if the given initialization statement is an assignment.
1418 * If so, return that assignment. Otherwise return NULL.
1420 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1422 BinaryOperator *ass;
1424 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1425 return NULL;
1427 ass = cast<BinaryOperator>(init);
1428 if (ass->getOpcode() != BO_Assign)
1429 return NULL;
1431 return ass;
1434 /* Check if the given initialization statement is a declaration
1435 * of a single variable.
1436 * If so, return that declaration. Otherwise return NULL.
1438 Decl *PetScan::initialization_declaration(Stmt *init)
1440 DeclStmt *decl;
1442 if (init->getStmtClass() != Stmt::DeclStmtClass)
1443 return NULL;
1445 decl = cast<DeclStmt>(init);
1447 if (!decl->isSingleDecl())
1448 return NULL;
1450 return decl->getSingleDecl();
1453 /* Given the assignment operator in the initialization of a for loop,
1454 * extract the induction variable, i.e., the (integer)variable being
1455 * assigned.
1457 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1459 Expr *lhs;
1460 DeclRefExpr *ref;
1461 ValueDecl *decl;
1462 const Type *type;
1464 lhs = init->getLHS();
1465 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1466 unsupported(init);
1467 return NULL;
1470 ref = cast<DeclRefExpr>(lhs);
1471 decl = ref->getDecl();
1472 type = decl->getType().getTypePtr();
1474 if (!type->isIntegerType()) {
1475 unsupported(lhs);
1476 return NULL;
1479 return decl;
1482 /* Given the initialization statement of a for loop and the single
1483 * declaration in this initialization statement,
1484 * extract the induction variable, i.e., the (integer) variable being
1485 * declared.
1487 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1489 VarDecl *vd;
1491 vd = cast<VarDecl>(decl);
1493 const QualType type = vd->getType();
1494 if (!type->isIntegerType()) {
1495 unsupported(init);
1496 return NULL;
1499 if (!vd->getInit()) {
1500 unsupported(init);
1501 return NULL;
1504 return vd;
1507 /* Check that op is of the form iv++ or iv--.
1508 * "inc" is accordingly set to 1 or -1.
1510 bool PetScan::check_unary_increment(UnaryOperator *op, clang::ValueDecl *iv,
1511 isl_int &inc)
1513 Expr *sub;
1514 DeclRefExpr *ref;
1516 if (!op->isIncrementDecrementOp()) {
1517 unsupported(op);
1518 return false;
1521 if (op->isIncrementOp())
1522 isl_int_set_si(inc, 1);
1523 else
1524 isl_int_set_si(inc, -1);
1526 sub = op->getSubExpr();
1527 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1528 unsupported(op);
1529 return false;
1532 ref = cast<DeclRefExpr>(sub);
1533 if (ref->getDecl() != iv) {
1534 unsupported(op);
1535 return false;
1538 return true;
1541 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1542 * has a single constant expression on a universe domain, then
1543 * put this constant in *user.
1545 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
1546 void *user)
1548 isl_int *inc = (isl_int *)user;
1549 int res = 0;
1551 if (!isl_set_plain_is_universe(set) || !isl_aff_is_cst(aff))
1552 res = -1;
1553 else
1554 isl_aff_get_constant(aff, inc);
1556 isl_set_free(set);
1557 isl_aff_free(aff);
1559 return res;
1562 /* Check if op is of the form
1564 * iv = iv + inc
1566 * with inc a constant and set "inc" accordingly.
1568 * We extract an affine expression from the RHS and the subtract iv.
1569 * The result should be a constant.
1571 bool PetScan::check_binary_increment(BinaryOperator *op, clang::ValueDecl *iv,
1572 isl_int &inc)
1574 Expr *lhs;
1575 DeclRefExpr *ref;
1576 isl_id *id;
1577 isl_space *dim;
1578 isl_aff *aff;
1579 isl_pw_aff *val;
1581 if (op->getOpcode() != BO_Assign) {
1582 unsupported(op);
1583 return false;
1586 lhs = op->getLHS();
1587 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1588 unsupported(op);
1589 return false;
1592 ref = cast<DeclRefExpr>(lhs);
1593 if (ref->getDecl() != iv) {
1594 unsupported(op);
1595 return false;
1598 val = extract_affine(op->getRHS());
1600 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1602 dim = isl_space_params_alloc(ctx, 1);
1603 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1604 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1605 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1607 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
1609 if (isl_pw_aff_foreach_piece(val, &extract_cst, &inc) < 0) {
1610 isl_pw_aff_free(val);
1611 unsupported(op);
1612 return false;
1615 isl_pw_aff_free(val);
1617 return true;
1620 /* Check that op is of the form iv += cst or iv -= cst.
1621 * "inc" is set to cst or -cst accordingly.
1623 bool PetScan::check_compound_increment(CompoundAssignOperator *op,
1624 clang::ValueDecl *iv, isl_int &inc)
1626 Expr *lhs, *rhs;
1627 DeclRefExpr *ref;
1628 bool neg = false;
1630 BinaryOperatorKind opcode;
1632 opcode = op->getOpcode();
1633 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1634 unsupported(op);
1635 return false;
1637 if (opcode == BO_SubAssign)
1638 neg = true;
1640 lhs = op->getLHS();
1641 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1642 unsupported(op);
1643 return false;
1646 ref = cast<DeclRefExpr>(lhs);
1647 if (ref->getDecl() != iv) {
1648 unsupported(op);
1649 return false;
1652 rhs = op->getRHS();
1654 if (rhs->getStmtClass() == Stmt::UnaryOperatorClass) {
1655 UnaryOperator *op = cast<UnaryOperator>(rhs);
1656 if (op->getOpcode() != UO_Minus) {
1657 unsupported(op);
1658 return false;
1661 neg = !neg;
1663 rhs = op->getSubExpr();
1666 if (rhs->getStmtClass() != Stmt::IntegerLiteralClass) {
1667 unsupported(op);
1668 return false;
1671 extract_int(cast<IntegerLiteral>(rhs), &inc);
1672 if (neg)
1673 isl_int_neg(inc, inc);
1675 return true;
1678 /* Check that the increment of the given for loop increments
1679 * (or decrements) the induction variable "iv".
1680 * "up" is set to true if the induction variable is incremented.
1682 bool PetScan::check_increment(ForStmt *stmt, ValueDecl *iv, isl_int &v)
1684 Stmt *inc = stmt->getInc();
1686 if (!inc) {
1687 unsupported(stmt);
1688 return false;
1691 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1692 return check_unary_increment(cast<UnaryOperator>(inc), iv, v);
1693 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1694 return check_compound_increment(
1695 cast<CompoundAssignOperator>(inc), iv, v);
1696 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1697 return check_binary_increment(cast<BinaryOperator>(inc), iv, v);
1699 unsupported(inc);
1700 return false;
1703 /* Embed the given iteration domain in an extra outer loop
1704 * with induction variable "var".
1705 * If this variable appeared as a parameter in the constraints,
1706 * it is replaced by the new outermost dimension.
1708 static __isl_give isl_set *embed(__isl_take isl_set *set,
1709 __isl_take isl_id *var)
1711 int pos;
1713 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
1714 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
1715 if (pos >= 0) {
1716 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
1717 set = isl_set_project_out(set, isl_dim_param, pos, 1);
1720 isl_id_free(var);
1721 return set;
1724 /* Construct a pet_scop for an infinite loop around the given body.
1726 * We extract a pet_scop for the body and then embed it in a loop with
1727 * iteration domain
1729 * { [t] : t >= 0 }
1731 * and schedule
1733 * { [t] -> [t] }
1735 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
1737 isl_id *id;
1738 isl_space *dim;
1739 isl_set *domain;
1740 isl_map *sched;
1741 struct pet_scop *scop;
1743 scop = extract(body);
1744 if (!scop)
1745 return NULL;
1747 id = isl_id_alloc(ctx, "t", NULL);
1748 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
1749 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
1750 dim = isl_space_from_domain(isl_set_get_space(domain));
1751 dim = isl_space_add_dims(dim, isl_dim_out, 1);
1752 sched = isl_map_universe(dim);
1753 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
1754 scop = pet_scop_embed(scop, domain, sched, id);
1756 return scop;
1759 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1761 * for (;;)
1762 * body
1765 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
1767 return extract_infinite_loop(stmt->getBody());
1770 /* Check if the while loop is of the form
1772 * while (1)
1773 * body
1775 * If so, construct a scop for an infinite loop around body.
1776 * Otherwise, fail.
1778 struct pet_scop *PetScan::extract(WhileStmt *stmt)
1780 Expr *cond;
1781 isl_set *set;
1782 int is_universe;
1784 cond = stmt->getCond();
1785 if (!cond) {
1786 unsupported(stmt);
1787 return NULL;
1790 set = extract_condition(cond);
1791 is_universe = isl_set_plain_is_universe(set);
1792 isl_set_free(set);
1794 if (!is_universe) {
1795 unsupported(stmt);
1796 return NULL;
1799 return extract_infinite_loop(stmt->getBody());
1802 /* Check whether "cond" expresses a simple loop bound
1803 * on the only set dimension.
1804 * In particular, if "up" is set then "cond" should contain only
1805 * upper bounds on the set dimension.
1806 * Otherwise, it should contain only lower bounds.
1808 static bool is_simple_bound(__isl_keep isl_set *cond, isl_int inc)
1810 if (isl_int_is_pos(inc))
1811 return !isl_set_dim_has_lower_bound(cond, isl_dim_set, 0);
1812 else
1813 return !isl_set_dim_has_upper_bound(cond, isl_dim_set, 0);
1816 /* Extend a condition on a given iteration of a loop to one that
1817 * imposes the same condition on all previous iterations.
1818 * "domain" expresses the lower [upper] bound on the iterations
1819 * when inc is positive [negative].
1821 * In particular, we construct the condition (when inc is positive)
1823 * forall i' : (domain(i') and i' <= i) => cond(i')
1825 * which is equivalent to
1827 * not exists i' : domain(i') and i' <= i and not cond(i')
1829 * We construct this set by negating cond, applying a map
1831 * { [i'] -> [i] : domain(i') and i' <= i }
1833 * and then negating the result again.
1835 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
1836 __isl_take isl_set *domain, isl_int inc)
1838 isl_map *previous_to_this;
1840 if (isl_int_is_pos(inc))
1841 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
1842 else
1843 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
1845 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
1847 cond = isl_set_complement(cond);
1848 cond = isl_set_apply(cond, previous_to_this);
1849 cond = isl_set_complement(cond);
1851 return cond;
1854 /* Construct a domain of the form
1856 * [id] -> { [] : exists a: id = init + a * inc and a >= 0 }
1858 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
1859 __isl_take isl_pw_aff *init, isl_int inc)
1861 isl_aff *aff;
1862 isl_space *dim;
1863 isl_set *set;
1865 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
1866 dim = isl_pw_aff_get_domain_space(init);
1867 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1868 aff = isl_aff_add_coefficient(aff, isl_dim_in, 0, inc);
1869 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
1871 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
1872 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1873 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1874 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1876 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
1878 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
1880 return isl_set_project_out(set, isl_dim_set, 0, 1);
1883 static unsigned get_type_size(ValueDecl *decl)
1885 return decl->getASTContext().getIntWidth(decl->getType());
1888 /* Assuming "cond" represents a simple bound on a loop where the loop
1889 * iterator "iv" is incremented (or decremented) by one, check if wrapping
1890 * is possible.
1892 * Under the given assumptions, wrapping is only possible if "cond" allows
1893 * for the last value before wrapping, i.e., 2^width - 1 in case of an
1894 * increasing iterator and 0 in case of a decreasing iterator.
1896 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv, isl_int inc)
1898 bool cw;
1899 isl_int limit;
1900 isl_set *test;
1902 test = isl_set_copy(cond);
1904 isl_int_init(limit);
1905 if (isl_int_is_neg(inc))
1906 isl_int_set_si(limit, 0);
1907 else {
1908 isl_int_set_si(limit, 1);
1909 isl_int_mul_2exp(limit, limit, get_type_size(iv));
1910 isl_int_sub_ui(limit, limit, 1);
1913 test = isl_set_fix(cond, isl_dim_set, 0, limit);
1914 cw = !isl_set_is_empty(test);
1915 isl_set_free(test);
1917 isl_int_clear(limit);
1919 return cw;
1922 /* Given a one-dimensional space, construct the following mapping on this
1923 * space
1925 * { [v] -> [v mod 2^width] }
1927 * where width is the number of bits used to represent the values
1928 * of the unsigned variable "iv".
1930 static __isl_give isl_map *compute_wrapping(__isl_take isl_space *dim,
1931 ValueDecl *iv)
1933 isl_int mod;
1934 isl_aff *aff;
1935 isl_map *map;
1937 isl_int_init(mod);
1938 isl_int_set_si(mod, 1);
1939 isl_int_mul_2exp(mod, mod, get_type_size(iv));
1941 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1942 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1943 aff = isl_aff_mod(aff, mod);
1945 isl_int_clear(mod);
1947 return isl_map_from_basic_map(isl_basic_map_from_aff(aff));
1948 map = isl_map_reverse(map);
1951 /* Construct a pet_scop for a for statement.
1952 * The for loop is required to be of the form
1954 * for (i = init; condition; ++i)
1956 * or
1958 * for (i = init; condition; --i)
1960 * The initialization of the for loop should either be an assignment
1961 * to an integer variable, or a declaration of such a variable with
1962 * initialization.
1964 * The condition is allowed to contain nested accesses, provided
1965 * they are not being written to inside the body of the loop.
1967 * We extract a pet_scop for the body and then embed it in a loop with
1968 * iteration domain and schedule
1970 * { [i] : i >= init and condition' }
1971 * { [i] -> [i] }
1973 * or
1975 * { [i] : i <= init and condition' }
1976 * { [i] -> [-i] }
1978 * Where condition' is equal to condition if the latter is
1979 * a simple upper [lower] bound and a condition that is extended
1980 * to apply to all previous iterations otherwise.
1982 * If the stride of the loop is not 1, then "i >= init" is replaced by
1984 * (exists a: i = init + stride * a and a >= 0)
1986 * If the loop iterator i is unsigned, then wrapping may occur.
1987 * During the computation, we work with a virtual iterator that
1988 * does not wrap. However, the condition in the code applies
1989 * to the wrapped value, so we need to change condition(i)
1990 * into condition([i % 2^width]).
1991 * After computing the virtual domain and schedule, we apply
1992 * the function { [v] -> [v % 2^width] } to the domain and the domain
1993 * of the schedule. In order not to lose any information, we also
1994 * need to intersect the domain of the schedule with the virtual domain
1995 * first, since some iterations in the wrapped domain may be scheduled
1996 * several times, typically an infinite number of times.
1997 * Note that there is no need to perform this final wrapping
1998 * if the loop condition (after wrapping) is simple.
2000 * Wrapping on unsigned iterators can be avoided entirely if
2001 * loop condition is simple, the loop iterator is incremented
2002 * [decremented] by one and the last value before wrapping cannot
2003 * possibly satisfy the loop condition.
2005 * Before extracting a pet_scop from the body we remove all
2006 * assignments in assigned_value to variables that are assigned
2007 * somewhere in the body of the loop.
2009 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2011 BinaryOperator *ass;
2012 Decl *decl;
2013 Stmt *init;
2014 Expr *lhs, *rhs;
2015 ValueDecl *iv;
2016 isl_space *dim;
2017 isl_set *domain;
2018 isl_map *sched;
2019 isl_set *cond = NULL;
2020 isl_id *id;
2021 struct pet_scop *scop;
2022 assigned_value_cache cache(assigned_value);
2023 isl_int inc;
2024 bool is_one;
2025 bool is_unsigned;
2026 bool is_simple;
2027 isl_map *wrap = NULL;
2029 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2030 return extract_infinite_for(stmt);
2032 init = stmt->getInit();
2033 if (!init) {
2034 unsupported(stmt);
2035 return NULL;
2037 if ((ass = initialization_assignment(init)) != NULL) {
2038 iv = extract_induction_variable(ass);
2039 if (!iv)
2040 return NULL;
2041 lhs = ass->getLHS();
2042 rhs = ass->getRHS();
2043 } else if ((decl = initialization_declaration(init)) != NULL) {
2044 VarDecl *var = extract_induction_variable(init, decl);
2045 if (!var)
2046 return NULL;
2047 iv = var;
2048 rhs = var->getInit();
2049 lhs = create_DeclRefExpr(var);
2050 } else {
2051 unsupported(stmt->getInit());
2052 return NULL;
2055 isl_int_init(inc);
2056 if (!check_increment(stmt, iv, inc)) {
2057 isl_int_clear(inc);
2058 return NULL;
2061 is_unsigned = iv->getType()->isUnsignedIntegerType();
2063 assigned_value.erase(iv);
2064 clear_assignments clear(assigned_value);
2065 clear.TraverseStmt(stmt->getBody());
2067 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2069 is_one = isl_int_is_one(inc) || isl_int_is_negone(inc);
2070 if (is_one)
2071 domain = extract_comparison(isl_int_is_pos(inc) ? BO_GE : BO_LE,
2072 lhs, rhs, init);
2073 else {
2074 isl_pw_aff *lb = extract_affine(rhs);
2075 domain = strided_domain(isl_id_copy(id), lb, inc);
2078 scop = extract(stmt->getBody());
2080 cond = try_extract_nested_condition(stmt->getCond());
2081 if (cond && !is_nested_allowed(cond, scop)) {
2082 isl_set_free(cond);
2083 cond = NULL;
2086 if (!cond)
2087 cond = extract_condition(stmt->getCond());
2088 cond = embed(cond, isl_id_copy(id));
2089 domain = embed(domain, isl_id_copy(id));
2090 is_simple = is_simple_bound(cond, inc);
2091 if (is_unsigned &&
2092 (!is_simple || !is_one || can_wrap(cond, iv, inc))) {
2093 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2094 cond = isl_set_apply(cond, isl_map_reverse(isl_map_copy(wrap)));
2095 is_simple = is_simple && is_simple_bound(cond, inc);
2097 if (!is_simple)
2098 cond = valid_for_each_iteration(cond,
2099 isl_set_copy(domain), inc);
2100 domain = isl_set_intersect(domain, cond);
2101 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2102 dim = isl_space_from_domain(isl_set_get_space(domain));
2103 dim = isl_space_add_dims(dim, isl_dim_out, 1);
2104 sched = isl_map_universe(dim);
2105 if (isl_int_is_pos(inc))
2106 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
2107 else
2108 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
2110 if (is_unsigned && !is_simple) {
2111 wrap = isl_map_set_dim_id(wrap,
2112 isl_dim_out, 0, isl_id_copy(id));
2113 sched = isl_map_intersect_domain(sched, isl_set_copy(domain));
2114 domain = isl_set_apply(domain, isl_map_copy(wrap));
2115 sched = isl_map_apply_domain(sched, wrap);
2116 } else
2117 isl_map_free(wrap);
2119 scop = pet_scop_embed(scop, domain, sched, id);
2120 scop = resolve_nested(scop);
2121 clear_assignment(assigned_value, iv);
2123 isl_int_clear(inc);
2124 return scop;
2127 struct pet_scop *PetScan::extract(CompoundStmt *stmt)
2129 return extract(stmt->children());
2132 /* Does "id" refer to a nested access?
2134 static bool is_nested_parameter(__isl_keep isl_id *id)
2136 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2139 /* Does parameter "pos" of "space" refer to a nested access?
2141 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2143 bool nested;
2144 isl_id *id;
2146 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2147 nested = is_nested_parameter(id);
2148 isl_id_free(id);
2150 return nested;
2153 /* Does parameter "pos" of "map" refer to a nested access?
2155 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
2157 bool nested;
2158 isl_id *id;
2160 id = isl_map_get_dim_id(map, isl_dim_param, pos);
2161 nested = is_nested_parameter(id);
2162 isl_id_free(id);
2164 return nested;
2167 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2169 static int n_nested_parameter(__isl_keep isl_space *space)
2171 int n = 0;
2172 int nparam;
2174 nparam = isl_space_dim(space, isl_dim_param);
2175 for (int i = 0; i < nparam; ++i)
2176 if (is_nested_parameter(space, i))
2177 ++n;
2179 return n;
2182 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2184 static int n_nested_parameter(__isl_keep isl_map *map)
2186 isl_space *space;
2187 int n;
2189 space = isl_map_get_space(map);
2190 n = n_nested_parameter(space);
2191 isl_space_free(space);
2193 return n;
2196 /* For each nested access parameter in "space",
2197 * construct a corresponding pet_expr, place it in args and
2198 * record its position in "param2pos".
2199 * "n_arg" is the number of elements that are already in args.
2200 * The position recorded in "param2pos" takes this number into account.
2201 * If the pet_expr corresponding to a parameter is identical to
2202 * the pet_expr corresponding to an earlier parameter, then these two
2203 * parameters are made to refer to the same element in args.
2205 * Return the final number of elements in args or -1 if an error has occurred.
2207 int PetScan::extract_nested(__isl_keep isl_space *space,
2208 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
2210 int nparam;
2212 nparam = isl_space_dim(space, isl_dim_param);
2213 for (int i = 0; i < nparam; ++i) {
2214 int j;
2215 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2216 Expr *nested;
2218 if (!is_nested_parameter(id)) {
2219 isl_id_free(id);
2220 continue;
2223 nested = (Expr *) isl_id_get_user(id);
2224 args[n_arg] = extract_expr(nested);
2225 if (!args[n_arg])
2226 return -1;
2228 for (j = 0; j < n_arg; ++j)
2229 if (pet_expr_is_equal(args[j], args[n_arg]))
2230 break;
2232 if (j < n_arg) {
2233 pet_expr_free(args[n_arg]);
2234 args[n_arg] = NULL;
2235 param2pos[i] = j;
2236 } else
2237 param2pos[i] = n_arg++;
2239 isl_id_free(id);
2242 return n_arg;
2245 /* For each nested access parameter in the access relations in "expr",
2246 * construct a corresponding pet_expr, place it in expr->args and
2247 * record its position in "param2pos".
2248 * n is the number of nested access parameters.
2250 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
2251 std::map<int,int> &param2pos)
2253 isl_space *space;
2255 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
2256 expr->n_arg = n;
2257 if (!expr->args)
2258 goto error;
2260 space = isl_map_get_space(expr->acc.access);
2261 n = extract_nested(space, 0, expr->args, param2pos);
2262 isl_space_free(space);
2264 if (n < 0)
2265 goto error;
2267 expr->n_arg = n;
2268 return expr;
2269 error:
2270 pet_expr_free(expr);
2271 return NULL;
2274 /* Look for parameters in any access relation in "expr" that
2275 * refer to nested accesses. In particular, these are
2276 * parameters with no name.
2278 * If there are any such parameters, then the domain of the access
2279 * relation, which is still [] at this point, is replaced by
2280 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2281 * (after identifying identical nested accesses).
2282 * The parameters are then equated to the corresponding t dimensions
2283 * and subsequently projected out.
2284 * param2pos maps the position of the parameter to the position
2285 * of the corresponding t dimension.
2287 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
2289 int n;
2290 int nparam;
2291 int n_in;
2292 isl_space *dim;
2293 isl_map *map;
2294 std::map<int,int> param2pos;
2296 if (!expr)
2297 return expr;
2299 for (int i = 0; i < expr->n_arg; ++i) {
2300 expr->args[i] = resolve_nested(expr->args[i]);
2301 if (!expr->args[i]) {
2302 pet_expr_free(expr);
2303 return NULL;
2307 if (expr->type != pet_expr_access)
2308 return expr;
2310 n = n_nested_parameter(expr->acc.access);
2311 if (n == 0)
2312 return expr;
2314 expr = extract_nested(expr, n, param2pos);
2315 if (!expr)
2316 return NULL;
2318 n = expr->n_arg;
2319 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
2320 n_in = isl_map_dim(expr->acc.access, isl_dim_in);
2321 dim = isl_map_get_space(expr->acc.access);
2322 dim = isl_space_domain(dim);
2323 dim = isl_space_from_domain(dim);
2324 dim = isl_space_add_dims(dim, isl_dim_out, n);
2325 map = isl_map_universe(dim);
2326 map = isl_map_domain_map(map);
2327 map = isl_map_reverse(map);
2328 expr->acc.access = isl_map_apply_domain(expr->acc.access, map);
2330 for (int i = nparam - 1; i >= 0; --i) {
2331 isl_id *id = isl_map_get_dim_id(expr->acc.access,
2332 isl_dim_param, i);
2333 if (!is_nested_parameter(id)) {
2334 isl_id_free(id);
2335 continue;
2338 expr->acc.access = isl_map_equate(expr->acc.access,
2339 isl_dim_param, i, isl_dim_in,
2340 n_in + param2pos[i]);
2341 expr->acc.access = isl_map_project_out(expr->acc.access,
2342 isl_dim_param, i, 1);
2344 isl_id_free(id);
2347 return expr;
2348 error:
2349 pet_expr_free(expr);
2350 return NULL;
2353 /* Convert a top-level pet_expr to a pet_scop with one statement.
2354 * This mainly involves resolving nested expression parameters
2355 * and setting the name of the iteration space.
2356 * The name is given by "label" if it is non-NULL. Otherwise,
2357 * it is of the form S_<n_stmt>.
2359 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
2360 __isl_take isl_id *label)
2362 struct pet_stmt *ps;
2363 SourceLocation loc = stmt->getLocStart();
2364 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2366 expr = resolve_nested(expr);
2367 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
2368 return pet_scop_from_pet_stmt(ctx, ps);
2371 /* Check if we can extract an affine expression from "expr".
2372 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
2373 * We turn on autodetection so that we won't generate any warnings
2374 * and turn off nesting, so that we won't accept any non-affine constructs.
2376 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
2378 isl_pw_aff *pwaff;
2379 int save_autodetect = autodetect;
2380 bool save_nesting = nesting_enabled;
2382 autodetect = 1;
2383 nesting_enabled = false;
2385 pwaff = extract_affine(expr);
2387 autodetect = save_autodetect;
2388 nesting_enabled = save_nesting;
2390 return pwaff;
2393 /* Check whether "expr" is an affine expression.
2395 bool PetScan::is_affine(Expr *expr)
2397 isl_pw_aff *pwaff;
2399 pwaff = try_extract_affine(expr);
2400 isl_pw_aff_free(pwaff);
2402 return pwaff != NULL;
2405 /* Check whether "expr" is an affine constraint.
2406 * We turn on autodetection so that we won't generate any warnings
2407 * and turn off nesting, so that we won't accept any non-affine constructs.
2409 bool PetScan::is_affine_condition(Expr *expr)
2411 isl_set *set;
2412 int save_autodetect = autodetect;
2413 bool save_nesting = nesting_enabled;
2415 autodetect = 1;
2416 nesting_enabled = false;
2418 set = extract_condition(expr);
2419 isl_set_free(set);
2421 autodetect = save_autodetect;
2422 nesting_enabled = save_nesting;
2424 return set != NULL;
2427 /* Check if we can extract a condition from "expr".
2428 * Return the condition as an isl_set if we can and NULL otherwise.
2429 * If allow_nested is set, then the condition may involve parameters
2430 * corresponding to nested accesses.
2431 * We turn on autodetection so that we won't generate any warnings.
2433 __isl_give isl_set *PetScan::try_extract_nested_condition(Expr *expr)
2435 isl_set *set;
2436 int save_autodetect = autodetect;
2437 bool save_nesting = nesting_enabled;
2439 autodetect = 1;
2440 nesting_enabled = allow_nested;
2441 set = extract_condition(expr);
2443 autodetect = save_autodetect;
2444 nesting_enabled = save_nesting;
2446 return set;
2449 /* If the top-level expression of "stmt" is an assignment, then
2450 * return that assignment as a BinaryOperator.
2451 * Otherwise return NULL.
2453 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
2455 BinaryOperator *ass;
2457 if (!stmt)
2458 return NULL;
2459 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
2460 return NULL;
2462 ass = cast<BinaryOperator>(stmt);
2463 if(ass->getOpcode() != BO_Assign)
2464 return NULL;
2466 return ass;
2469 /* Check if the given if statement is a conditional assignement
2470 * with a non-affine condition. If so, construct a pet_scop
2471 * corresponding to this conditional assignment. Otherwise return NULL.
2473 * In particular we check if "stmt" is of the form
2475 * if (condition)
2476 * a = f(...);
2477 * else
2478 * a = g(...);
2480 * where a is some array or scalar access.
2481 * The constructed pet_scop then corresponds to the expression
2483 * a = condition ? f(...) : g(...)
2485 * All access relations in f(...) are intersected with condition
2486 * while all access relation in g(...) are intersected with the complement.
2488 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
2490 BinaryOperator *ass_then, *ass_else;
2491 isl_map *write_then, *write_else;
2492 isl_set *cond, *comp;
2493 isl_map *map, *map_true, *map_false;
2494 int equal;
2495 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
2496 bool save_nesting = nesting_enabled;
2498 ass_then = top_assignment_or_null(stmt->getThen());
2499 ass_else = top_assignment_or_null(stmt->getElse());
2501 if (!ass_then || !ass_else)
2502 return NULL;
2504 if (is_affine_condition(stmt->getCond()))
2505 return NULL;
2507 write_then = extract_access(ass_then->getLHS());
2508 write_else = extract_access(ass_else->getLHS());
2510 equal = isl_map_is_equal(write_then, write_else);
2511 isl_map_free(write_else);
2512 if (equal < 0 || !equal) {
2513 isl_map_free(write_then);
2514 return NULL;
2517 nesting_enabled = allow_nested;
2518 cond = extract_condition(stmt->getCond());
2519 nesting_enabled = save_nesting;
2520 comp = isl_set_complement(isl_set_copy(cond));
2521 map_true = isl_map_from_domain(isl_set_from_params(isl_set_copy(cond)));
2522 map_true = isl_map_add_dims(map_true, isl_dim_out, 1);
2523 map_true = isl_map_fix_si(map_true, isl_dim_out, 0, 1);
2524 map_false = isl_map_from_domain(isl_set_from_params(isl_set_copy(comp)));
2525 map_false = isl_map_add_dims(map_false, isl_dim_out, 1);
2526 map_false = isl_map_fix_si(map_false, isl_dim_out, 0, 0);
2527 map = isl_map_union_disjoint(map_true, map_false);
2529 pe_cond = pet_expr_from_access(map);
2531 pe_then = extract_expr(ass_then->getRHS());
2532 pe_then = pet_expr_restrict(pe_then, cond);
2533 pe_else = extract_expr(ass_else->getRHS());
2534 pe_else = pet_expr_restrict(pe_else, comp);
2536 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
2537 pe_write = pet_expr_from_access(write_then);
2538 if (pe_write) {
2539 pe_write->acc.write = 1;
2540 pe_write->acc.read = 0;
2542 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
2543 return extract(stmt, pe);
2546 /* Create an access to a virtual array representing the result
2547 * of a condition.
2548 * Unlike other accessed data, the id of the array is NULL as
2549 * there is no ValueDecl in the program corresponding to the virtual
2550 * array.
2551 * The array starts out as a scalar, but grows along with the
2552 * statement writing to the array in pet_scop_embed.
2554 static __isl_give isl_map *create_test_access(isl_ctx *ctx, int test_nr)
2556 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2557 isl_id *id;
2558 char name[50];
2560 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2561 id = isl_id_alloc(ctx, name, NULL);
2562 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2563 return isl_map_universe(dim);
2566 /* Create a pet_scop with a single statement evaluating "cond"
2567 * and writing the result to a virtual scalar, as expressed by
2568 * "access".
2570 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond,
2571 __isl_take isl_map *access)
2573 struct pet_expr *expr, *write;
2574 struct pet_stmt *ps;
2575 SourceLocation loc = cond->getLocStart();
2576 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2578 write = pet_expr_from_access(access);
2579 if (write) {
2580 write->acc.write = 1;
2581 write->acc.read = 0;
2583 expr = extract_expr(cond);
2584 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
2585 ps = pet_stmt_from_pet_expr(ctx, line, NULL, n_stmt++, expr);
2586 return pet_scop_from_pet_stmt(ctx, ps);
2589 /* Add an array with the given extent ("access") to the list
2590 * of arrays in "scop" and return the extended pet_scop.
2591 * The array is marked as attaining values 0 and 1 only.
2593 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2594 __isl_keep isl_map *access, clang::ASTContext &ast_ctx)
2596 isl_ctx *ctx = isl_map_get_ctx(access);
2597 isl_space *dim;
2598 struct pet_array **arrays;
2599 struct pet_array *array;
2601 if (!scop)
2602 return NULL;
2603 if (!ctx)
2604 goto error;
2606 arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2607 scop->n_array + 1);
2608 if (!arrays)
2609 goto error;
2610 scop->arrays = arrays;
2612 array = isl_calloc_type(ctx, struct pet_array);
2613 if (!array)
2614 goto error;
2616 array->extent = isl_map_range(isl_map_copy(access));
2617 dim = isl_space_params_alloc(ctx, 0);
2618 array->context = isl_set_universe(dim);
2619 dim = isl_space_set_alloc(ctx, 0, 1);
2620 array->value_bounds = isl_set_universe(dim);
2621 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2622 isl_dim_set, 0, 0);
2623 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2624 isl_dim_set, 0, 1);
2625 array->element_type = strdup("int");
2626 array->element_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2628 scop->arrays[scop->n_array] = array;
2629 scop->n_array++;
2631 if (!array->extent || !array->context)
2632 goto error;
2634 return scop;
2635 error:
2636 pet_scop_free(scop);
2637 return NULL;
2640 extern "C" {
2641 static __isl_give isl_map *embed_access(__isl_take isl_map *access,
2642 void *user);
2645 /* Apply the map pointed to by "user" to the domain of the access
2646 * relation, thereby embedding it in the range of the map.
2647 * The domain of both relations is the zero-dimensional domain.
2649 static __isl_give isl_map *embed_access(__isl_take isl_map *access, void *user)
2651 isl_map *map = (isl_map *) user;
2653 return isl_map_apply_domain(access, isl_map_copy(map));
2656 /* Apply "map" to all access relations in "expr".
2658 static struct pet_expr *embed(struct pet_expr *expr, __isl_keep isl_map *map)
2660 return pet_expr_foreach_access(expr, &embed_access, map);
2663 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
2665 static int n_nested_parameter(__isl_keep isl_set *set)
2667 isl_space *space;
2668 int n;
2670 space = isl_set_get_space(set);
2671 n = n_nested_parameter(space);
2672 isl_space_free(space);
2674 return n;
2677 /* Remove all parameters from "map" that refer to nested accesses.
2679 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
2681 int nparam;
2682 isl_space *space;
2684 space = isl_map_get_space(map);
2685 nparam = isl_space_dim(space, isl_dim_param);
2686 for (int i = nparam - 1; i >= 0; --i)
2687 if (is_nested_parameter(space, i))
2688 map = isl_map_project_out(map, isl_dim_param, i, 1);
2689 isl_space_free(space);
2691 return map;
2694 extern "C" {
2695 static __isl_give isl_map *access_remove_nested_parameters(
2696 __isl_take isl_map *access, void *user);
2699 static __isl_give isl_map *access_remove_nested_parameters(
2700 __isl_take isl_map *access, void *user)
2702 return remove_nested_parameters(access);
2705 /* Remove all nested access parameters from the schedule and all
2706 * accesses of "stmt".
2707 * There is no need to remove them from the domain as these parameters
2708 * have already been removed from the domain when this function is called.
2710 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
2712 if (!stmt)
2713 return NULL;
2714 stmt->schedule = remove_nested_parameters(stmt->schedule);
2715 stmt->body = pet_expr_foreach_access(stmt->body,
2716 &access_remove_nested_parameters, NULL);
2717 if (!stmt->schedule || !stmt->body)
2718 goto error;
2719 for (int i = 0; i < stmt->n_arg; ++i) {
2720 stmt->args[i] = pet_expr_foreach_access(stmt->args[i],
2721 &access_remove_nested_parameters, NULL);
2722 if (!stmt->args[i])
2723 goto error;
2726 return stmt;
2727 error:
2728 pet_stmt_free(stmt);
2729 return NULL;
2732 /* For each nested access parameter in the domain of "stmt",
2733 * construct a corresponding pet_expr, place it in stmt->args and
2734 * record its position in "param2pos".
2735 * n is the number of nested access parameters.
2737 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
2738 std::map<int,int> &param2pos)
2740 isl_space *space;
2741 unsigned n_arg;
2742 struct pet_expr **args;
2744 n_arg = stmt->n_arg;
2745 args = isl_realloc_array(ctx, stmt->args, struct pet_expr *, n_arg + n);
2746 if (!args)
2747 goto error;
2748 stmt->args = args;
2749 stmt->n_arg += n;
2751 space = isl_set_get_space(stmt->domain);
2752 n = extract_nested(space, n_arg, stmt->args, param2pos);
2753 isl_space_free(space);
2755 if (n < 0)
2756 goto error;
2758 stmt->n_arg = n;
2759 return stmt;
2760 error:
2761 pet_stmt_free(stmt);
2762 return NULL;
2765 /* Look for parameters in the iteration domain of "stmt" that
2766 * refer to nested accesses. In particular, these are
2767 * parameters with no name.
2769 * If there are any such parameters, then as many extra variables
2770 * (after identifying identical nested accesses) are added to the
2771 * range of the map wrapped inside the domain.
2772 * If the original domain is not a wrapped map, then a new wrapped
2773 * map is created with zero output dimensions.
2774 * The parameters are then equated to the corresponding output dimensions
2775 * and subsequently projected out, from the iteration domain,
2776 * the schedule and the access relations.
2777 * For each of the output dimensions, a corresponding argument
2778 * expression is added. Initially they are created with
2779 * a zero-dimensional domain, so they have to be embedded
2780 * in the current iteration domain.
2781 * param2pos maps the position of the parameter to the position
2782 * of the corresponding output dimension in the wrapped map.
2784 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
2786 int n;
2787 int nparam;
2788 unsigned n_arg;
2789 isl_map *map;
2790 std::map<int,int> param2pos;
2792 if (!stmt)
2793 return NULL;
2795 n = n_nested_parameter(stmt->domain);
2796 if (n == 0)
2797 return stmt;
2799 n_arg = stmt->n_arg;
2800 stmt = extract_nested(stmt, n, param2pos);
2801 if (!stmt)
2802 return NULL;
2804 n = stmt->n_arg - n_arg;
2805 nparam = isl_set_dim(stmt->domain, isl_dim_param);
2806 if (isl_set_is_wrapping(stmt->domain))
2807 map = isl_set_unwrap(stmt->domain);
2808 else
2809 map = isl_map_from_domain(stmt->domain);
2810 map = isl_map_add_dims(map, isl_dim_out, n);
2812 for (int i = nparam - 1; i >= 0; --i) {
2813 isl_id *id;
2815 if (!is_nested_parameter(map, i))
2816 continue;
2818 id = isl_map_get_tuple_id(stmt->args[param2pos[i]]->acc.access,
2819 isl_dim_out);
2820 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
2821 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
2822 param2pos[i]);
2823 map = isl_map_project_out(map, isl_dim_param, i, 1);
2826 stmt->domain = isl_map_wrap(map);
2828 map = isl_set_unwrap(isl_set_copy(stmt->domain));
2829 map = isl_map_from_range(isl_map_domain(map));
2830 for (int pos = n_arg; pos < stmt->n_arg; ++pos)
2831 stmt->args[pos] = embed(stmt->args[pos], map);
2832 isl_map_free(map);
2834 stmt = remove_nested_parameters(stmt);
2836 return stmt;
2837 error:
2838 pet_stmt_free(stmt);
2839 return NULL;
2842 /* For each statement in "scop", move the parameters that correspond
2843 * to nested access into the ranges of the domains and create
2844 * corresponding argument expressions.
2846 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
2848 if (!scop)
2849 return NULL;
2851 for (int i = 0; i < scop->n_stmt; ++i) {
2852 scop->stmts[i] = resolve_nested(scop->stmts[i]);
2853 if (!scop->stmts[i])
2854 goto error;
2857 return scop;
2858 error:
2859 pet_scop_free(scop);
2860 return NULL;
2863 /* Does "space" involve any parameters that refer to nested
2864 * accesses, i.e., parameters with no name?
2866 static bool has_nested(__isl_keep isl_space *space)
2868 int nparam;
2870 nparam = isl_space_dim(space, isl_dim_param);
2871 for (int i = 0; i < nparam; ++i)
2872 if (is_nested_parameter(space, i))
2873 return true;
2875 return false;
2878 /* Does "set" involve any parameters that refer to nested
2879 * accesses, i.e., parameters with no name?
2881 static bool has_nested(__isl_keep isl_set *set)
2883 isl_space *space;
2884 bool nested;
2886 space = isl_set_get_space(set);
2887 nested = has_nested(space);
2888 isl_space_free(space);
2890 return nested;
2893 /* Given an access expression "expr", is the variable accessed by
2894 * "expr" assigned anywhere inside "scop"?
2896 static bool is_assigned(pet_expr *expr, pet_scop *scop)
2898 bool assigned = false;
2899 isl_id *id;
2901 id = isl_map_get_tuple_id(expr->acc.access, isl_dim_out);
2902 assigned = pet_scop_writes(scop, id);
2903 isl_id_free(id);
2905 return assigned;
2908 /* Are all nested access parameters in "set" allowed given "scop".
2909 * In particular, is none of them written by anywhere inside "scop".
2911 bool PetScan::is_nested_allowed(__isl_keep isl_set *set, pet_scop *scop)
2913 int nparam;
2915 nparam = isl_set_dim(set, isl_dim_param);
2916 for (int i = 0; i < nparam; ++i) {
2917 Expr *nested;
2918 isl_id *id = isl_set_get_dim_id(set, isl_dim_param, i);
2919 pet_expr *expr;
2920 bool allowed;
2922 if (!is_nested_parameter(id)) {
2923 isl_id_free(id);
2924 continue;
2927 nested = (Expr *) isl_id_get_user(id);
2928 expr = extract_expr(nested);
2929 allowed = expr && expr->type == pet_expr_access &&
2930 !is_assigned(expr, scop);
2932 pet_expr_free(expr);
2933 isl_id_free(id);
2935 if (!allowed)
2936 return false;
2939 return true;
2942 /* Construct a pet_scop for an if statement.
2944 * If the condition fits the pattern of a conditional assignment,
2945 * then it is handled by extract_conditional_assignment.
2946 * Otherwise, we do the following.
2948 * If the condition is affine, then the condition is added
2949 * to the iteration domains of the then branch, while the
2950 * opposite of the condition in added to the iteration domains
2951 * of the else branch, if any.
2952 * We allow the condition to be dynamic, i.e., to refer to
2953 * scalars or array elements that may be written to outside
2954 * of the given if statement. These nested accesses are then represented
2955 * as output dimensions in the wrapping iteration domain.
2956 * If it also written _inside_ the then or else branch, then
2957 * we treat the condition as non-affine.
2958 * As explained below, this will introduce an extra statement.
2959 * For aesthetic reasons, we want this statement to have a statement
2960 * number that is lower than those of the then and else branches.
2961 * In order to evaluate if will need such a statement, however, we
2962 * first construct scops for the then and else branches.
2963 * We therefore reserve a statement number if we might have to
2964 * introduce such an extra statement.
2966 * If the condition is not affine, then we create a separate
2967 * statement that writes the result of the condition to a virtual scalar.
2968 * A constraint requiring the value of this virtual scalar to be one
2969 * is added to the iteration domains of the then branch.
2970 * Similarly, a constraint requiring the value of this virtual scalar
2971 * to be zero is added to the iteration domains of the else branch, if any.
2972 * We adjust the schedules to ensure that the virtual scalar is written
2973 * before it is read.
2975 struct pet_scop *PetScan::extract(IfStmt *stmt)
2977 struct pet_scop *scop_then, *scop_else, *scop;
2978 assigned_value_cache cache(assigned_value);
2979 isl_map *test_access = NULL;
2980 isl_set *cond;
2981 int stmt_id;
2983 scop = extract_conditional_assignment(stmt);
2984 if (scop)
2985 return scop;
2987 cond = try_extract_nested_condition(stmt->getCond());
2988 if (allow_nested && (!cond || has_nested(cond)))
2989 stmt_id = n_stmt++;
2991 scop_then = extract(stmt->getThen());
2993 if (stmt->getElse()) {
2994 scop_else = extract(stmt->getElse());
2995 if (autodetect) {
2996 if (scop_then && !scop_else) {
2997 partial = true;
2998 isl_set_free(cond);
2999 return scop_then;
3001 if (!scop_then && scop_else) {
3002 partial = true;
3003 isl_set_free(cond);
3004 return scop_else;
3009 if (cond &&
3010 (!is_nested_allowed(cond, scop_then) ||
3011 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
3012 isl_set_free(cond);
3013 cond = NULL;
3015 if (allow_nested && !cond) {
3016 int save_n_stmt = n_stmt;
3017 test_access = create_test_access(ctx, n_test++);
3018 n_stmt = stmt_id;
3019 scop = extract_non_affine_condition(stmt->getCond(),
3020 isl_map_copy(test_access));
3021 n_stmt = save_n_stmt;
3022 scop = scop_add_array(scop, test_access, ast_context);
3023 if (!scop) {
3024 pet_scop_free(scop_then);
3025 pet_scop_free(scop_else);
3026 isl_map_free(test_access);
3027 return NULL;
3031 if (!scop) {
3032 if (!cond)
3033 cond = extract_condition(stmt->getCond());
3034 scop = pet_scop_restrict(scop_then, isl_set_copy(cond));
3036 if (stmt->getElse()) {
3037 cond = isl_set_complement(cond);
3038 scop_else = pet_scop_restrict(scop_else, cond);
3039 scop = pet_scop_add(ctx, scop, scop_else);
3040 } else
3041 isl_set_free(cond);
3042 scop = resolve_nested(scop);
3043 } else {
3044 scop = pet_scop_prefix(scop, 0);
3045 scop_then = pet_scop_prefix(scop_then, 1);
3046 scop_then = pet_scop_filter(scop_then,
3047 isl_map_copy(test_access), 1);
3048 scop = pet_scop_add(ctx, scop, scop_then);
3049 if (stmt->getElse()) {
3050 scop_else = pet_scop_prefix(scop_else, 1);
3051 scop_else = pet_scop_filter(scop_else, test_access, 0);
3052 scop = pet_scop_add(ctx, scop, scop_else);
3053 } else
3054 isl_map_free(test_access);
3057 return scop;
3060 /* Try and construct a pet_scop for a label statement.
3061 * We currently only allow labels on expression statements.
3063 struct pet_scop *PetScan::extract(LabelStmt *stmt)
3065 isl_id *label;
3066 Stmt *sub;
3068 sub = stmt->getSubStmt();
3069 if (!isa<Expr>(sub)) {
3070 unsupported(stmt);
3071 return NULL;
3074 label = isl_id_alloc(ctx, stmt->getName(), NULL);
3076 return extract(sub, extract_expr(cast<Expr>(sub)), label);
3079 /* Try and construct a pet_scop corresponding to "stmt".
3081 struct pet_scop *PetScan::extract(Stmt *stmt)
3083 if (isa<Expr>(stmt))
3084 return extract(stmt, extract_expr(cast<Expr>(stmt)));
3086 switch (stmt->getStmtClass()) {
3087 case Stmt::WhileStmtClass:
3088 return extract(cast<WhileStmt>(stmt));
3089 case Stmt::ForStmtClass:
3090 return extract_for(cast<ForStmt>(stmt));
3091 case Stmt::IfStmtClass:
3092 return extract(cast<IfStmt>(stmt));
3093 case Stmt::CompoundStmtClass:
3094 return extract(cast<CompoundStmt>(stmt));
3095 case Stmt::LabelStmtClass:
3096 return extract(cast<LabelStmt>(stmt));
3097 default:
3098 unsupported(stmt);
3101 return NULL;
3104 /* Try and construct a pet_scop corresponding to (part of)
3105 * a sequence of statements.
3107 struct pet_scop *PetScan::extract(StmtRange stmt_range)
3109 pet_scop *scop;
3110 StmtIterator i;
3111 int j;
3112 bool partial_range = false;
3114 scop = pet_scop_empty(ctx);
3115 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
3116 Stmt *child = *i;
3117 struct pet_scop *scop_i;
3118 scop_i = extract(child);
3119 if (scop && partial) {
3120 pet_scop_free(scop_i);
3121 break;
3123 scop_i = pet_scop_prefix(scop_i, j);
3124 if (autodetect) {
3125 if (scop_i)
3126 scop = pet_scop_add(ctx, scop, scop_i);
3127 else
3128 partial_range = true;
3129 if (scop->n_stmt != 0 && !scop_i)
3130 partial = true;
3131 } else {
3132 scop = pet_scop_add(ctx, scop, scop_i);
3134 if (partial)
3135 break;
3138 if (scop && partial_range)
3139 partial = true;
3141 return scop;
3144 /* Check if the scop marked by the user is exactly this Stmt
3145 * or part of this Stmt.
3146 * If so, return a pet_scop corresponding to the marked region.
3147 * Otherwise, return NULL.
3149 struct pet_scop *PetScan::scan(Stmt *stmt)
3151 SourceManager &SM = PP.getSourceManager();
3152 unsigned start_off, end_off;
3154 start_off = SM.getFileOffset(stmt->getLocStart());
3155 end_off = SM.getFileOffset(stmt->getLocEnd());
3157 if (start_off > loc.end)
3158 return NULL;
3159 if (end_off < loc.start)
3160 return NULL;
3161 if (start_off >= loc.start && end_off <= loc.end) {
3162 return extract(stmt);
3165 StmtIterator start;
3166 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
3167 Stmt *child = *start;
3168 if (!child)
3169 continue;
3170 start_off = SM.getFileOffset(child->getLocStart());
3171 end_off = SM.getFileOffset(child->getLocEnd());
3172 if (start_off < loc.start && end_off > loc.end)
3173 return scan(child);
3174 if (start_off >= loc.start)
3175 break;
3178 StmtIterator end;
3179 for (end = start; end != stmt->child_end(); ++end) {
3180 Stmt *child = *end;
3181 start_off = SM.getFileOffset(child->getLocStart());
3182 if (start_off >= loc.end)
3183 break;
3186 return extract(StmtRange(start, end));
3189 /* Set the size of index "pos" of "array" to "size".
3190 * In particular, add a constraint of the form
3192 * i_pos < size
3194 * to array->extent and a constraint of the form
3196 * size >= 0
3198 * to array->context.
3200 static struct pet_array *update_size(struct pet_array *array, int pos,
3201 __isl_take isl_pw_aff *size)
3203 isl_set *valid;
3204 isl_set *univ;
3205 isl_set *bound;
3206 isl_space *dim;
3207 isl_aff *aff;
3208 isl_pw_aff *index;
3209 isl_id *id;
3211 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
3212 array->context = isl_set_intersect(array->context, valid);
3214 dim = isl_set_get_space(array->extent);
3215 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
3216 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
3217 univ = isl_set_universe(isl_aff_get_domain_space(aff));
3218 index = isl_pw_aff_alloc(univ, aff);
3220 size = isl_pw_aff_add_dims(size, isl_dim_in,
3221 isl_set_dim(array->extent, isl_dim_set));
3222 id = isl_set_get_tuple_id(array->extent);
3223 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
3224 bound = isl_pw_aff_lt_set(index, size);
3226 array->extent = isl_set_intersect(array->extent, bound);
3228 if (!array->context || !array->extent)
3229 goto error;
3231 return array;
3232 error:
3233 pet_array_free(array);
3234 return NULL;
3237 /* Figure out the size of the array at position "pos" and all
3238 * subsequent positions from "type" and update "array" accordingly.
3240 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
3241 const Type *type, int pos)
3243 const ArrayType *atype;
3244 isl_pw_aff *size;
3246 if (!array)
3247 return NULL;
3249 if (type->isPointerType()) {
3250 type = type->getPointeeType().getTypePtr();
3251 return set_upper_bounds(array, type, pos + 1);
3253 if (!type->isArrayType())
3254 return array;
3256 type = type->getCanonicalTypeInternal().getTypePtr();
3257 atype = cast<ArrayType>(type);
3259 if (type->isConstantArrayType()) {
3260 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
3261 size = extract_affine(ca->getSize());
3262 array = update_size(array, pos, size);
3263 } else if (type->isVariableArrayType()) {
3264 const VariableArrayType *vla = cast<VariableArrayType>(atype);
3265 size = extract_affine(vla->getSizeExpr());
3266 array = update_size(array, pos, size);
3269 type = atype->getElementType().getTypePtr();
3271 return set_upper_bounds(array, type, pos + 1);
3274 /* Construct and return a pet_array corresponding to the variable "decl".
3275 * In particular, initialize array->extent to
3277 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
3279 * and then call set_upper_bounds to set the upper bounds on the indices
3280 * based on the type of the variable.
3282 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl)
3284 struct pet_array *array;
3285 QualType qt = decl->getType();
3286 const Type *type = qt.getTypePtr();
3287 int depth = array_depth(type);
3288 QualType base = base_type(qt);
3289 string name;
3290 isl_id *id;
3291 isl_space *dim;
3293 array = isl_calloc_type(ctx, struct pet_array);
3294 if (!array)
3295 return NULL;
3297 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
3298 dim = isl_space_set_alloc(ctx, 0, depth);
3299 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
3301 array->extent = isl_set_nat_universe(dim);
3303 dim = isl_space_params_alloc(ctx, 0);
3304 array->context = isl_set_universe(dim);
3306 array = set_upper_bounds(array, type, 0);
3307 if (!array)
3308 return NULL;
3310 name = base.getAsString();
3311 array->element_type = strdup(name.c_str());
3312 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
3314 return array;
3317 /* Construct a list of pet_arrays, one for each array (or scalar)
3318 * accessed inside "scop" add this list to "scop" and return the result.
3320 * The context of "scop" is updated with the intesection of
3321 * the contexts of all arrays, i.e., constraints on the parameters
3322 * that ensure that the arrays have a valid (non-negative) size.
3324 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
3326 int i;
3327 set<ValueDecl *> arrays;
3328 set<ValueDecl *>::iterator it;
3329 int n_array;
3330 struct pet_array **scop_arrays;
3332 if (!scop)
3333 return NULL;
3335 pet_scop_collect_arrays(scop, arrays);
3336 if (arrays.size() == 0)
3337 return scop;
3339 n_array = scop->n_array;
3341 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
3342 n_array + arrays.size());
3343 if (!scop_arrays)
3344 goto error;
3345 scop->arrays = scop_arrays;
3347 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
3348 struct pet_array *array;
3349 scop->arrays[n_array + i] = array = extract_array(ctx, *it);
3350 if (!scop->arrays[n_array + i])
3351 goto error;
3352 scop->n_array++;
3353 scop->context = isl_set_intersect(scop->context,
3354 isl_set_copy(array->context));
3355 if (!scop->context)
3356 goto error;
3359 return scop;
3360 error:
3361 pet_scop_free(scop);
3362 return NULL;
3365 /* Construct a pet_scop from the given function.
3367 struct pet_scop *PetScan::scan(FunctionDecl *fd)
3369 pet_scop *scop;
3370 Stmt *stmt;
3372 stmt = fd->getBody();
3374 if (autodetect)
3375 scop = extract(stmt);
3376 else
3377 scop = scan(stmt);
3378 scop = pet_scop_detect_parameter_accesses(scop);
3379 scop = scan_arrays(scop);
3381 return scop;