adjust to change in number of arguments of DeclRefExpr::Create
[pet.git] / scan.cc
blobe33b571fab326da3f9ce95481fe235c3a1befb4d
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);
253 /* Called if we found something we (currently) cannot handle.
254 * We'll provide more informative warnings later.
256 * We only actually complain if autodetect is false.
258 void PetScan::unsupported(Stmt *stmt, const char *msg)
260 if (autodetect)
261 return;
263 SourceLocation loc = stmt->getLocStart();
264 DiagnosticsEngine &diag = PP.getDiagnostics();
265 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
266 msg ? msg : "unsupported");
267 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
270 /* Extract an integer from "expr" and store it in "v".
272 int PetScan::extract_int(IntegerLiteral *expr, isl_int *v)
274 const Type *type = expr->getType().getTypePtr();
275 int is_signed = type->hasSignedIntegerRepresentation();
277 if (is_signed) {
278 int64_t i = expr->getValue().getSExtValue();
279 isl_int_set_si(*v, i);
280 } else {
281 uint64_t i = expr->getValue().getZExtValue();
282 isl_int_set_ui(*v, i);
285 return 0;
288 /* Extract an integer from "expr" and store it in "v".
289 * Return -1 if "expr" does not (obviously) represent an integer.
291 int PetScan::extract_int(clang::ParenExpr *expr, isl_int *v)
293 return extract_int(expr->getSubExpr(), v);
296 /* Extract an integer from "expr" and store it in "v".
297 * Return -1 if "expr" does not (obviously) represent an integer.
299 int PetScan::extract_int(clang::Expr *expr, isl_int *v)
301 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
302 return extract_int(cast<IntegerLiteral>(expr), v);
303 if (expr->getStmtClass() == Stmt::ParenExprClass)
304 return extract_int(cast<ParenExpr>(expr), v);
306 unsupported(expr);
307 return -1;
310 /* Extract an affine expression from the IntegerLiteral "expr".
312 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
314 isl_space *dim = isl_space_params_alloc(ctx, 0);
315 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
316 isl_aff *aff = isl_aff_zero_on_domain(ls);
317 isl_set *dom = isl_set_universe(dim);
318 isl_int v;
320 isl_int_init(v);
321 extract_int(expr, &v);
322 aff = isl_aff_add_constant(aff, v);
323 isl_int_clear(v);
325 return isl_pw_aff_alloc(dom, aff);
328 /* Extract an affine expression from the APInt "val".
330 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
332 isl_space *dim = isl_space_params_alloc(ctx, 0);
333 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
334 isl_aff *aff = isl_aff_zero_on_domain(ls);
335 isl_set *dom = isl_set_universe(dim);
336 isl_int v;
338 isl_int_init(v);
339 isl_int_set_ui(v, val.getZExtValue());
340 aff = isl_aff_add_constant(aff, v);
341 isl_int_clear(v);
343 return isl_pw_aff_alloc(dom, aff);
346 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
348 return extract_affine(expr->getSubExpr());
351 /* Extract an affine expression from the DeclRefExpr "expr".
353 * If the variable has been assigned a value, then we check whether
354 * we know what (affine) value was assigned.
355 * If so, we return this value. Otherwise we convert "expr"
356 * to an extra parameter (provided nesting_enabled is set).
358 * Otherwise, we simply return an expression that is equal
359 * to a parameter corresponding to the referenced variable.
361 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
363 ValueDecl *decl = expr->getDecl();
364 const Type *type = decl->getType().getTypePtr();
365 isl_id *id;
366 isl_space *dim;
367 isl_aff *aff;
368 isl_set *dom;
370 if (!type->isIntegerType()) {
371 unsupported(expr);
372 return NULL;
375 if (assigned_value.find(decl) != assigned_value.end()) {
376 if (assigned_value[decl])
377 return isl_pw_aff_copy(assigned_value[decl]);
378 else
379 return nested_access(expr);
382 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
383 dim = isl_space_params_alloc(ctx, 1);
385 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
387 dom = isl_set_universe(isl_space_copy(dim));
388 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
389 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
391 return isl_pw_aff_alloc(dom, aff);
394 /* Extract an affine expression from an integer division operation.
395 * In particular, if "expr" is lhs/rhs, then return
397 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
399 * The second argument (rhs) is required to be a (positive) integer constant.
401 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
403 Expr *rhs_expr;
404 isl_pw_aff *lhs, *lhs_f, *lhs_c;
405 isl_pw_aff *res;
406 isl_int v;
407 isl_set *cond;
409 rhs_expr = expr->getRHS();
410 isl_int_init(v);
411 if (extract_int(rhs_expr, &v) < 0) {
412 isl_int_clear(v);
413 return NULL;
416 lhs = extract_affine(expr->getLHS());
417 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
419 lhs = isl_pw_aff_scale_down(lhs, v);
420 isl_int_clear(v);
422 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(lhs));
423 lhs_c = isl_pw_aff_ceil(lhs);
424 res = isl_pw_aff_cond(cond, lhs_f, lhs_c);
426 return res;
429 /* Extract an affine expression from a modulo operation.
430 * In particular, if "expr" is lhs/rhs, then return
432 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
434 * The second argument (rhs) is required to be a (positive) integer constant.
436 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
438 Expr *rhs_expr;
439 isl_pw_aff *lhs, *lhs_f, *lhs_c;
440 isl_pw_aff *res;
441 isl_int v;
442 isl_set *cond;
444 rhs_expr = expr->getRHS();
445 if (rhs_expr->getStmtClass() != Stmt::IntegerLiteralClass) {
446 unsupported(expr);
447 return NULL;
450 lhs = extract_affine(expr->getLHS());
451 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
453 isl_int_init(v);
454 extract_int(cast<IntegerLiteral>(rhs_expr), &v);
455 res = isl_pw_aff_scale_down(isl_pw_aff_copy(lhs), v);
457 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(res));
458 lhs_c = isl_pw_aff_ceil(res);
459 res = isl_pw_aff_cond(cond, lhs_f, lhs_c);
461 res = isl_pw_aff_scale(res, v);
462 isl_int_clear(v);
464 res = isl_pw_aff_sub(lhs, res);
466 return res;
469 /* Extract an affine expression from a multiplication operation.
470 * This is only allowed if at least one of the two arguments
471 * is a (piecewise) constant.
473 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
475 isl_pw_aff *lhs;
476 isl_pw_aff *rhs;
478 lhs = extract_affine(expr->getLHS());
479 rhs = extract_affine(expr->getRHS());
481 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
482 isl_pw_aff_free(lhs);
483 isl_pw_aff_free(rhs);
484 unsupported(expr);
485 return NULL;
488 return isl_pw_aff_mul(lhs, rhs);
491 /* Extract an affine expression from an addition or subtraction operation.
493 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
495 isl_pw_aff *lhs;
496 isl_pw_aff *rhs;
498 lhs = extract_affine(expr->getLHS());
499 rhs = extract_affine(expr->getRHS());
501 switch (expr->getOpcode()) {
502 case BO_Add:
503 return isl_pw_aff_add(lhs, rhs);
504 case BO_Sub:
505 return isl_pw_aff_sub(lhs, rhs);
506 default:
507 isl_pw_aff_free(lhs);
508 isl_pw_aff_free(rhs);
509 return NULL;
514 /* Compute
516 * pwaff mod 2^width
518 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
519 unsigned width)
521 isl_int mod;
523 isl_int_init(mod);
524 isl_int_set_si(mod, 1);
525 isl_int_mul_2exp(mod, mod, width);
527 pwaff = isl_pw_aff_mod(pwaff, mod);
529 isl_int_clear(mod);
531 return pwaff;
534 /* Extract an affine expression from a boolean expression.
535 * In particular, return the expression "expr ? 1 : 0".
537 __isl_give isl_pw_aff *PetScan::extract_implicit_affine(Expr *expr)
539 isl_set *cond = extract_condition(expr);
540 isl_space *space = isl_set_get_space(cond);
541 isl_local_space *ls = isl_local_space_from_space(space);
542 isl_aff *zero = isl_aff_zero_on_domain(isl_local_space_copy(ls));
543 isl_aff *one = isl_aff_zero_on_domain(ls);
544 one = isl_aff_add_constant_si(one, 1);
545 return isl_pw_aff_cond(cond, isl_pw_aff_from_aff(one),
546 isl_pw_aff_from_aff(zero));
549 /* Extract an affine expression from some binary operations.
550 * If the result of the expression is unsigned, then we wrap it
551 * based on the size of the type.
553 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
555 isl_pw_aff *res;
557 switch (expr->getOpcode()) {
558 case BO_Add:
559 case BO_Sub:
560 res = extract_affine_add(expr);
561 break;
562 case BO_Div:
563 res = extract_affine_div(expr);
564 break;
565 case BO_Rem:
566 res = extract_affine_mod(expr);
567 break;
568 case BO_Mul:
569 res = extract_affine_mul(expr);
570 break;
571 case BO_LT:
572 case BO_LE:
573 case BO_GT:
574 case BO_GE:
575 case BO_EQ:
576 case BO_NE:
577 case BO_LAnd:
578 case BO_LOr:
579 res = extract_implicit_affine(expr);
580 break;
581 default:
582 unsupported(expr);
583 return NULL;
586 if (expr->getType()->isUnsignedIntegerType())
587 res = wrap(res, ast_context.getIntWidth(expr->getType()));
589 return res;
592 /* Extract an affine expression from a negation operation.
594 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
596 if (expr->getOpcode() == UO_Minus)
597 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
598 if (expr->getOpcode() == UO_LNot)
599 return extract_implicit_affine(expr);
601 unsupported(expr);
602 return NULL;
605 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
607 return extract_affine(expr->getSubExpr());
610 /* Extract an affine expression from some special function calls.
611 * In particular, we handle "min", "max", "ceild" and "floord".
612 * In case of the latter two, the second argument needs to be
613 * a (positive) integer constant.
615 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
617 FunctionDecl *fd;
618 string name;
619 isl_pw_aff *aff1, *aff2;
621 fd = expr->getDirectCallee();
622 if (!fd) {
623 unsupported(expr);
624 return NULL;
627 name = fd->getDeclName().getAsString();
628 if (!(expr->getNumArgs() == 2 && name == "min") &&
629 !(expr->getNumArgs() == 2 && name == "max") &&
630 !(expr->getNumArgs() == 2 && name == "floord") &&
631 !(expr->getNumArgs() == 2 && name == "ceild")) {
632 unsupported(expr);
633 return NULL;
636 if (name == "min" || name == "max") {
637 aff1 = extract_affine(expr->getArg(0));
638 aff2 = extract_affine(expr->getArg(1));
640 if (name == "min")
641 aff1 = isl_pw_aff_min(aff1, aff2);
642 else
643 aff1 = isl_pw_aff_max(aff1, aff2);
644 } else if (name == "floord" || name == "ceild") {
645 isl_int v;
646 Expr *arg2 = expr->getArg(1);
648 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
649 unsupported(expr);
650 return NULL;
652 aff1 = extract_affine(expr->getArg(0));
653 isl_int_init(v);
654 extract_int(cast<IntegerLiteral>(arg2), &v);
655 aff1 = isl_pw_aff_scale_down(aff1, v);
656 isl_int_clear(v);
657 if (name == "floord")
658 aff1 = isl_pw_aff_floor(aff1);
659 else
660 aff1 = isl_pw_aff_ceil(aff1);
661 } else {
662 unsupported(expr);
663 return NULL;
666 return aff1;
670 /* This method is called when we come across an access that is
671 * nested in what is supposed to be an affine expression.
672 * If nesting is allowed, we return a new parameter that corresponds
673 * to this nested access. Otherwise, we simply complain.
675 * The new parameter is resolved in resolve_nested.
677 isl_pw_aff *PetScan::nested_access(Expr *expr)
679 isl_id *id;
680 isl_space *dim;
681 isl_aff *aff;
682 isl_set *dom;
684 if (!nesting_enabled) {
685 unsupported(expr);
686 return NULL;
689 id = isl_id_alloc(ctx, NULL, expr);
690 dim = isl_space_params_alloc(ctx, 1);
692 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
694 dom = isl_set_universe(isl_space_copy(dim));
695 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
696 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
698 return isl_pw_aff_alloc(dom, aff);
701 /* Affine expressions are not supposed to contain array accesses,
702 * but if nesting is allowed, we return a parameter corresponding
703 * to the array access.
705 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
707 return nested_access(expr);
710 /* Extract an affine expression from a conditional operation.
712 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
714 isl_set *cond;
715 isl_pw_aff *lhs, *rhs;
717 cond = extract_condition(expr->getCond());
718 lhs = extract_affine(expr->getTrueExpr());
719 rhs = extract_affine(expr->getFalseExpr());
721 return isl_pw_aff_cond(cond, lhs, rhs);
724 /* Extract an affine expression, if possible, from "expr".
725 * Otherwise return NULL.
727 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
729 switch (expr->getStmtClass()) {
730 case Stmt::ImplicitCastExprClass:
731 return extract_affine(cast<ImplicitCastExpr>(expr));
732 case Stmt::IntegerLiteralClass:
733 return extract_affine(cast<IntegerLiteral>(expr));
734 case Stmt::DeclRefExprClass:
735 return extract_affine(cast<DeclRefExpr>(expr));
736 case Stmt::BinaryOperatorClass:
737 return extract_affine(cast<BinaryOperator>(expr));
738 case Stmt::UnaryOperatorClass:
739 return extract_affine(cast<UnaryOperator>(expr));
740 case Stmt::ParenExprClass:
741 return extract_affine(cast<ParenExpr>(expr));
742 case Stmt::CallExprClass:
743 return extract_affine(cast<CallExpr>(expr));
744 case Stmt::ArraySubscriptExprClass:
745 return extract_affine(cast<ArraySubscriptExpr>(expr));
746 case Stmt::ConditionalOperatorClass:
747 return extract_affine(cast<ConditionalOperator>(expr));
748 default:
749 unsupported(expr);
751 return NULL;
754 __isl_give isl_map *PetScan::extract_access(ImplicitCastExpr *expr)
756 return extract_access(expr->getSubExpr());
759 /* Return the depth of an array of the given type.
761 static int array_depth(const Type *type)
763 if (type->isPointerType())
764 return 1 + array_depth(type->getPointeeType().getTypePtr());
765 if (type->isArrayType()) {
766 const ArrayType *atype;
767 type = type->getCanonicalTypeInternal().getTypePtr();
768 atype = cast<ArrayType>(type);
769 return 1 + array_depth(atype->getElementType().getTypePtr());
771 return 0;
774 /* Return the element type of the given array type.
776 static QualType base_type(QualType qt)
778 const Type *type = qt.getTypePtr();
780 if (type->isPointerType())
781 return base_type(type->getPointeeType());
782 if (type->isArrayType()) {
783 const ArrayType *atype;
784 type = type->getCanonicalTypeInternal().getTypePtr();
785 atype = cast<ArrayType>(type);
786 return base_type(atype->getElementType());
788 return qt;
791 /* Extract an access relation from a reference to a variable.
792 * If the variable has name "A" and its type corresponds to an
793 * array of depth d, then the returned access relation is of the
794 * form
796 * { [] -> A[i_1,...,i_d] }
798 __isl_give isl_map *PetScan::extract_access(DeclRefExpr *expr)
800 ValueDecl *decl = expr->getDecl();
801 int depth = array_depth(decl->getType().getTypePtr());
802 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
803 isl_space *dim = isl_space_alloc(ctx, 0, 0, depth);
804 isl_map *access_rel;
806 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
808 access_rel = isl_map_universe(dim);
810 return access_rel;
813 /* Extract an access relation from an integer contant.
814 * If the value of the constant is "v", then the returned access relation
815 * is
817 * { [] -> [v] }
819 __isl_give isl_map *PetScan::extract_access(IntegerLiteral *expr)
821 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr)));
824 /* Try and extract an access relation from the given Expr.
825 * Return NULL if it doesn't work out.
827 __isl_give isl_map *PetScan::extract_access(Expr *expr)
829 switch (expr->getStmtClass()) {
830 case Stmt::ImplicitCastExprClass:
831 return extract_access(cast<ImplicitCastExpr>(expr));
832 case Stmt::DeclRefExprClass:
833 return extract_access(cast<DeclRefExpr>(expr));
834 case Stmt::ArraySubscriptExprClass:
835 return extract_access(cast<ArraySubscriptExpr>(expr));
836 default:
837 unsupported(expr);
839 return NULL;
842 /* Assign the affine expression "index" to the output dimension "pos" of "map"
843 * and return the result.
845 __isl_give isl_map *set_index(__isl_take isl_map *map, int pos,
846 __isl_take isl_pw_aff *index)
848 isl_map *index_map;
849 int len = isl_map_dim(map, isl_dim_out);
850 isl_id *id;
852 index_map = isl_map_from_range(isl_set_from_pw_aff(index));
853 index_map = isl_map_insert_dims(index_map, isl_dim_out, 0, pos);
854 index_map = isl_map_add_dims(index_map, isl_dim_out, len - pos - 1);
855 id = isl_map_get_tuple_id(map, isl_dim_out);
856 index_map = isl_map_set_tuple_id(index_map, isl_dim_out, id);
858 map = isl_map_intersect(map, index_map);
860 return map;
863 /* Extract an access relation from the given array subscript expression.
864 * If nesting is allowed in general, then we turn it on while
865 * examining the index expression.
867 * We first extract an access relation from the base.
868 * This will result in an access relation with a range that corresponds
869 * to the array being accessed and with earlier indices filled in already.
870 * We then extract the current index and fill that in as well.
871 * The position of the current index is based on the type of base.
872 * If base is the actual array variable, then the depth of this type
873 * will be the same as the depth of the array and we will fill in
874 * the first array index.
875 * Otherwise, the depth of the base type will be smaller and we will fill
876 * in a later index.
878 __isl_give isl_map *PetScan::extract_access(ArraySubscriptExpr *expr)
880 Expr *base = expr->getBase();
881 Expr *idx = expr->getIdx();
882 isl_pw_aff *index;
883 isl_map *base_access;
884 isl_map *access;
885 int depth = array_depth(base->getType().getTypePtr());
886 int pos;
887 bool save_nesting = nesting_enabled;
889 nesting_enabled = allow_nested;
891 base_access = extract_access(base);
892 index = extract_affine(idx);
894 nesting_enabled = save_nesting;
896 pos = isl_map_dim(base_access, isl_dim_out) - depth;
897 access = set_index(base_access, pos, index);
899 return access;
902 /* Check if "expr" calls function "minmax" with two arguments and if so
903 * make lhs and rhs refer to these two arguments.
905 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
907 CallExpr *call;
908 FunctionDecl *fd;
909 string name;
911 if (expr->getStmtClass() != Stmt::CallExprClass)
912 return false;
914 call = cast<CallExpr>(expr);
915 fd = call->getDirectCallee();
916 if (!fd)
917 return false;
919 if (call->getNumArgs() != 2)
920 return false;
922 name = fd->getDeclName().getAsString();
923 if (name != minmax)
924 return false;
926 lhs = call->getArg(0);
927 rhs = call->getArg(1);
929 return true;
932 /* Check if "expr" is of the form min(lhs, rhs) and if so make
933 * lhs and rhs refer to the two arguments.
935 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
937 return is_minmax(expr, "min", lhs, rhs);
940 /* Check if "expr" is of the form max(lhs, rhs) and if so make
941 * lhs and rhs refer to the two arguments.
943 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
945 return is_minmax(expr, "max", lhs, rhs);
948 /* Extract a set of values satisfying the comparison "LHS op RHS"
949 * "comp" is the original statement that "LHS op RHS" is derived from
950 * and is used for diagnostics.
952 * If the comparison is of the form
954 * a <= min(b,c)
956 * then the set is constructed as the intersection of the set corresponding
957 * to the comparisons
959 * a <= b and a <= c
961 * A similar optimization is performed for max(a,b) <= c.
962 * We do this because that will lead to simpler representations of the set.
963 * If isl is ever enhanced to explicitly deal with min and max expressions,
964 * this optimization can be removed.
966 __isl_give isl_set *PetScan::extract_comparison(BinaryOperatorKind op,
967 Expr *LHS, Expr *RHS, Stmt *comp)
969 isl_pw_aff *lhs;
970 isl_pw_aff *rhs;
971 isl_set *cond;
973 if (op == BO_GT)
974 return extract_comparison(BO_LT, RHS, LHS, comp);
975 if (op == BO_GE)
976 return extract_comparison(BO_LE, RHS, LHS, comp);
978 if (op == BO_LT || op == BO_LE) {
979 Expr *expr1, *expr2;
980 isl_set *set1, *set2;
981 if (is_min(RHS, expr1, expr2)) {
982 set1 = extract_comparison(op, LHS, expr1, comp);
983 set2 = extract_comparison(op, LHS, expr2, comp);
984 return isl_set_intersect(set1, set2);
986 if (is_max(LHS, expr1, expr2)) {
987 set1 = extract_comparison(op, expr1, RHS, comp);
988 set2 = extract_comparison(op, expr2, RHS, comp);
989 return isl_set_intersect(set1, set2);
993 lhs = extract_affine(LHS);
994 rhs = extract_affine(RHS);
996 switch (op) {
997 case BO_LT:
998 cond = isl_pw_aff_lt_set(lhs, rhs);
999 break;
1000 case BO_LE:
1001 cond = isl_pw_aff_le_set(lhs, rhs);
1002 break;
1003 case BO_EQ:
1004 cond = isl_pw_aff_eq_set(lhs, rhs);
1005 break;
1006 case BO_NE:
1007 cond = isl_pw_aff_ne_set(lhs, rhs);
1008 break;
1009 default:
1010 isl_pw_aff_free(lhs);
1011 isl_pw_aff_free(rhs);
1012 unsupported(comp);
1013 return NULL;
1016 cond = isl_set_coalesce(cond);
1018 return cond;
1021 __isl_give isl_set *PetScan::extract_comparison(BinaryOperator *comp)
1023 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1024 comp->getRHS(), comp);
1027 /* Extract a set of values satisfying the negation (logical not)
1028 * of a subexpression.
1030 __isl_give isl_set *PetScan::extract_boolean(UnaryOperator *op)
1032 isl_set *cond;
1034 cond = extract_condition(op->getSubExpr());
1036 return isl_set_complement(cond);
1039 /* Extract a set of values satisfying the union (logical or)
1040 * or intersection (logical and) of two subexpressions.
1042 __isl_give isl_set *PetScan::extract_boolean(BinaryOperator *comp)
1044 isl_set *lhs;
1045 isl_set *rhs;
1046 isl_set *cond;
1048 lhs = extract_condition(comp->getLHS());
1049 rhs = extract_condition(comp->getRHS());
1051 switch (comp->getOpcode()) {
1052 case BO_LAnd:
1053 cond = isl_set_intersect(lhs, rhs);
1054 break;
1055 case BO_LOr:
1056 cond = isl_set_union(lhs, rhs);
1057 break;
1058 default:
1059 isl_set_free(lhs);
1060 isl_set_free(rhs);
1061 unsupported(comp);
1062 return NULL;
1065 return cond;
1068 __isl_give isl_set *PetScan::extract_condition(UnaryOperator *expr)
1070 switch (expr->getOpcode()) {
1071 case UO_LNot:
1072 return extract_boolean(expr);
1073 default:
1074 unsupported(expr);
1075 return NULL;
1079 /* Extract a set of values satisfying the condition "expr != 0".
1081 __isl_give isl_set *PetScan::extract_implicit_condition(Expr *expr)
1083 return isl_pw_aff_non_zero_set(extract_affine(expr));
1086 /* Extract a set of values satisfying the condition expressed by "expr".
1088 * If the expression doesn't look like a condition, we assume it
1089 * is an affine expression and return the condition "expr != 0".
1091 __isl_give isl_set *PetScan::extract_condition(Expr *expr)
1093 BinaryOperator *comp;
1095 if (!expr)
1096 return isl_set_universe(isl_space_params_alloc(ctx, 0));
1098 if (expr->getStmtClass() == Stmt::ParenExprClass)
1099 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1101 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1102 return extract_condition(cast<UnaryOperator>(expr));
1104 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1105 return extract_implicit_condition(expr);
1107 comp = cast<BinaryOperator>(expr);
1108 switch (comp->getOpcode()) {
1109 case BO_LT:
1110 case BO_LE:
1111 case BO_GT:
1112 case BO_GE:
1113 case BO_EQ:
1114 case BO_NE:
1115 return extract_comparison(comp);
1116 case BO_LAnd:
1117 case BO_LOr:
1118 return extract_boolean(comp);
1119 default:
1120 return extract_implicit_condition(expr);
1124 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1126 switch (kind) {
1127 case UO_Minus:
1128 return pet_op_minus;
1129 default:
1130 return pet_op_last;
1134 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1136 switch (kind) {
1137 case BO_AddAssign:
1138 return pet_op_add_assign;
1139 case BO_SubAssign:
1140 return pet_op_sub_assign;
1141 case BO_MulAssign:
1142 return pet_op_mul_assign;
1143 case BO_DivAssign:
1144 return pet_op_div_assign;
1145 case BO_Assign:
1146 return pet_op_assign;
1147 case BO_Add:
1148 return pet_op_add;
1149 case BO_Sub:
1150 return pet_op_sub;
1151 case BO_Mul:
1152 return pet_op_mul;
1153 case BO_Div:
1154 return pet_op_div;
1155 case BO_EQ:
1156 return pet_op_eq;
1157 case BO_LE:
1158 return pet_op_le;
1159 case BO_LT:
1160 return pet_op_lt;
1161 case BO_GT:
1162 return pet_op_gt;
1163 default:
1164 return pet_op_last;
1168 /* Construct a pet_expr representing a unary operator expression.
1170 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1172 struct pet_expr *arg;
1173 enum pet_op_type op;
1175 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1176 if (op == pet_op_last) {
1177 unsupported(expr);
1178 return NULL;
1181 arg = extract_expr(expr->getSubExpr());
1183 return pet_expr_new_unary(ctx, op, arg);
1186 /* Mark the given access pet_expr as a write.
1187 * If a scalar is being accessed, then mark its value
1188 * as unknown in assigned_value.
1190 void PetScan::mark_write(struct pet_expr *access)
1192 isl_id *id;
1193 ValueDecl *decl;
1195 access->acc.write = 1;
1196 access->acc.read = 0;
1198 if (isl_map_dim(access->acc.access, isl_dim_out) != 0)
1199 return;
1201 id = isl_map_get_tuple_id(access->acc.access, isl_dim_out);
1202 decl = (ValueDecl *) isl_id_get_user(id);
1203 clear_assignment(assigned_value, decl);
1204 isl_id_free(id);
1207 /* Construct a pet_expr representing a binary operator expression.
1209 * If the top level operator is an assignment and the LHS is an access,
1210 * then we mark that access as a write. If the operator is a compound
1211 * assignment, the access is marked as both a read and a write.
1213 * If "expr" assigns something to a scalar variable, then we mark
1214 * the variable as having been assigned. If, furthermore, the expression
1215 * is affine, then keep track of this value in assigned_value
1216 * so that we can plug it in when we later come across the same variable.
1218 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1220 struct pet_expr *lhs, *rhs;
1221 enum pet_op_type op;
1223 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1224 if (op == pet_op_last) {
1225 unsupported(expr);
1226 return NULL;
1229 lhs = extract_expr(expr->getLHS());
1230 rhs = extract_expr(expr->getRHS());
1232 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1233 mark_write(lhs);
1234 if (expr->isCompoundAssignmentOp())
1235 lhs->acc.read = 1;
1238 if (expr->getOpcode() == BO_Assign &&
1239 lhs && lhs->type == pet_expr_access &&
1240 isl_map_dim(lhs->acc.access, isl_dim_out) == 0) {
1241 isl_id *id = isl_map_get_tuple_id(lhs->acc.access, isl_dim_out);
1242 ValueDecl *decl = (ValueDecl *) isl_id_get_user(id);
1243 Expr *rhs = expr->getRHS();
1244 isl_pw_aff *pa = try_extract_affine(rhs);
1245 clear_assignment(assigned_value, decl);
1246 if (pa) {
1247 assigned_value[decl] = pa;
1248 insert_expression(pa);
1250 isl_id_free(id);
1253 return pet_expr_new_binary(ctx, op, lhs, rhs);
1256 /* Construct a pet_expr representing a conditional operation.
1258 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1260 struct pet_expr *cond, *lhs, *rhs;
1262 cond = extract_expr(expr->getCond());
1263 lhs = extract_expr(expr->getTrueExpr());
1264 rhs = extract_expr(expr->getFalseExpr());
1266 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1269 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1271 return extract_expr(expr->getSubExpr());
1274 /* Construct a pet_expr representing a floating point value.
1276 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1278 return pet_expr_new_double(ctx, expr->getValueAsApproximateDouble());
1281 /* Extract an access relation from "expr" and then convert it into
1282 * a pet_expr.
1284 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1286 isl_map *access;
1287 struct pet_expr *pe;
1289 switch (expr->getStmtClass()) {
1290 case Stmt::ArraySubscriptExprClass:
1291 access = extract_access(cast<ArraySubscriptExpr>(expr));
1292 break;
1293 case Stmt::DeclRefExprClass:
1294 access = extract_access(cast<DeclRefExpr>(expr));
1295 break;
1296 case Stmt::IntegerLiteralClass:
1297 access = extract_access(cast<IntegerLiteral>(expr));
1298 break;
1299 default:
1300 unsupported(expr);
1301 return NULL;
1304 pe = pet_expr_from_access(access);
1306 return pe;
1309 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1311 return extract_expr(expr->getSubExpr());
1314 /* Construct a pet_expr representing a function call.
1316 * If we are passing along a pointer to an array element
1317 * or an entire row or even higher dimensional slice of an array,
1318 * then the function being called may write into the array.
1320 * We assume here that if the function is declared to take a pointer
1321 * to a const type, then the function will perform a read
1322 * and that otherwise, it will perform a write.
1324 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1326 struct pet_expr *res = NULL;
1327 FunctionDecl *fd;
1328 string name;
1330 fd = expr->getDirectCallee();
1331 if (!fd) {
1332 unsupported(expr);
1333 return NULL;
1336 name = fd->getDeclName().getAsString();
1337 res = pet_expr_new_call(ctx, name.c_str(), expr->getNumArgs());
1338 if (!res)
1339 return NULL;
1341 for (int i = 0; i < expr->getNumArgs(); ++i) {
1342 Expr *arg = expr->getArg(i);
1343 int is_addr = 0;
1344 pet_expr *main_arg;
1346 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
1347 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(arg);
1348 arg = ice->getSubExpr();
1350 if (arg->getStmtClass() == Stmt::UnaryOperatorClass) {
1351 UnaryOperator *op = cast<UnaryOperator>(arg);
1352 if (op->getOpcode() == UO_AddrOf) {
1353 is_addr = 1;
1354 arg = op->getSubExpr();
1357 res->args[i] = PetScan::extract_expr(arg);
1358 main_arg = res->args[i];
1359 if (is_addr)
1360 res->args[i] = pet_expr_new_unary(ctx,
1361 pet_op_address_of, res->args[i]);
1362 if (!res->args[i])
1363 goto error;
1364 if (arg->getStmtClass() == Stmt::ArraySubscriptExprClass &&
1365 array_depth(arg->getType().getTypePtr()) > 0)
1366 is_addr = 1;
1367 if (is_addr && main_arg->type == pet_expr_access) {
1368 ParmVarDecl *parm;
1369 if (!fd->hasPrototype()) {
1370 unsupported(expr, "prototype required");
1371 goto error;
1373 parm = fd->getParamDecl(i);
1374 if (!const_base(parm->getType()))
1375 mark_write(main_arg);
1379 return res;
1380 error:
1381 pet_expr_free(res);
1382 return NULL;
1385 /* Try and onstruct a pet_expr representing "expr".
1387 struct pet_expr *PetScan::extract_expr(Expr *expr)
1389 switch (expr->getStmtClass()) {
1390 case Stmt::UnaryOperatorClass:
1391 return extract_expr(cast<UnaryOperator>(expr));
1392 case Stmt::CompoundAssignOperatorClass:
1393 case Stmt::BinaryOperatorClass:
1394 return extract_expr(cast<BinaryOperator>(expr));
1395 case Stmt::ImplicitCastExprClass:
1396 return extract_expr(cast<ImplicitCastExpr>(expr));
1397 case Stmt::ArraySubscriptExprClass:
1398 case Stmt::DeclRefExprClass:
1399 case Stmt::IntegerLiteralClass:
1400 return extract_access_expr(expr);
1401 case Stmt::FloatingLiteralClass:
1402 return extract_expr(cast<FloatingLiteral>(expr));
1403 case Stmt::ParenExprClass:
1404 return extract_expr(cast<ParenExpr>(expr));
1405 case Stmt::ConditionalOperatorClass:
1406 return extract_expr(cast<ConditionalOperator>(expr));
1407 case Stmt::CallExprClass:
1408 return extract_expr(cast<CallExpr>(expr));
1409 default:
1410 unsupported(expr);
1412 return NULL;
1415 /* Check if the given initialization statement is an assignment.
1416 * If so, return that assignment. Otherwise return NULL.
1418 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1420 BinaryOperator *ass;
1422 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1423 return NULL;
1425 ass = cast<BinaryOperator>(init);
1426 if (ass->getOpcode() != BO_Assign)
1427 return NULL;
1429 return ass;
1432 /* Check if the given initialization statement is a declaration
1433 * of a single variable.
1434 * If so, return that declaration. Otherwise return NULL.
1436 Decl *PetScan::initialization_declaration(Stmt *init)
1438 DeclStmt *decl;
1440 if (init->getStmtClass() != Stmt::DeclStmtClass)
1441 return NULL;
1443 decl = cast<DeclStmt>(init);
1445 if (!decl->isSingleDecl())
1446 return NULL;
1448 return decl->getSingleDecl();
1451 /* Given the assignment operator in the initialization of a for loop,
1452 * extract the induction variable, i.e., the (integer)variable being
1453 * assigned.
1455 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1457 Expr *lhs;
1458 DeclRefExpr *ref;
1459 ValueDecl *decl;
1460 const Type *type;
1462 lhs = init->getLHS();
1463 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1464 unsupported(init);
1465 return NULL;
1468 ref = cast<DeclRefExpr>(lhs);
1469 decl = ref->getDecl();
1470 type = decl->getType().getTypePtr();
1472 if (!type->isIntegerType()) {
1473 unsupported(lhs);
1474 return NULL;
1477 return decl;
1480 /* Given the initialization statement of a for loop and the single
1481 * declaration in this initialization statement,
1482 * extract the induction variable, i.e., the (integer) variable being
1483 * declared.
1485 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1487 VarDecl *vd;
1489 vd = cast<VarDecl>(decl);
1491 const QualType type = vd->getType();
1492 if (!type->isIntegerType()) {
1493 unsupported(init);
1494 return NULL;
1497 if (!vd->getInit()) {
1498 unsupported(init);
1499 return NULL;
1502 return vd;
1505 /* Check that op is of the form iv++ or iv--.
1506 * "inc" is accordingly set to 1 or -1.
1508 bool PetScan::check_unary_increment(UnaryOperator *op, clang::ValueDecl *iv,
1509 isl_int &inc)
1511 Expr *sub;
1512 DeclRefExpr *ref;
1514 if (!op->isIncrementDecrementOp()) {
1515 unsupported(op);
1516 return false;
1519 if (op->isIncrementOp())
1520 isl_int_set_si(inc, 1);
1521 else
1522 isl_int_set_si(inc, -1);
1524 sub = op->getSubExpr();
1525 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1526 unsupported(op);
1527 return false;
1530 ref = cast<DeclRefExpr>(sub);
1531 if (ref->getDecl() != iv) {
1532 unsupported(op);
1533 return false;
1536 return true;
1539 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1540 * has a single constant expression on a universe domain, then
1541 * put this constant in *user.
1543 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
1544 void *user)
1546 isl_int *inc = (isl_int *)user;
1547 int res = 0;
1549 if (!isl_set_plain_is_universe(set) || !isl_aff_is_cst(aff))
1550 res = -1;
1551 else
1552 isl_aff_get_constant(aff, inc);
1554 isl_set_free(set);
1555 isl_aff_free(aff);
1557 return res;
1560 /* Check if op is of the form
1562 * iv = iv + inc
1564 * with inc a constant and set "inc" accordingly.
1566 * We extract an affine expression from the RHS and the subtract iv.
1567 * The result should be a constant.
1569 bool PetScan::check_binary_increment(BinaryOperator *op, clang::ValueDecl *iv,
1570 isl_int &inc)
1572 Expr *lhs;
1573 DeclRefExpr *ref;
1574 isl_id *id;
1575 isl_space *dim;
1576 isl_aff *aff;
1577 isl_pw_aff *val;
1579 if (op->getOpcode() != BO_Assign) {
1580 unsupported(op);
1581 return false;
1584 lhs = op->getLHS();
1585 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1586 unsupported(op);
1587 return false;
1590 ref = cast<DeclRefExpr>(lhs);
1591 if (ref->getDecl() != iv) {
1592 unsupported(op);
1593 return false;
1596 val = extract_affine(op->getRHS());
1598 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1600 dim = isl_space_params_alloc(ctx, 1);
1601 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1602 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1603 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1605 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
1607 if (isl_pw_aff_foreach_piece(val, &extract_cst, &inc) < 0) {
1608 isl_pw_aff_free(val);
1609 unsupported(op);
1610 return false;
1613 isl_pw_aff_free(val);
1615 return true;
1618 /* Check that op is of the form iv += cst or iv -= cst.
1619 * "inc" is set to cst or -cst accordingly.
1621 bool PetScan::check_compound_increment(CompoundAssignOperator *op,
1622 clang::ValueDecl *iv, isl_int &inc)
1624 Expr *lhs, *rhs;
1625 DeclRefExpr *ref;
1626 bool neg = false;
1628 BinaryOperatorKind opcode;
1630 opcode = op->getOpcode();
1631 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1632 unsupported(op);
1633 return false;
1635 if (opcode == BO_SubAssign)
1636 neg = true;
1638 lhs = op->getLHS();
1639 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1640 unsupported(op);
1641 return false;
1644 ref = cast<DeclRefExpr>(lhs);
1645 if (ref->getDecl() != iv) {
1646 unsupported(op);
1647 return false;
1650 rhs = op->getRHS();
1652 if (rhs->getStmtClass() == Stmt::UnaryOperatorClass) {
1653 UnaryOperator *op = cast<UnaryOperator>(rhs);
1654 if (op->getOpcode() != UO_Minus) {
1655 unsupported(op);
1656 return false;
1659 neg = !neg;
1661 rhs = op->getSubExpr();
1664 if (rhs->getStmtClass() != Stmt::IntegerLiteralClass) {
1665 unsupported(op);
1666 return false;
1669 extract_int(cast<IntegerLiteral>(rhs), &inc);
1670 if (neg)
1671 isl_int_neg(inc, inc);
1673 return true;
1676 /* Check that the increment of the given for loop increments
1677 * (or decrements) the induction variable "iv".
1678 * "up" is set to true if the induction variable is incremented.
1680 bool PetScan::check_increment(ForStmt *stmt, ValueDecl *iv, isl_int &v)
1682 Stmt *inc = stmt->getInc();
1684 if (!inc) {
1685 unsupported(stmt);
1686 return false;
1689 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1690 return check_unary_increment(cast<UnaryOperator>(inc), iv, v);
1691 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1692 return check_compound_increment(
1693 cast<CompoundAssignOperator>(inc), iv, v);
1694 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1695 return check_binary_increment(cast<BinaryOperator>(inc), iv, v);
1697 unsupported(inc);
1698 return false;
1701 /* Embed the given iteration domain in an extra outer loop
1702 * with induction variable "var".
1703 * If this variable appeared as a parameter in the constraints,
1704 * it is replaced by the new outermost dimension.
1706 static __isl_give isl_set *embed(__isl_take isl_set *set,
1707 __isl_take isl_id *var)
1709 int pos;
1711 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
1712 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
1713 if (pos >= 0) {
1714 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
1715 set = isl_set_project_out(set, isl_dim_param, pos, 1);
1718 isl_id_free(var);
1719 return set;
1722 /* Construct a pet_scop for an infinite loop around the given body.
1724 * We extract a pet_scop for the body and then embed it in a loop with
1725 * iteration domain
1727 * { [t] : t >= 0 }
1729 * and schedule
1731 * { [t] -> [t] }
1733 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
1735 isl_id *id;
1736 isl_space *dim;
1737 isl_set *domain;
1738 isl_map *sched;
1739 struct pet_scop *scop;
1741 scop = extract(body);
1742 if (!scop)
1743 return NULL;
1745 id = isl_id_alloc(ctx, "t", NULL);
1746 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
1747 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
1748 dim = isl_space_from_domain(isl_set_get_space(domain));
1749 dim = isl_space_add_dims(dim, isl_dim_out, 1);
1750 sched = isl_map_universe(dim);
1751 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
1752 scop = pet_scop_embed(scop, domain, sched, id);
1754 return scop;
1757 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1759 * for (;;)
1760 * body
1763 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
1765 return extract_infinite_loop(stmt->getBody());
1768 /* Check if the while loop is of the form
1770 * while (1)
1771 * body
1773 * If so, construct a scop for an infinite loop around body.
1774 * Otherwise, fail.
1776 struct pet_scop *PetScan::extract(WhileStmt *stmt)
1778 Expr *cond;
1779 isl_set *set;
1780 int is_universe;
1782 cond = stmt->getCond();
1783 if (!cond) {
1784 unsupported(stmt);
1785 return NULL;
1788 set = extract_condition(cond);
1789 is_universe = isl_set_plain_is_universe(set);
1790 isl_set_free(set);
1792 if (!is_universe) {
1793 unsupported(stmt);
1794 return NULL;
1797 return extract_infinite_loop(stmt->getBody());
1800 /* Check whether "cond" expresses a simple loop bound
1801 * on the only set dimension.
1802 * In particular, if "up" is set then "cond" should contain only
1803 * upper bounds on the set dimension.
1804 * Otherwise, it should contain only lower bounds.
1806 static bool is_simple_bound(__isl_keep isl_set *cond, isl_int inc)
1808 if (isl_int_is_pos(inc))
1809 return !isl_set_dim_has_lower_bound(cond, isl_dim_set, 0);
1810 else
1811 return !isl_set_dim_has_upper_bound(cond, isl_dim_set, 0);
1814 /* Extend a condition on a given iteration of a loop to one that
1815 * imposes the same condition on all previous iterations.
1816 * "domain" expresses the lower [upper] bound on the iterations
1817 * when inc is positive [negative].
1819 * In particular, we construct the condition (when inc is positive)
1821 * forall i' : (domain(i') and i' <= i) => cond(i')
1823 * which is equivalent to
1825 * not exists i' : domain(i') and i' <= i and not cond(i')
1827 * We construct this set by negating cond, applying a map
1829 * { [i'] -> [i] : domain(i') and i' <= i }
1831 * and then negating the result again.
1833 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
1834 __isl_take isl_set *domain, isl_int inc)
1836 isl_map *previous_to_this;
1838 if (isl_int_is_pos(inc))
1839 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
1840 else
1841 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
1843 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
1845 cond = isl_set_complement(cond);
1846 cond = isl_set_apply(cond, previous_to_this);
1847 cond = isl_set_complement(cond);
1849 return cond;
1852 /* Construct a domain of the form
1854 * [id] -> { [] : exists a: id = init + a * inc and a >= 0 }
1856 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
1857 __isl_take isl_pw_aff *init, isl_int inc)
1859 isl_aff *aff;
1860 isl_space *dim;
1861 isl_set *set;
1863 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
1864 dim = isl_pw_aff_get_domain_space(init);
1865 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1866 aff = isl_aff_add_coefficient(aff, isl_dim_in, 0, inc);
1867 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
1869 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
1870 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1871 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1872 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1874 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
1876 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
1878 return isl_set_project_out(set, isl_dim_set, 0, 1);
1881 static unsigned get_type_size(ValueDecl *decl)
1883 return decl->getASTContext().getIntWidth(decl->getType());
1886 /* Assuming "cond" represents a simple bound on a loop where the loop
1887 * iterator "iv" is incremented (or decremented) by one, check if wrapping
1888 * is possible.
1890 * Under the given assumptions, wrapping is only possible if "cond" allows
1891 * for the last value before wrapping, i.e., 2^width - 1 in case of an
1892 * increasing iterator and 0 in case of a decreasing iterator.
1894 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv, isl_int inc)
1896 bool cw;
1897 isl_int limit;
1898 isl_set *test;
1900 test = isl_set_copy(cond);
1902 isl_int_init(limit);
1903 if (isl_int_is_neg(inc))
1904 isl_int_set_si(limit, 0);
1905 else {
1906 isl_int_set_si(limit, 1);
1907 isl_int_mul_2exp(limit, limit, get_type_size(iv));
1908 isl_int_sub_ui(limit, limit, 1);
1911 test = isl_set_fix(cond, isl_dim_set, 0, limit);
1912 cw = !isl_set_is_empty(test);
1913 isl_set_free(test);
1915 isl_int_clear(limit);
1917 return cw;
1920 /* Given a one-dimensional space, construct the following mapping on this
1921 * space
1923 * { [v] -> [v mod 2^width] }
1925 * where width is the number of bits used to represent the values
1926 * of the unsigned variable "iv".
1928 static __isl_give isl_map *compute_wrapping(__isl_take isl_space *dim,
1929 ValueDecl *iv)
1931 isl_int mod;
1932 isl_aff *aff;
1933 isl_map *map;
1935 isl_int_init(mod);
1936 isl_int_set_si(mod, 1);
1937 isl_int_mul_2exp(mod, mod, get_type_size(iv));
1939 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1940 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1941 aff = isl_aff_mod(aff, mod);
1943 isl_int_clear(mod);
1945 return isl_map_from_basic_map(isl_basic_map_from_aff(aff));
1946 map = isl_map_reverse(map);
1949 /* Construct a pet_scop for a for statement.
1950 * The for loop is required to be of the form
1952 * for (i = init; condition; ++i)
1954 * or
1956 * for (i = init; condition; --i)
1958 * The initialization of the for loop should either be an assignment
1959 * to an integer variable, or a declaration of such a variable with
1960 * initialization.
1962 * The condition is allowed to contain nested accesses, provided
1963 * they are not being written to inside the body of the loop.
1965 * We extract a pet_scop for the body and then embed it in a loop with
1966 * iteration domain and schedule
1968 * { [i] : i >= init and condition' }
1969 * { [i] -> [i] }
1971 * or
1973 * { [i] : i <= init and condition' }
1974 * { [i] -> [-i] }
1976 * Where condition' is equal to condition if the latter is
1977 * a simple upper [lower] bound and a condition that is extended
1978 * to apply to all previous iterations otherwise.
1980 * If the stride of the loop is not 1, then "i >= init" is replaced by
1982 * (exists a: i = init + stride * a and a >= 0)
1984 * If the loop iterator i is unsigned, then wrapping may occur.
1985 * During the computation, we work with a virtual iterator that
1986 * does not wrap. However, the condition in the code applies
1987 * to the wrapped value, so we need to change condition(i)
1988 * into condition([i % 2^width]).
1989 * After computing the virtual domain and schedule, we apply
1990 * the function { [v] -> [v % 2^width] } to the domain and the domain
1991 * of the schedule. In order not to lose any information, we also
1992 * need to intersect the domain of the schedule with the virtual domain
1993 * first, since some iterations in the wrapped domain may be scheduled
1994 * several times, typically an infinite number of times.
1995 * Note that there is no need to perform this final wrapping
1996 * if the loop condition (after wrapping) is simple.
1998 * Wrapping on unsigned iterators can be avoided entirely if
1999 * loop condition is simple, the loop iterator is incremented
2000 * [decremented] by one and the last value before wrapping cannot
2001 * possibly satisfy the loop condition.
2003 * Before extracting a pet_scop from the body we remove all
2004 * assignments in assigned_value to variables that are assigned
2005 * somewhere in the body of the loop.
2007 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2009 BinaryOperator *ass;
2010 Decl *decl;
2011 Stmt *init;
2012 Expr *lhs, *rhs;
2013 ValueDecl *iv;
2014 isl_space *dim;
2015 isl_set *domain;
2016 isl_map *sched;
2017 isl_set *cond = NULL;
2018 isl_id *id;
2019 struct pet_scop *scop;
2020 assigned_value_cache cache(assigned_value);
2021 isl_int inc;
2022 bool is_one;
2023 bool is_unsigned;
2024 bool is_simple;
2025 isl_map *wrap = NULL;
2027 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2028 return extract_infinite_for(stmt);
2030 init = stmt->getInit();
2031 if (!init) {
2032 unsupported(stmt);
2033 return NULL;
2035 if ((ass = initialization_assignment(init)) != NULL) {
2036 iv = extract_induction_variable(ass);
2037 if (!iv)
2038 return NULL;
2039 lhs = ass->getLHS();
2040 rhs = ass->getRHS();
2041 } else if ((decl = initialization_declaration(init)) != NULL) {
2042 VarDecl *var = extract_induction_variable(init, decl);
2043 if (!var)
2044 return NULL;
2045 iv = var;
2046 rhs = var->getInit();
2047 lhs = create_DeclRefExpr(var);
2048 } else {
2049 unsupported(stmt->getInit());
2050 return NULL;
2053 isl_int_init(inc);
2054 if (!check_increment(stmt, iv, inc)) {
2055 isl_int_clear(inc);
2056 return NULL;
2059 is_unsigned = iv->getType()->isUnsignedIntegerType();
2061 assigned_value.erase(iv);
2062 clear_assignments clear(assigned_value);
2063 clear.TraverseStmt(stmt->getBody());
2065 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2067 is_one = isl_int_is_one(inc) || isl_int_is_negone(inc);
2068 if (is_one)
2069 domain = extract_comparison(isl_int_is_pos(inc) ? BO_GE : BO_LE,
2070 lhs, rhs, init);
2071 else {
2072 isl_pw_aff *lb = extract_affine(rhs);
2073 domain = strided_domain(isl_id_copy(id), lb, inc);
2076 scop = extract(stmt->getBody());
2078 cond = try_extract_nested_condition(stmt->getCond());
2079 if (cond && !is_nested_allowed(cond, scop)) {
2080 isl_set_free(cond);
2081 cond = NULL;
2084 if (!cond)
2085 cond = extract_condition(stmt->getCond());
2086 cond = embed(cond, isl_id_copy(id));
2087 domain = embed(domain, isl_id_copy(id));
2088 is_simple = is_simple_bound(cond, inc);
2089 if (is_unsigned &&
2090 (!is_simple || !is_one || can_wrap(cond, iv, inc))) {
2091 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2092 cond = isl_set_apply(cond, isl_map_reverse(isl_map_copy(wrap)));
2093 is_simple = is_simple && is_simple_bound(cond, inc);
2095 if (!is_simple)
2096 cond = valid_for_each_iteration(cond,
2097 isl_set_copy(domain), inc);
2098 domain = isl_set_intersect(domain, cond);
2099 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2100 dim = isl_space_from_domain(isl_set_get_space(domain));
2101 dim = isl_space_add_dims(dim, isl_dim_out, 1);
2102 sched = isl_map_universe(dim);
2103 if (isl_int_is_pos(inc))
2104 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
2105 else
2106 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
2108 if (is_unsigned && !is_simple) {
2109 wrap = isl_map_set_dim_id(wrap,
2110 isl_dim_out, 0, isl_id_copy(id));
2111 sched = isl_map_intersect_domain(sched, isl_set_copy(domain));
2112 domain = isl_set_apply(domain, isl_map_copy(wrap));
2113 sched = isl_map_apply_domain(sched, wrap);
2114 } else
2115 isl_map_free(wrap);
2117 scop = pet_scop_embed(scop, domain, sched, id);
2118 scop = resolve_nested(scop);
2119 clear_assignment(assigned_value, iv);
2121 isl_int_clear(inc);
2122 return scop;
2125 struct pet_scop *PetScan::extract(CompoundStmt *stmt)
2127 return extract(stmt->children());
2130 /* Does "id" refer to a nested access?
2132 static bool is_nested_parameter(__isl_keep isl_id *id)
2134 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2137 /* Does parameter "pos" of "space" refer to a nested access?
2139 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2141 bool nested;
2142 isl_id *id;
2144 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2145 nested = is_nested_parameter(id);
2146 isl_id_free(id);
2148 return nested;
2151 /* Does parameter "pos" of "map" refer to a nested access?
2153 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
2155 bool nested;
2156 isl_id *id;
2158 id = isl_map_get_dim_id(map, isl_dim_param, pos);
2159 nested = is_nested_parameter(id);
2160 isl_id_free(id);
2162 return nested;
2165 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2167 static int n_nested_parameter(__isl_keep isl_space *space)
2169 int n = 0;
2170 int nparam;
2172 nparam = isl_space_dim(space, isl_dim_param);
2173 for (int i = 0; i < nparam; ++i)
2174 if (is_nested_parameter(space, i))
2175 ++n;
2177 return n;
2180 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2182 static int n_nested_parameter(__isl_keep isl_map *map)
2184 isl_space *space;
2185 int n;
2187 space = isl_map_get_space(map);
2188 n = n_nested_parameter(space);
2189 isl_space_free(space);
2191 return n;
2194 /* For each nested access parameter in "space",
2195 * construct a corresponding pet_expr, place it in args and
2196 * record its position in "param2pos".
2197 * "n_arg" is the number of elements that are already in args.
2198 * The position recorded in "param2pos" takes this number into account.
2199 * If the pet_expr corresponding to a parameter is identical to
2200 * the pet_expr corresponding to an earlier parameter, then these two
2201 * parameters are made to refer to the same element in args.
2203 * Return the final number of elements in args or -1 if an error has occurred.
2205 int PetScan::extract_nested(__isl_keep isl_space *space,
2206 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
2208 int nparam;
2210 nparam = isl_space_dim(space, isl_dim_param);
2211 for (int i = 0; i < nparam; ++i) {
2212 int j;
2213 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2214 Expr *nested;
2216 if (!is_nested_parameter(id)) {
2217 isl_id_free(id);
2218 continue;
2221 nested = (Expr *) isl_id_get_user(id);
2222 args[n_arg] = extract_expr(nested);
2223 if (!args[n_arg])
2224 return -1;
2226 for (j = 0; j < n_arg; ++j)
2227 if (pet_expr_is_equal(args[j], args[n_arg]))
2228 break;
2230 if (j < n_arg) {
2231 pet_expr_free(args[n_arg]);
2232 args[n_arg] = NULL;
2233 param2pos[i] = j;
2234 } else
2235 param2pos[i] = n_arg++;
2237 isl_id_free(id);
2240 return n_arg;
2243 /* For each nested access parameter in the access relations in "expr",
2244 * construct a corresponding pet_expr, place it in expr->args and
2245 * record its position in "param2pos".
2246 * n is the number of nested access parameters.
2248 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
2249 std::map<int,int> &param2pos)
2251 isl_space *space;
2253 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
2254 expr->n_arg = n;
2255 if (!expr->args)
2256 goto error;
2258 space = isl_map_get_space(expr->acc.access);
2259 n = extract_nested(space, 0, expr->args, param2pos);
2260 isl_space_free(space);
2262 if (n < 0)
2263 goto error;
2265 expr->n_arg = n;
2266 return expr;
2267 error:
2268 pet_expr_free(expr);
2269 return NULL;
2272 /* Look for parameters in any access relation in "expr" that
2273 * refer to nested accesses. In particular, these are
2274 * parameters with no name.
2276 * If there are any such parameters, then the domain of the access
2277 * relation, which is still [] at this point, is replaced by
2278 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2279 * (after identifying identical nested accesses).
2280 * The parameters are then equated to the corresponding t dimensions
2281 * and subsequently projected out.
2282 * param2pos maps the position of the parameter to the position
2283 * of the corresponding t dimension.
2285 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
2287 int n;
2288 int nparam;
2289 int n_in;
2290 isl_space *dim;
2291 isl_map *map;
2292 std::map<int,int> param2pos;
2294 if (!expr)
2295 return expr;
2297 for (int i = 0; i < expr->n_arg; ++i) {
2298 expr->args[i] = resolve_nested(expr->args[i]);
2299 if (!expr->args[i]) {
2300 pet_expr_free(expr);
2301 return NULL;
2305 if (expr->type != pet_expr_access)
2306 return expr;
2308 n = n_nested_parameter(expr->acc.access);
2309 if (n == 0)
2310 return expr;
2312 expr = extract_nested(expr, n, param2pos);
2313 if (!expr)
2314 return NULL;
2316 n = expr->n_arg;
2317 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
2318 n_in = isl_map_dim(expr->acc.access, isl_dim_in);
2319 dim = isl_map_get_space(expr->acc.access);
2320 dim = isl_space_domain(dim);
2321 dim = isl_space_from_domain(dim);
2322 dim = isl_space_add_dims(dim, isl_dim_out, n);
2323 map = isl_map_universe(dim);
2324 map = isl_map_domain_map(map);
2325 map = isl_map_reverse(map);
2326 expr->acc.access = isl_map_apply_domain(expr->acc.access, map);
2328 for (int i = nparam - 1; i >= 0; --i) {
2329 isl_id *id = isl_map_get_dim_id(expr->acc.access,
2330 isl_dim_param, i);
2331 if (!is_nested_parameter(id)) {
2332 isl_id_free(id);
2333 continue;
2336 expr->acc.access = isl_map_equate(expr->acc.access,
2337 isl_dim_param, i, isl_dim_in,
2338 n_in + param2pos[i]);
2339 expr->acc.access = isl_map_project_out(expr->acc.access,
2340 isl_dim_param, i, 1);
2342 isl_id_free(id);
2345 return expr;
2346 error:
2347 pet_expr_free(expr);
2348 return NULL;
2351 /* Convert a top-level pet_expr to a pet_scop with one statement.
2352 * This mainly involves resolving nested expression parameters
2353 * and setting the name of the iteration space.
2354 * The name is given by "label" if it is non-NULL. Otherwise,
2355 * it is of the form S_<n_stmt>.
2357 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
2358 __isl_take isl_id *label)
2360 struct pet_stmt *ps;
2361 SourceLocation loc = stmt->getLocStart();
2362 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2364 expr = resolve_nested(expr);
2365 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
2366 return pet_scop_from_pet_stmt(ctx, ps);
2369 /* Check if we can extract an affine expression from "expr".
2370 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
2371 * We turn on autodetection so that we won't generate any warnings
2372 * and turn off nesting, so that we won't accept any non-affine constructs.
2374 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
2376 isl_pw_aff *pwaff;
2377 int save_autodetect = autodetect;
2378 bool save_nesting = nesting_enabled;
2380 autodetect = 1;
2381 nesting_enabled = false;
2383 pwaff = extract_affine(expr);
2385 autodetect = save_autodetect;
2386 nesting_enabled = save_nesting;
2388 return pwaff;
2391 /* Check whether "expr" is an affine expression.
2393 bool PetScan::is_affine(Expr *expr)
2395 isl_pw_aff *pwaff;
2397 pwaff = try_extract_affine(expr);
2398 isl_pw_aff_free(pwaff);
2400 return pwaff != NULL;
2403 /* Check whether "expr" is an affine constraint.
2404 * We turn on autodetection so that we won't generate any warnings
2405 * and turn off nesting, so that we won't accept any non-affine constructs.
2407 bool PetScan::is_affine_condition(Expr *expr)
2409 isl_set *set;
2410 int save_autodetect = autodetect;
2411 bool save_nesting = nesting_enabled;
2413 autodetect = 1;
2414 nesting_enabled = false;
2416 set = extract_condition(expr);
2417 isl_set_free(set);
2419 autodetect = save_autodetect;
2420 nesting_enabled = save_nesting;
2422 return set != NULL;
2425 /* Check if we can extract a condition from "expr".
2426 * Return the condition as an isl_set if we can and NULL otherwise.
2427 * If allow_nested is set, then the condition may involve parameters
2428 * corresponding to nested accesses.
2429 * We turn on autodetection so that we won't generate any warnings.
2431 __isl_give isl_set *PetScan::try_extract_nested_condition(Expr *expr)
2433 isl_set *set;
2434 int save_autodetect = autodetect;
2435 bool save_nesting = nesting_enabled;
2437 autodetect = 1;
2438 nesting_enabled = allow_nested;
2439 set = extract_condition(expr);
2441 autodetect = save_autodetect;
2442 nesting_enabled = save_nesting;
2444 return set;
2447 /* If the top-level expression of "stmt" is an assignment, then
2448 * return that assignment as a BinaryOperator.
2449 * Otherwise return NULL.
2451 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
2453 BinaryOperator *ass;
2455 if (!stmt)
2456 return NULL;
2457 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
2458 return NULL;
2460 ass = cast<BinaryOperator>(stmt);
2461 if(ass->getOpcode() != BO_Assign)
2462 return NULL;
2464 return ass;
2467 /* Check if the given if statement is a conditional assignement
2468 * with a non-affine condition. If so, construct a pet_scop
2469 * corresponding to this conditional assignment. Otherwise return NULL.
2471 * In particular we check if "stmt" is of the form
2473 * if (condition)
2474 * a = f(...);
2475 * else
2476 * a = g(...);
2478 * where a is some array or scalar access.
2479 * The constructed pet_scop then corresponds to the expression
2481 * a = condition ? f(...) : g(...)
2483 * All access relations in f(...) are intersected with condition
2484 * while all access relation in g(...) are intersected with the complement.
2486 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
2488 BinaryOperator *ass_then, *ass_else;
2489 isl_map *write_then, *write_else;
2490 isl_set *cond, *comp;
2491 isl_map *map, *map_true, *map_false;
2492 int equal;
2493 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
2494 bool save_nesting = nesting_enabled;
2496 ass_then = top_assignment_or_null(stmt->getThen());
2497 ass_else = top_assignment_or_null(stmt->getElse());
2499 if (!ass_then || !ass_else)
2500 return NULL;
2502 if (is_affine_condition(stmt->getCond()))
2503 return NULL;
2505 write_then = extract_access(ass_then->getLHS());
2506 write_else = extract_access(ass_else->getLHS());
2508 equal = isl_map_is_equal(write_then, write_else);
2509 isl_map_free(write_else);
2510 if (equal < 0 || !equal) {
2511 isl_map_free(write_then);
2512 return NULL;
2515 nesting_enabled = allow_nested;
2516 cond = extract_condition(stmt->getCond());
2517 nesting_enabled = save_nesting;
2518 comp = isl_set_complement(isl_set_copy(cond));
2519 map_true = isl_map_from_domain(isl_set_from_params(isl_set_copy(cond)));
2520 map_true = isl_map_add_dims(map_true, isl_dim_out, 1);
2521 map_true = isl_map_fix_si(map_true, isl_dim_out, 0, 1);
2522 map_false = isl_map_from_domain(isl_set_from_params(isl_set_copy(comp)));
2523 map_false = isl_map_add_dims(map_false, isl_dim_out, 1);
2524 map_false = isl_map_fix_si(map_false, isl_dim_out, 0, 0);
2525 map = isl_map_union_disjoint(map_true, map_false);
2527 pe_cond = pet_expr_from_access(map);
2529 pe_then = extract_expr(ass_then->getRHS());
2530 pe_then = pet_expr_restrict(pe_then, cond);
2531 pe_else = extract_expr(ass_else->getRHS());
2532 pe_else = pet_expr_restrict(pe_else, comp);
2534 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
2535 pe_write = pet_expr_from_access(write_then);
2536 if (pe_write) {
2537 pe_write->acc.write = 1;
2538 pe_write->acc.read = 0;
2540 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
2541 return extract(stmt, pe);
2544 /* Create an access to a virtual array representing the result
2545 * of a condition.
2546 * Unlike other accessed data, the id of the array is NULL as
2547 * there is no ValueDecl in the program corresponding to the virtual
2548 * array.
2549 * The array starts out as a scalar, but grows along with the
2550 * statement writing to the array in pet_scop_embed.
2552 static __isl_give isl_map *create_test_access(isl_ctx *ctx, int test_nr)
2554 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2555 isl_id *id;
2556 char name[50];
2558 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2559 id = isl_id_alloc(ctx, name, NULL);
2560 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2561 return isl_map_universe(dim);
2564 /* Create a pet_scop with a single statement evaluating "cond"
2565 * and writing the result to a virtual scalar, as expressed by
2566 * "access".
2568 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond,
2569 __isl_take isl_map *access)
2571 struct pet_expr *expr, *write;
2572 struct pet_stmt *ps;
2573 SourceLocation loc = cond->getLocStart();
2574 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2576 write = pet_expr_from_access(access);
2577 if (write) {
2578 write->acc.write = 1;
2579 write->acc.read = 0;
2581 expr = extract_expr(cond);
2582 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
2583 ps = pet_stmt_from_pet_expr(ctx, line, NULL, n_stmt++, expr);
2584 return pet_scop_from_pet_stmt(ctx, ps);
2587 /* Add an array with the given extent ("access") to the list
2588 * of arrays in "scop" and return the extended pet_scop.
2589 * The array is marked as attaining values 0 and 1 only.
2591 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2592 __isl_keep isl_map *access)
2594 isl_ctx *ctx = isl_map_get_ctx(access);
2595 isl_space *dim;
2596 struct pet_array **arrays;
2597 struct pet_array *array;
2599 if (!scop)
2600 return NULL;
2601 if (!ctx)
2602 goto error;
2604 arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2605 scop->n_array + 1);
2606 if (!arrays)
2607 goto error;
2608 scop->arrays = arrays;
2610 array = isl_calloc_type(ctx, struct pet_array);
2611 if (!array)
2612 goto error;
2614 array->extent = isl_map_range(isl_map_copy(access));
2615 dim = isl_space_params_alloc(ctx, 0);
2616 array->context = isl_set_universe(dim);
2617 dim = isl_space_set_alloc(ctx, 0, 1);
2618 array->value_bounds = isl_set_universe(dim);
2619 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2620 isl_dim_set, 0, 0);
2621 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2622 isl_dim_set, 0, 1);
2623 array->element_type = strdup("int");
2625 scop->arrays[scop->n_array] = array;
2626 scop->n_array++;
2628 if (!array->extent || !array->context)
2629 goto error;
2631 return scop;
2632 error:
2633 pet_scop_free(scop);
2634 return NULL;
2637 extern "C" {
2638 static __isl_give isl_map *embed_access(__isl_take isl_map *access,
2639 void *user);
2642 /* Apply the map pointed to by "user" to the domain of the access
2643 * relation, thereby embedding it in the range of the map.
2644 * The domain of both relations is the zero-dimensional domain.
2646 static __isl_give isl_map *embed_access(__isl_take isl_map *access, void *user)
2648 isl_map *map = (isl_map *) user;
2650 return isl_map_apply_domain(access, isl_map_copy(map));
2653 /* Apply "map" to all access relations in "expr".
2655 static struct pet_expr *embed(struct pet_expr *expr, __isl_keep isl_map *map)
2657 return pet_expr_foreach_access(expr, &embed_access, map);
2660 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
2662 static int n_nested_parameter(__isl_keep isl_set *set)
2664 isl_space *space;
2665 int n;
2667 space = isl_set_get_space(set);
2668 n = n_nested_parameter(space);
2669 isl_space_free(space);
2671 return n;
2674 /* Remove all parameters from "map" that refer to nested accesses.
2676 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
2678 int nparam;
2679 isl_space *space;
2681 space = isl_map_get_space(map);
2682 nparam = isl_space_dim(space, isl_dim_param);
2683 for (int i = nparam - 1; i >= 0; --i)
2684 if (is_nested_parameter(space, i))
2685 map = isl_map_project_out(map, isl_dim_param, i, 1);
2686 isl_space_free(space);
2688 return map;
2691 extern "C" {
2692 static __isl_give isl_map *access_remove_nested_parameters(
2693 __isl_take isl_map *access, void *user);
2696 static __isl_give isl_map *access_remove_nested_parameters(
2697 __isl_take isl_map *access, void *user)
2699 return remove_nested_parameters(access);
2702 /* Remove all nested access parameters from the schedule and all
2703 * accesses of "stmt".
2704 * There is no need to remove them from the domain as these parameters
2705 * have already been removed from the domain when this function is called.
2707 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
2709 if (!stmt)
2710 return NULL;
2711 stmt->schedule = remove_nested_parameters(stmt->schedule);
2712 stmt->body = pet_expr_foreach_access(stmt->body,
2713 &access_remove_nested_parameters, NULL);
2714 if (!stmt->schedule || !stmt->body)
2715 goto error;
2716 for (int i = 0; i < stmt->n_arg; ++i) {
2717 stmt->args[i] = pet_expr_foreach_access(stmt->args[i],
2718 &access_remove_nested_parameters, NULL);
2719 if (!stmt->args[i])
2720 goto error;
2723 return stmt;
2724 error:
2725 pet_stmt_free(stmt);
2726 return NULL;
2729 /* For each nested access parameter in the domain of "stmt",
2730 * construct a corresponding pet_expr, place it in stmt->args and
2731 * record its position in "param2pos".
2732 * n is the number of nested access parameters.
2734 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
2735 std::map<int,int> &param2pos)
2737 isl_space *space;
2738 unsigned n_arg;
2739 struct pet_expr **args;
2741 n_arg = stmt->n_arg;
2742 args = isl_realloc_array(ctx, stmt->args, struct pet_expr *, n_arg + n);
2743 if (!args)
2744 goto error;
2745 stmt->args = args;
2746 stmt->n_arg += n;
2748 space = isl_set_get_space(stmt->domain);
2749 n = extract_nested(space, n_arg, stmt->args, param2pos);
2750 isl_space_free(space);
2752 if (n < 0)
2753 goto error;
2755 stmt->n_arg = n;
2756 return stmt;
2757 error:
2758 pet_stmt_free(stmt);
2759 return NULL;
2762 /* Look for parameters in the iteration domain of "stmt" that
2763 * refer to nested accesses. In particular, these are
2764 * parameters with no name.
2766 * If there are any such parameters, then as many extra variables
2767 * (after identifying identical nested accesses) are added to the
2768 * range of the map wrapped inside the domain.
2769 * If the original domain is not a wrapped map, then a new wrapped
2770 * map is created with zero output dimensions.
2771 * The parameters are then equated to the corresponding output dimensions
2772 * and subsequently projected out, from the iteration domain,
2773 * the schedule and the access relations.
2774 * For each of the output dimensions, a corresponding argument
2775 * expression is added. Initially they are created with
2776 * a zero-dimensional domain, so they have to be embedded
2777 * in the current iteration domain.
2778 * param2pos maps the position of the parameter to the position
2779 * of the corresponding output dimension in the wrapped map.
2781 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
2783 int n;
2784 int nparam;
2785 unsigned n_arg;
2786 isl_map *map;
2787 std::map<int,int> param2pos;
2789 if (!stmt)
2790 return NULL;
2792 n = n_nested_parameter(stmt->domain);
2793 if (n == 0)
2794 return stmt;
2796 n_arg = stmt->n_arg;
2797 stmt = extract_nested(stmt, n, param2pos);
2798 if (!stmt)
2799 return NULL;
2801 n = stmt->n_arg - n_arg;
2802 nparam = isl_set_dim(stmt->domain, isl_dim_param);
2803 if (isl_set_is_wrapping(stmt->domain))
2804 map = isl_set_unwrap(stmt->domain);
2805 else
2806 map = isl_map_from_domain(stmt->domain);
2807 map = isl_map_add_dims(map, isl_dim_out, n);
2809 for (int i = nparam - 1; i >= 0; --i) {
2810 isl_id *id;
2812 if (!is_nested_parameter(map, i))
2813 continue;
2815 id = isl_map_get_tuple_id(stmt->args[param2pos[i]]->acc.access,
2816 isl_dim_out);
2817 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
2818 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
2819 param2pos[i]);
2820 map = isl_map_project_out(map, isl_dim_param, i, 1);
2823 stmt->domain = isl_map_wrap(map);
2825 map = isl_set_unwrap(isl_set_copy(stmt->domain));
2826 map = isl_map_from_range(isl_map_domain(map));
2827 for (int pos = n_arg; pos < stmt->n_arg; ++pos)
2828 stmt->args[pos] = embed(stmt->args[pos], map);
2829 isl_map_free(map);
2831 stmt = remove_nested_parameters(stmt);
2833 return stmt;
2834 error:
2835 pet_stmt_free(stmt);
2836 return NULL;
2839 /* For each statement in "scop", move the parameters that correspond
2840 * to nested access into the ranges of the domains and create
2841 * corresponding argument expressions.
2843 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
2845 if (!scop)
2846 return NULL;
2848 for (int i = 0; i < scop->n_stmt; ++i) {
2849 scop->stmts[i] = resolve_nested(scop->stmts[i]);
2850 if (!scop->stmts[i])
2851 goto error;
2854 return scop;
2855 error:
2856 pet_scop_free(scop);
2857 return NULL;
2860 /* Does "space" involve any parameters that refer to nested
2861 * accesses, i.e., parameters with no name?
2863 static bool has_nested(__isl_keep isl_space *space)
2865 int nparam;
2867 nparam = isl_space_dim(space, isl_dim_param);
2868 for (int i = 0; i < nparam; ++i)
2869 if (is_nested_parameter(space, i))
2870 return true;
2872 return false;
2875 /* Does "set" involve any parameters that refer to nested
2876 * accesses, i.e., parameters with no name?
2878 static bool has_nested(__isl_keep isl_set *set)
2880 isl_space *space;
2881 bool nested;
2883 space = isl_set_get_space(set);
2884 nested = has_nested(space);
2885 isl_space_free(space);
2887 return nested;
2890 /* Given an access expression "expr", is the variable accessed by
2891 * "expr" assigned anywhere inside "scop"?
2893 static bool is_assigned(pet_expr *expr, pet_scop *scop)
2895 bool assigned = false;
2896 isl_id *id;
2898 id = isl_map_get_tuple_id(expr->acc.access, isl_dim_out);
2899 assigned = pet_scop_writes(scop, id);
2900 isl_id_free(id);
2902 return assigned;
2905 /* Are all nested access parameters in "set" allowed given "scop".
2906 * In particular, is none of them written by anywhere inside "scop".
2908 bool PetScan::is_nested_allowed(__isl_keep isl_set *set, pet_scop *scop)
2910 int nparam;
2912 nparam = isl_set_dim(set, isl_dim_param);
2913 for (int i = 0; i < nparam; ++i) {
2914 Expr *nested;
2915 isl_id *id = isl_set_get_dim_id(set, isl_dim_param, i);
2916 pet_expr *expr;
2917 bool allowed;
2919 if (!is_nested_parameter(id)) {
2920 isl_id_free(id);
2921 continue;
2924 nested = (Expr *) isl_id_get_user(id);
2925 expr = extract_expr(nested);
2926 allowed = expr && expr->type == pet_expr_access &&
2927 !is_assigned(expr, scop);
2929 pet_expr_free(expr);
2930 isl_id_free(id);
2932 if (!allowed)
2933 return false;
2936 return true;
2939 /* Construct a pet_scop for an if statement.
2941 * If the condition fits the pattern of a conditional assignment,
2942 * then it is handled by extract_conditional_assignment.
2943 * Otherwise, we do the following.
2945 * If the condition is affine, then the condition is added
2946 * to the iteration domains of the then branch, while the
2947 * opposite of the condition in added to the iteration domains
2948 * of the else branch, if any.
2949 * We allow the condition to be dynamic, i.e., to refer to
2950 * scalars or array elements that may be written to outside
2951 * of the given if statement. These nested accesses are then represented
2952 * as output dimensions in the wrapping iteration domain.
2953 * If it also written _inside_ the then or else branch, then
2954 * we treat the condition as non-affine.
2955 * As explained below, this will introduce an extra statement.
2956 * For aesthetic reasons, we want this statement to have a statement
2957 * number that is lower than those of the then and else branches.
2958 * In order to evaluate if will need such a statement, however, we
2959 * first construct scops for the then and else branches.
2960 * We therefore reserve a statement number if we might have to
2961 * introduce such an extra statement.
2963 * If the condition is not affine, then we create a separate
2964 * statement that writes the result of the condition to a virtual scalar.
2965 * A constraint requiring the value of this virtual scalar to be one
2966 * is added to the iteration domains of the then branch.
2967 * Similarly, a constraint requiring the value of this virtual scalar
2968 * to be zero is added to the iteration domains of the else branch, if any.
2969 * We adjust the schedules to ensure that the virtual scalar is written
2970 * before it is read.
2972 struct pet_scop *PetScan::extract(IfStmt *stmt)
2974 struct pet_scop *scop_then, *scop_else, *scop;
2975 assigned_value_cache cache(assigned_value);
2976 isl_map *test_access = NULL;
2977 isl_set *cond;
2978 int stmt_id;
2980 scop = extract_conditional_assignment(stmt);
2981 if (scop)
2982 return scop;
2984 cond = try_extract_nested_condition(stmt->getCond());
2985 if (allow_nested && (!cond || has_nested(cond)))
2986 stmt_id = n_stmt++;
2988 scop_then = extract(stmt->getThen());
2990 if (stmt->getElse()) {
2991 scop_else = extract(stmt->getElse());
2992 if (autodetect) {
2993 if (scop_then && !scop_else) {
2994 partial = true;
2995 isl_set_free(cond);
2996 return scop_then;
2998 if (!scop_then && scop_else) {
2999 partial = true;
3000 isl_set_free(cond);
3001 return scop_else;
3006 if (cond &&
3007 (!is_nested_allowed(cond, scop_then) ||
3008 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
3009 isl_set_free(cond);
3010 cond = NULL;
3012 if (allow_nested && !cond) {
3013 int save_n_stmt = n_stmt;
3014 test_access = create_test_access(ctx, n_test++);
3015 n_stmt = stmt_id;
3016 scop = extract_non_affine_condition(stmt->getCond(),
3017 isl_map_copy(test_access));
3018 n_stmt = save_n_stmt;
3019 scop = scop_add_array(scop, test_access);
3020 if (!scop) {
3021 pet_scop_free(scop_then);
3022 pet_scop_free(scop_else);
3023 isl_map_free(test_access);
3024 return NULL;
3028 if (!scop) {
3029 if (!cond)
3030 cond = extract_condition(stmt->getCond());
3031 scop = pet_scop_restrict(scop_then, isl_set_copy(cond));
3033 if (stmt->getElse()) {
3034 cond = isl_set_complement(cond);
3035 scop_else = pet_scop_restrict(scop_else, cond);
3036 scop = pet_scop_add(ctx, scop, scop_else);
3037 } else
3038 isl_set_free(cond);
3039 scop = resolve_nested(scop);
3040 } else {
3041 scop = pet_scop_prefix(scop, 0);
3042 scop_then = pet_scop_prefix(scop_then, 1);
3043 scop_then = pet_scop_filter(scop_then,
3044 isl_map_copy(test_access), 1);
3045 scop = pet_scop_add(ctx, scop, scop_then);
3046 if (stmt->getElse()) {
3047 scop_else = pet_scop_prefix(scop_else, 1);
3048 scop_else = pet_scop_filter(scop_else, test_access, 0);
3049 scop = pet_scop_add(ctx, scop, scop_else);
3050 } else
3051 isl_map_free(test_access);
3054 return scop;
3057 /* Try and construct a pet_scop for a label statement.
3058 * We currently only allow labels on expression statements.
3060 struct pet_scop *PetScan::extract(LabelStmt *stmt)
3062 isl_id *label;
3063 Stmt *sub;
3065 sub = stmt->getSubStmt();
3066 if (!isa<Expr>(sub)) {
3067 unsupported(stmt);
3068 return NULL;
3071 label = isl_id_alloc(ctx, stmt->getName(), NULL);
3073 return extract(sub, extract_expr(cast<Expr>(sub)), label);
3076 /* Try and construct a pet_scop corresponding to "stmt".
3078 struct pet_scop *PetScan::extract(Stmt *stmt)
3080 if (isa<Expr>(stmt))
3081 return extract(stmt, extract_expr(cast<Expr>(stmt)));
3083 switch (stmt->getStmtClass()) {
3084 case Stmt::WhileStmtClass:
3085 return extract(cast<WhileStmt>(stmt));
3086 case Stmt::ForStmtClass:
3087 return extract_for(cast<ForStmt>(stmt));
3088 case Stmt::IfStmtClass:
3089 return extract(cast<IfStmt>(stmt));
3090 case Stmt::CompoundStmtClass:
3091 return extract(cast<CompoundStmt>(stmt));
3092 case Stmt::LabelStmtClass:
3093 return extract(cast<LabelStmt>(stmt));
3094 default:
3095 unsupported(stmt);
3098 return NULL;
3101 /* Try and construct a pet_scop corresponding to (part of)
3102 * a sequence of statements.
3104 struct pet_scop *PetScan::extract(StmtRange stmt_range)
3106 pet_scop *scop;
3107 StmtIterator i;
3108 int j;
3109 bool partial_range = false;
3111 scop = pet_scop_empty(ctx);
3112 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
3113 Stmt *child = *i;
3114 struct pet_scop *scop_i;
3115 scop_i = extract(child);
3116 if (scop && partial) {
3117 pet_scop_free(scop_i);
3118 break;
3120 scop_i = pet_scop_prefix(scop_i, j);
3121 if (autodetect) {
3122 if (scop_i)
3123 scop = pet_scop_add(ctx, scop, scop_i);
3124 else
3125 partial_range = true;
3126 if (scop->n_stmt != 0 && !scop_i)
3127 partial = true;
3128 } else {
3129 scop = pet_scop_add(ctx, scop, scop_i);
3131 if (partial)
3132 break;
3135 if (scop && partial_range)
3136 partial = true;
3138 return scop;
3141 /* Check if the scop marked by the user is exactly this Stmt
3142 * or part of this Stmt.
3143 * If so, return a pet_scop corresponding to the marked region.
3144 * Otherwise, return NULL.
3146 struct pet_scop *PetScan::scan(Stmt *stmt)
3148 SourceManager &SM = PP.getSourceManager();
3149 unsigned start_off, end_off;
3151 start_off = SM.getFileOffset(stmt->getLocStart());
3152 end_off = SM.getFileOffset(stmt->getLocEnd());
3154 if (start_off > loc.end)
3155 return NULL;
3156 if (end_off < loc.start)
3157 return NULL;
3158 if (start_off >= loc.start && end_off <= loc.end) {
3159 return extract(stmt);
3162 StmtIterator start;
3163 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
3164 Stmt *child = *start;
3165 if (!child)
3166 continue;
3167 start_off = SM.getFileOffset(child->getLocStart());
3168 end_off = SM.getFileOffset(child->getLocEnd());
3169 if (start_off < loc.start && end_off > loc.end)
3170 return scan(child);
3171 if (start_off >= loc.start)
3172 break;
3175 StmtIterator end;
3176 for (end = start; end != stmt->child_end(); ++end) {
3177 Stmt *child = *end;
3178 start_off = SM.getFileOffset(child->getLocStart());
3179 if (start_off >= loc.end)
3180 break;
3183 return extract(StmtRange(start, end));
3186 /* Set the size of index "pos" of "array" to "size".
3187 * In particular, add a constraint of the form
3189 * i_pos < size
3191 * to array->extent and a constraint of the form
3193 * size >= 0
3195 * to array->context.
3197 static struct pet_array *update_size(struct pet_array *array, int pos,
3198 __isl_take isl_pw_aff *size)
3200 isl_set *valid;
3201 isl_set *univ;
3202 isl_set *bound;
3203 isl_space *dim;
3204 isl_aff *aff;
3205 isl_pw_aff *index;
3206 isl_id *id;
3208 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
3209 array->context = isl_set_intersect(array->context, valid);
3211 dim = isl_set_get_space(array->extent);
3212 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
3213 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
3214 univ = isl_set_universe(isl_aff_get_domain_space(aff));
3215 index = isl_pw_aff_alloc(univ, aff);
3217 size = isl_pw_aff_add_dims(size, isl_dim_in,
3218 isl_set_dim(array->extent, isl_dim_set));
3219 id = isl_set_get_tuple_id(array->extent);
3220 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
3221 bound = isl_pw_aff_lt_set(index, size);
3223 array->extent = isl_set_intersect(array->extent, bound);
3225 if (!array->context || !array->extent)
3226 goto error;
3228 return array;
3229 error:
3230 pet_array_free(array);
3231 return NULL;
3234 /* Figure out the size of the array at position "pos" and all
3235 * subsequent positions from "type" and update "array" accordingly.
3237 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
3238 const Type *type, int pos)
3240 const ArrayType *atype;
3241 isl_pw_aff *size;
3243 if (!array)
3244 return NULL;
3246 if (type->isPointerType()) {
3247 type = type->getPointeeType().getTypePtr();
3248 return set_upper_bounds(array, type, pos + 1);
3250 if (!type->isArrayType())
3251 return array;
3253 type = type->getCanonicalTypeInternal().getTypePtr();
3254 atype = cast<ArrayType>(type);
3256 if (type->isConstantArrayType()) {
3257 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
3258 size = extract_affine(ca->getSize());
3259 array = update_size(array, pos, size);
3260 } else if (type->isVariableArrayType()) {
3261 const VariableArrayType *vla = cast<VariableArrayType>(atype);
3262 size = extract_affine(vla->getSizeExpr());
3263 array = update_size(array, pos, size);
3266 type = atype->getElementType().getTypePtr();
3268 return set_upper_bounds(array, type, pos + 1);
3271 /* Construct and return a pet_array corresponding to the variable "decl".
3272 * In particular, initialize array->extent to
3274 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
3276 * and then call set_upper_bounds to set the upper bounds on the indices
3277 * based on the type of the variable.
3279 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl)
3281 struct pet_array *array;
3282 QualType qt = decl->getType();
3283 const Type *type = qt.getTypePtr();
3284 int depth = array_depth(type);
3285 QualType base = base_type(qt);
3286 string name;
3287 isl_id *id;
3288 isl_space *dim;
3290 array = isl_calloc_type(ctx, struct pet_array);
3291 if (!array)
3292 return NULL;
3294 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
3295 dim = isl_space_set_alloc(ctx, 0, depth);
3296 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
3298 array->extent = isl_set_nat_universe(dim);
3300 dim = isl_space_params_alloc(ctx, 0);
3301 array->context = isl_set_universe(dim);
3303 array = set_upper_bounds(array, type, 0);
3304 if (!array)
3305 return NULL;
3307 name = base.getAsString();
3308 array->element_type = strdup(name.c_str());
3310 return array;
3313 /* Construct a list of pet_arrays, one for each array (or scalar)
3314 * accessed inside "scop" add this list to "scop" and return the result.
3316 * The context of "scop" is updated with the intesection of
3317 * the contexts of all arrays, i.e., constraints on the parameters
3318 * that ensure that the arrays have a valid (non-negative) size.
3320 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
3322 int i;
3323 set<ValueDecl *> arrays;
3324 set<ValueDecl *>::iterator it;
3325 int n_array;
3326 struct pet_array **scop_arrays;
3328 if (!scop)
3329 return NULL;
3331 pet_scop_collect_arrays(scop, arrays);
3332 if (arrays.size() == 0)
3333 return scop;
3335 n_array = scop->n_array;
3337 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
3338 n_array + arrays.size());
3339 if (!scop_arrays)
3340 goto error;
3341 scop->arrays = scop_arrays;
3343 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
3344 struct pet_array *array;
3345 scop->arrays[n_array + i] = array = extract_array(ctx, *it);
3346 if (!scop->arrays[n_array + i])
3347 goto error;
3348 scop->n_array++;
3349 scop->context = isl_set_intersect(scop->context,
3350 isl_set_copy(array->context));
3351 if (!scop->context)
3352 goto error;
3355 return scop;
3356 error:
3357 pet_scop_free(scop);
3358 return NULL;
3361 /* Construct a pet_scop from the given function.
3363 struct pet_scop *PetScan::scan(FunctionDecl *fd)
3365 pet_scop *scop;
3366 Stmt *stmt;
3368 stmt = fd->getBody();
3370 if (autodetect)
3371 scop = extract(stmt);
3372 else
3373 scop = scan(stmt);
3374 scop = pet_scop_detect_parameter_accesses(scop);
3375 scop = scan_arrays(scop);
3377 return scop;