update isl for support for recent clangs
[pet.git] / scan.cc
blobaabc2bfb0f6859a37c2e04287419085183ae143e
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012 Ecole Normale Superieure. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials provided
15 * with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
21 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
24 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 * The views and conclusions contained in the software and documentation
30 * are those of the authors and should not be interpreted as
31 * representing official policies, either expressed or implied, of
32 * Leiden University.
33 */
35 #include <set>
36 #include <map>
37 #include <iostream>
38 #include <clang/AST/ASTDiagnostic.h>
39 #include <clang/AST/Expr.h>
40 #include <clang/AST/RecursiveASTVisitor.h>
42 #include <isl/id.h>
43 #include <isl/space.h>
44 #include <isl/aff.h>
45 #include <isl/set.h>
47 #include "scan.h"
48 #include "scop.h"
49 #include "scop_plus.h"
51 #include "config.h"
53 using namespace std;
54 using namespace clang;
56 #ifdef DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION
57 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
59 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
60 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
61 VK_LValue);
63 #else
64 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
66 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
67 var, var->getInnerLocStart(), var->getType(), VK_LValue);
69 #endif
71 /* Check if the element type corresponding to the given array type
72 * has a const qualifier.
74 static bool const_base(QualType qt)
76 const Type *type = qt.getTypePtr();
78 if (type->isPointerType())
79 return const_base(type->getPointeeType());
80 if (type->isArrayType()) {
81 const ArrayType *atype;
82 type = type->getCanonicalTypeInternal().getTypePtr();
83 atype = cast<ArrayType>(type);
84 return const_base(atype->getElementType());
87 return qt.isConstQualified();
90 /* Mark "decl" as having an unknown value in "assigned_value".
92 * If no (known or unknown) value was assigned to "decl" before,
93 * then it may have been treated as a parameter before and may
94 * therefore appear in a value assigned to another variable.
95 * If so, this assignment needs to be turned into an unknown value too.
97 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
98 ValueDecl *decl)
100 map<ValueDecl *, isl_pw_aff *>::iterator it;
102 it = assigned_value.find(decl);
104 assigned_value[decl] = NULL;
106 if (it == assigned_value.end())
107 return;
109 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
110 isl_pw_aff *pa = it->second;
111 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
113 for (int i = 0; i < nparam; ++i) {
114 isl_id *id;
116 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
117 continue;
118 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
119 if (isl_id_get_user(id) == decl)
120 it->second = NULL;
121 isl_id_free(id);
126 /* Look for any assignments to scalar variables in part of the parse
127 * tree and set assigned_value to NULL for each of them.
128 * Also reset assigned_value if the address of a scalar variable
129 * is being taken. As an exception, if the address is passed to a function
130 * that is declared to receive a const pointer, then assigned_value is
131 * not reset.
133 * This ensures that we won't use any previously stored value
134 * in the current subtree and its parents.
136 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
137 map<ValueDecl *, isl_pw_aff *> &assigned_value;
138 set<UnaryOperator *> skip;
140 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
141 assigned_value(assigned_value) {}
143 /* Check for "address of" operators whose value is passed
144 * to a const pointer argument and add them to "skip", so that
145 * we can skip them in VisitUnaryOperator.
147 bool VisitCallExpr(CallExpr *expr) {
148 FunctionDecl *fd;
149 fd = expr->getDirectCallee();
150 if (!fd)
151 return true;
152 for (int i = 0; i < expr->getNumArgs(); ++i) {
153 Expr *arg = expr->getArg(i);
154 UnaryOperator *op;
155 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
156 ImplicitCastExpr *ice;
157 ice = cast<ImplicitCastExpr>(arg);
158 arg = ice->getSubExpr();
160 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
161 continue;
162 op = cast<UnaryOperator>(arg);
163 if (op->getOpcode() != UO_AddrOf)
164 continue;
165 if (const_base(fd->getParamDecl(i)->getType()))
166 skip.insert(op);
168 return true;
171 bool VisitUnaryOperator(UnaryOperator *expr) {
172 Expr *arg;
173 DeclRefExpr *ref;
174 ValueDecl *decl;
176 if (expr->getOpcode() != UO_AddrOf)
177 return true;
178 if (skip.find(expr) != skip.end())
179 return true;
181 arg = expr->getSubExpr();
182 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
183 return true;
184 ref = cast<DeclRefExpr>(arg);
185 decl = ref->getDecl();
186 clear_assignment(assigned_value, decl);
187 return true;
190 bool VisitBinaryOperator(BinaryOperator *expr) {
191 Expr *lhs;
192 DeclRefExpr *ref;
193 ValueDecl *decl;
195 if (!expr->isAssignmentOp())
196 return true;
197 lhs = expr->getLHS();
198 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
199 return true;
200 ref = cast<DeclRefExpr>(lhs);
201 decl = ref->getDecl();
202 clear_assignment(assigned_value, decl);
203 return true;
207 /* Keep a copy of the currently assigned values.
209 * Any variable that is assigned a value inside the current scope
210 * is removed again when we leave the scope (either because it wasn't
211 * stored in the cache or because it has a different value in the cache).
213 struct assigned_value_cache {
214 map<ValueDecl *, isl_pw_aff *> &assigned_value;
215 map<ValueDecl *, isl_pw_aff *> cache;
217 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
218 assigned_value(assigned_value), cache(assigned_value) {}
219 ~assigned_value_cache() {
220 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
221 for (it = assigned_value.begin(); it != assigned_value.end();
222 ++it) {
223 if (!it->second ||
224 (cache.find(it->first) != cache.end() &&
225 cache[it->first] != it->second))
226 cache[it->first] = NULL;
228 assigned_value = cache;
232 /* Insert an expression into the collection of expressions,
233 * provided it is not already in there.
234 * The isl_pw_affs are freed in the destructor.
236 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
238 std::set<isl_pw_aff *>::iterator it;
240 if (expressions.find(expr) == expressions.end())
241 expressions.insert(expr);
242 else
243 isl_pw_aff_free(expr);
246 PetScan::~PetScan()
248 std::set<isl_pw_aff *>::iterator it;
250 for (it = expressions.begin(); it != expressions.end(); ++it)
251 isl_pw_aff_free(*it);
253 isl_union_map_free(value_bounds);
256 /* Called if we found something we (currently) cannot handle.
257 * We'll provide more informative warnings later.
259 * We only actually complain if autodetect is false.
261 void PetScan::unsupported(Stmt *stmt, const char *msg)
263 if (autodetect)
264 return;
266 SourceLocation loc = stmt->getLocStart();
267 DiagnosticsEngine &diag = PP.getDiagnostics();
268 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
269 msg ? msg : "unsupported");
270 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
273 /* Extract an integer from "expr" and store it in "v".
275 int PetScan::extract_int(IntegerLiteral *expr, isl_int *v)
277 const Type *type = expr->getType().getTypePtr();
278 int is_signed = type->hasSignedIntegerRepresentation();
280 if (is_signed) {
281 int64_t i = expr->getValue().getSExtValue();
282 isl_int_set_si(*v, i);
283 } else {
284 uint64_t i = expr->getValue().getZExtValue();
285 isl_int_set_ui(*v, i);
288 return 0;
291 /* Extract an integer from "expr" and store it in "v".
292 * Return -1 if "expr" does not (obviously) represent an integer.
294 int PetScan::extract_int(clang::ParenExpr *expr, isl_int *v)
296 return extract_int(expr->getSubExpr(), v);
299 /* Extract an integer from "expr" and store it in "v".
300 * Return -1 if "expr" does not (obviously) represent an integer.
302 int PetScan::extract_int(clang::Expr *expr, isl_int *v)
304 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
305 return extract_int(cast<IntegerLiteral>(expr), v);
306 if (expr->getStmtClass() == Stmt::ParenExprClass)
307 return extract_int(cast<ParenExpr>(expr), v);
309 unsupported(expr);
310 return -1;
313 /* Extract an affine expression from the IntegerLiteral "expr".
315 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
317 isl_space *dim = isl_space_params_alloc(ctx, 0);
318 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
319 isl_aff *aff = isl_aff_zero_on_domain(ls);
320 isl_set *dom = isl_set_universe(dim);
321 isl_int v;
323 isl_int_init(v);
324 extract_int(expr, &v);
325 aff = isl_aff_add_constant(aff, v);
326 isl_int_clear(v);
328 return isl_pw_aff_alloc(dom, aff);
331 /* Extract an affine expression from the APInt "val".
333 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
335 isl_space *dim = isl_space_params_alloc(ctx, 0);
336 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
337 isl_aff *aff = isl_aff_zero_on_domain(ls);
338 isl_set *dom = isl_set_universe(dim);
339 isl_int v;
341 isl_int_init(v);
342 isl_int_set_ui(v, val.getZExtValue());
343 aff = isl_aff_add_constant(aff, v);
344 isl_int_clear(v);
346 return isl_pw_aff_alloc(dom, aff);
349 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
351 return extract_affine(expr->getSubExpr());
354 static unsigned get_type_size(ValueDecl *decl)
356 return decl->getASTContext().getIntWidth(decl->getType());
359 /* Bound parameter "pos" of "set" to the possible values of "decl".
361 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
362 unsigned pos, ValueDecl *decl)
364 unsigned width;
365 isl_int v;
367 isl_int_init(v);
369 width = get_type_size(decl);
370 if (decl->getType()->isUnsignedIntegerType()) {
371 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
372 isl_int_set_si(v, 1);
373 isl_int_mul_2exp(v, v, width);
374 isl_int_sub_ui(v, v, 1);
375 set = isl_set_upper_bound(set, isl_dim_param, pos, v);
376 } else {
377 isl_int_set_si(v, 1);
378 isl_int_mul_2exp(v, v, width - 1);
379 isl_int_sub_ui(v, v, 1);
380 set = isl_set_upper_bound(set, isl_dim_param, pos, v);
381 isl_int_neg(v, v);
382 isl_int_sub_ui(v, v, 1);
383 set = isl_set_lower_bound(set, isl_dim_param, pos, v);
386 isl_int_clear(v);
388 return set;
391 /* Extract an affine expression from the DeclRefExpr "expr".
393 * If the variable has been assigned a value, then we check whether
394 * we know what (affine) value was assigned.
395 * If so, we return this value. Otherwise we convert "expr"
396 * to an extra parameter (provided nesting_enabled is set).
398 * Otherwise, we simply return an expression that is equal
399 * to a parameter corresponding to the referenced variable.
401 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
403 ValueDecl *decl = expr->getDecl();
404 const Type *type = decl->getType().getTypePtr();
405 isl_id *id;
406 isl_space *dim;
407 isl_aff *aff;
408 isl_set *dom;
410 if (!type->isIntegerType()) {
411 unsupported(expr);
412 return NULL;
415 if (assigned_value.find(decl) != assigned_value.end()) {
416 if (assigned_value[decl])
417 return isl_pw_aff_copy(assigned_value[decl]);
418 else
419 return nested_access(expr);
422 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
423 dim = isl_space_params_alloc(ctx, 1);
425 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
427 dom = isl_set_universe(isl_space_copy(dim));
428 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
429 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
431 return isl_pw_aff_alloc(dom, aff);
434 /* Extract an affine expression from an integer division operation.
435 * In particular, if "expr" is lhs/rhs, then return
437 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
439 * The second argument (rhs) is required to be a (positive) integer constant.
441 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
443 Expr *rhs_expr;
444 isl_pw_aff *lhs, *lhs_f, *lhs_c;
445 isl_pw_aff *res;
446 isl_int v;
447 isl_set *cond;
449 rhs_expr = expr->getRHS();
450 isl_int_init(v);
451 if (extract_int(rhs_expr, &v) < 0) {
452 isl_int_clear(v);
453 return NULL;
456 lhs = extract_affine(expr->getLHS());
457 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
459 lhs = isl_pw_aff_scale_down(lhs, v);
460 isl_int_clear(v);
462 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(lhs));
463 lhs_c = isl_pw_aff_ceil(lhs);
464 res = isl_pw_aff_cond(isl_set_indicator_function(cond), lhs_f, lhs_c);
466 return res;
469 /* Extract an affine expression from a modulo operation.
470 * In particular, if "expr" is lhs/rhs, then return
472 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
474 * The second argument (rhs) is required to be a (positive) integer constant.
476 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
478 Expr *rhs_expr;
479 isl_pw_aff *lhs, *lhs_f, *lhs_c;
480 isl_pw_aff *res;
481 isl_int v;
482 isl_set *cond;
484 rhs_expr = expr->getRHS();
485 if (rhs_expr->getStmtClass() != Stmt::IntegerLiteralClass) {
486 unsupported(expr);
487 return NULL;
490 lhs = extract_affine(expr->getLHS());
491 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
493 isl_int_init(v);
494 extract_int(cast<IntegerLiteral>(rhs_expr), &v);
495 res = isl_pw_aff_scale_down(isl_pw_aff_copy(lhs), v);
497 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(res));
498 lhs_c = isl_pw_aff_ceil(res);
499 res = isl_pw_aff_cond(isl_set_indicator_function(cond), lhs_f, lhs_c);
501 res = isl_pw_aff_scale(res, v);
502 isl_int_clear(v);
504 res = isl_pw_aff_sub(lhs, res);
506 return res;
509 /* Extract an affine expression from a multiplication operation.
510 * This is only allowed if at least one of the two arguments
511 * is a (piecewise) constant.
513 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
515 isl_pw_aff *lhs;
516 isl_pw_aff *rhs;
518 lhs = extract_affine(expr->getLHS());
519 rhs = extract_affine(expr->getRHS());
521 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
522 isl_pw_aff_free(lhs);
523 isl_pw_aff_free(rhs);
524 unsupported(expr);
525 return NULL;
528 return isl_pw_aff_mul(lhs, rhs);
531 /* Extract an affine expression from an addition or subtraction operation.
533 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
535 isl_pw_aff *lhs;
536 isl_pw_aff *rhs;
538 lhs = extract_affine(expr->getLHS());
539 rhs = extract_affine(expr->getRHS());
541 switch (expr->getOpcode()) {
542 case BO_Add:
543 return isl_pw_aff_add(lhs, rhs);
544 case BO_Sub:
545 return isl_pw_aff_sub(lhs, rhs);
546 default:
547 isl_pw_aff_free(lhs);
548 isl_pw_aff_free(rhs);
549 return NULL;
554 /* Compute
556 * pwaff mod 2^width
558 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
559 unsigned width)
561 isl_int mod;
563 isl_int_init(mod);
564 isl_int_set_si(mod, 1);
565 isl_int_mul_2exp(mod, mod, width);
567 pwaff = isl_pw_aff_mod(pwaff, mod);
569 isl_int_clear(mod);
571 return pwaff;
574 /* Limit the domain of "pwaff" to those elements where the function
575 * value satisfies
577 * 2^{width-1} <= pwaff < 2^{width-1}
579 static __isl_give isl_pw_aff *avoid_overflow(__isl_take isl_pw_aff *pwaff,
580 unsigned width)
582 isl_int v;
583 isl_space *space = isl_pw_aff_get_domain_space(pwaff);
584 isl_local_space *ls = isl_local_space_from_space(space);
585 isl_aff *bound;
586 isl_set *dom;
587 isl_pw_aff *b;
589 isl_int_init(v);
590 isl_int_set_si(v, 1);
591 isl_int_mul_2exp(v, v, width - 1);
593 bound = isl_aff_zero_on_domain(ls);
594 bound = isl_aff_add_constant(bound, v);
595 b = isl_pw_aff_from_aff(bound);
597 dom = isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff), isl_pw_aff_copy(b));
598 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
600 b = isl_pw_aff_neg(b);
601 dom = isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff), b);
602 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
604 isl_int_clear(v);
606 return pwaff;
609 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
611 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
612 __isl_take isl_set *dom)
614 isl_pw_aff *pa;
615 pa = isl_set_indicator_function(set);
616 pa = isl_pw_aff_intersect_domain(pa, dom);
617 return pa;
620 /* Extract an affine expression from some binary operations.
621 * If the result of the expression is unsigned, then we wrap it
622 * based on the size of the type. Otherwise, we ensure that
623 * no overflow occurs.
625 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
627 isl_pw_aff *res;
628 unsigned width;
630 switch (expr->getOpcode()) {
631 case BO_Add:
632 case BO_Sub:
633 res = extract_affine_add(expr);
634 break;
635 case BO_Div:
636 res = extract_affine_div(expr);
637 break;
638 case BO_Rem:
639 res = extract_affine_mod(expr);
640 break;
641 case BO_Mul:
642 res = extract_affine_mul(expr);
643 break;
644 case BO_LT:
645 case BO_LE:
646 case BO_GT:
647 case BO_GE:
648 case BO_EQ:
649 case BO_NE:
650 case BO_LAnd:
651 case BO_LOr:
652 return extract_condition(expr);
653 default:
654 unsupported(expr);
655 return NULL;
658 width = ast_context.getIntWidth(expr->getType());
659 if (expr->getType()->isUnsignedIntegerType())
660 res = wrap(res, width);
661 else
662 res = avoid_overflow(res, width);
664 return res;
667 /* Extract an affine expression from a negation operation.
669 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
671 if (expr->getOpcode() == UO_Minus)
672 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
673 if (expr->getOpcode() == UO_LNot)
674 return extract_condition(expr);
676 unsupported(expr);
677 return NULL;
680 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
682 return extract_affine(expr->getSubExpr());
685 /* Extract an affine expression from some special function calls.
686 * In particular, we handle "min", "max", "ceild" and "floord".
687 * In case of the latter two, the second argument needs to be
688 * a (positive) integer constant.
690 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
692 FunctionDecl *fd;
693 string name;
694 isl_pw_aff *aff1, *aff2;
696 fd = expr->getDirectCallee();
697 if (!fd) {
698 unsupported(expr);
699 return NULL;
702 name = fd->getDeclName().getAsString();
703 if (!(expr->getNumArgs() == 2 && name == "min") &&
704 !(expr->getNumArgs() == 2 && name == "max") &&
705 !(expr->getNumArgs() == 2 && name == "floord") &&
706 !(expr->getNumArgs() == 2 && name == "ceild")) {
707 unsupported(expr);
708 return NULL;
711 if (name == "min" || name == "max") {
712 aff1 = extract_affine(expr->getArg(0));
713 aff2 = extract_affine(expr->getArg(1));
715 if (name == "min")
716 aff1 = isl_pw_aff_min(aff1, aff2);
717 else
718 aff1 = isl_pw_aff_max(aff1, aff2);
719 } else if (name == "floord" || name == "ceild") {
720 isl_int v;
721 Expr *arg2 = expr->getArg(1);
723 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
724 unsupported(expr);
725 return NULL;
727 aff1 = extract_affine(expr->getArg(0));
728 isl_int_init(v);
729 extract_int(cast<IntegerLiteral>(arg2), &v);
730 aff1 = isl_pw_aff_scale_down(aff1, v);
731 isl_int_clear(v);
732 if (name == "floord")
733 aff1 = isl_pw_aff_floor(aff1);
734 else
735 aff1 = isl_pw_aff_ceil(aff1);
736 } else {
737 unsupported(expr);
738 return NULL;
741 return aff1;
745 /* This method is called when we come across an access that is
746 * nested in what is supposed to be an affine expression.
747 * If nesting is allowed, we return a new parameter that corresponds
748 * to this nested access. Otherwise, we simply complain.
750 * The new parameter is resolved in resolve_nested.
752 isl_pw_aff *PetScan::nested_access(Expr *expr)
754 isl_id *id;
755 isl_space *dim;
756 isl_aff *aff;
757 isl_set *dom;
759 if (!nesting_enabled) {
760 unsupported(expr);
761 return NULL;
764 id = isl_id_alloc(ctx, NULL, expr);
765 dim = isl_space_params_alloc(ctx, 1);
767 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
769 dom = isl_set_universe(isl_space_copy(dim));
770 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
771 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
773 return isl_pw_aff_alloc(dom, aff);
776 /* Affine expressions are not supposed to contain array accesses,
777 * but if nesting is allowed, we return a parameter corresponding
778 * to the array access.
780 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
782 return nested_access(expr);
785 /* Extract an affine expression from a conditional operation.
787 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
789 isl_pw_aff *cond, *lhs, *rhs, *res;
791 cond = extract_condition(expr->getCond());
792 lhs = extract_affine(expr->getTrueExpr());
793 rhs = extract_affine(expr->getFalseExpr());
795 return isl_pw_aff_cond(cond, lhs, rhs);
798 /* Extract an affine expression, if possible, from "expr".
799 * Otherwise return NULL.
801 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
803 switch (expr->getStmtClass()) {
804 case Stmt::ImplicitCastExprClass:
805 return extract_affine(cast<ImplicitCastExpr>(expr));
806 case Stmt::IntegerLiteralClass:
807 return extract_affine(cast<IntegerLiteral>(expr));
808 case Stmt::DeclRefExprClass:
809 return extract_affine(cast<DeclRefExpr>(expr));
810 case Stmt::BinaryOperatorClass:
811 return extract_affine(cast<BinaryOperator>(expr));
812 case Stmt::UnaryOperatorClass:
813 return extract_affine(cast<UnaryOperator>(expr));
814 case Stmt::ParenExprClass:
815 return extract_affine(cast<ParenExpr>(expr));
816 case Stmt::CallExprClass:
817 return extract_affine(cast<CallExpr>(expr));
818 case Stmt::ArraySubscriptExprClass:
819 return extract_affine(cast<ArraySubscriptExpr>(expr));
820 case Stmt::ConditionalOperatorClass:
821 return extract_affine(cast<ConditionalOperator>(expr));
822 default:
823 unsupported(expr);
825 return NULL;
828 __isl_give isl_map *PetScan::extract_access(ImplicitCastExpr *expr)
830 return extract_access(expr->getSubExpr());
833 /* Return the depth of an array of the given type.
835 static int array_depth(const Type *type)
837 if (type->isPointerType())
838 return 1 + array_depth(type->getPointeeType().getTypePtr());
839 if (type->isArrayType()) {
840 const ArrayType *atype;
841 type = type->getCanonicalTypeInternal().getTypePtr();
842 atype = cast<ArrayType>(type);
843 return 1 + array_depth(atype->getElementType().getTypePtr());
845 return 0;
848 /* Return the element type of the given array type.
850 static QualType base_type(QualType qt)
852 const Type *type = qt.getTypePtr();
854 if (type->isPointerType())
855 return base_type(type->getPointeeType());
856 if (type->isArrayType()) {
857 const ArrayType *atype;
858 type = type->getCanonicalTypeInternal().getTypePtr();
859 atype = cast<ArrayType>(type);
860 return base_type(atype->getElementType());
862 return qt;
865 /* Extract an access relation from a reference to a variable.
866 * If the variable has name "A" and its type corresponds to an
867 * array of depth d, then the returned access relation is of the
868 * form
870 * { [] -> A[i_1,...,i_d] }
872 __isl_give isl_map *PetScan::extract_access(DeclRefExpr *expr)
874 ValueDecl *decl = expr->getDecl();
875 int depth = array_depth(decl->getType().getTypePtr());
876 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
877 isl_space *dim = isl_space_alloc(ctx, 0, 0, depth);
878 isl_map *access_rel;
880 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
882 access_rel = isl_map_universe(dim);
884 return access_rel;
887 /* Extract an access relation from an integer contant.
888 * If the value of the constant is "v", then the returned access relation
889 * is
891 * { [] -> [v] }
893 __isl_give isl_map *PetScan::extract_access(IntegerLiteral *expr)
895 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr)));
898 /* Try and extract an access relation from the given Expr.
899 * Return NULL if it doesn't work out.
901 __isl_give isl_map *PetScan::extract_access(Expr *expr)
903 switch (expr->getStmtClass()) {
904 case Stmt::ImplicitCastExprClass:
905 return extract_access(cast<ImplicitCastExpr>(expr));
906 case Stmt::DeclRefExprClass:
907 return extract_access(cast<DeclRefExpr>(expr));
908 case Stmt::ArraySubscriptExprClass:
909 return extract_access(cast<ArraySubscriptExpr>(expr));
910 default:
911 unsupported(expr);
913 return NULL;
916 /* Assign the affine expression "index" to the output dimension "pos" of "map"
917 * and return the result.
919 __isl_give isl_map *set_index(__isl_take isl_map *map, int pos,
920 __isl_take isl_pw_aff *index)
922 isl_map *index_map;
923 int len = isl_map_dim(map, isl_dim_out);
924 isl_id *id;
926 index_map = isl_map_from_range(isl_set_from_pw_aff(index));
927 index_map = isl_map_insert_dims(index_map, isl_dim_out, 0, pos);
928 index_map = isl_map_add_dims(index_map, isl_dim_out, len - pos - 1);
929 id = isl_map_get_tuple_id(map, isl_dim_out);
930 index_map = isl_map_set_tuple_id(index_map, isl_dim_out, id);
932 map = isl_map_intersect(map, index_map);
934 return map;
937 /* Extract an access relation from the given array subscript expression.
938 * If nesting is allowed in general, then we turn it on while
939 * examining the index expression.
941 * We first extract an access relation from the base.
942 * This will result in an access relation with a range that corresponds
943 * to the array being accessed and with earlier indices filled in already.
944 * We then extract the current index and fill that in as well.
945 * The position of the current index is based on the type of base.
946 * If base is the actual array variable, then the depth of this type
947 * will be the same as the depth of the array and we will fill in
948 * the first array index.
949 * Otherwise, the depth of the base type will be smaller and we will fill
950 * in a later index.
952 __isl_give isl_map *PetScan::extract_access(ArraySubscriptExpr *expr)
954 Expr *base = expr->getBase();
955 Expr *idx = expr->getIdx();
956 isl_pw_aff *index;
957 isl_map *base_access;
958 isl_map *access;
959 int depth = array_depth(base->getType().getTypePtr());
960 int pos;
961 bool save_nesting = nesting_enabled;
963 nesting_enabled = allow_nested;
965 base_access = extract_access(base);
966 index = extract_affine(idx);
968 nesting_enabled = save_nesting;
970 pos = isl_map_dim(base_access, isl_dim_out) - depth;
971 access = set_index(base_access, pos, index);
973 return access;
976 /* Check if "expr" calls function "minmax" with two arguments and if so
977 * make lhs and rhs refer to these two arguments.
979 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
981 CallExpr *call;
982 FunctionDecl *fd;
983 string name;
985 if (expr->getStmtClass() != Stmt::CallExprClass)
986 return false;
988 call = cast<CallExpr>(expr);
989 fd = call->getDirectCallee();
990 if (!fd)
991 return false;
993 if (call->getNumArgs() != 2)
994 return false;
996 name = fd->getDeclName().getAsString();
997 if (name != minmax)
998 return false;
1000 lhs = call->getArg(0);
1001 rhs = call->getArg(1);
1003 return true;
1006 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1007 * lhs and rhs refer to the two arguments.
1009 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
1011 return is_minmax(expr, "min", lhs, rhs);
1014 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1015 * lhs and rhs refer to the two arguments.
1017 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
1019 return is_minmax(expr, "max", lhs, rhs);
1022 /* Return "lhs && rhs", defined on the shared definition domain.
1024 static __isl_give isl_pw_aff *pw_aff_and(__isl_take isl_pw_aff *lhs,
1025 __isl_take isl_pw_aff *rhs)
1027 isl_set *cond;
1028 isl_set *dom;
1030 dom = isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs)),
1031 isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1032 cond = isl_set_intersect(isl_pw_aff_non_zero_set(lhs),
1033 isl_pw_aff_non_zero_set(rhs));
1034 return indicator_function(cond, dom);
1037 /* Return "lhs && rhs", with shortcut semantics.
1038 * That is, if lhs is false, then the result is defined even if rhs is not.
1039 * In practice, we compute lhs ? rhs : lhs.
1041 static __isl_give isl_pw_aff *pw_aff_and_then(__isl_take isl_pw_aff *lhs,
1042 __isl_take isl_pw_aff *rhs)
1044 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), rhs, lhs);
1047 /* Return "lhs || rhs", with shortcut semantics.
1048 * That is, if lhs is true, then the result is defined even if rhs is not.
1049 * In practice, we compute lhs ? lhs : rhs.
1051 static __isl_give isl_pw_aff *pw_aff_or_else(__isl_take isl_pw_aff *lhs,
1052 __isl_take isl_pw_aff *rhs)
1054 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), lhs, rhs);
1057 /* Extract an affine expressions representing the comparison "LHS op RHS"
1058 * "comp" is the original statement that "LHS op RHS" is derived from
1059 * and is used for diagnostics.
1061 * If the comparison is of the form
1063 * a <= min(b,c)
1065 * then the expression is constructed as the conjunction of
1066 * the comparisons
1068 * a <= b and a <= c
1070 * A similar optimization is performed for max(a,b) <= c.
1071 * We do this because that will lead to simpler representations
1072 * of the expression.
1073 * If isl is ever enhanced to explicitly deal with min and max expressions,
1074 * this optimization can be removed.
1076 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
1077 Expr *LHS, Expr *RHS, Stmt *comp)
1079 isl_pw_aff *lhs;
1080 isl_pw_aff *rhs;
1081 isl_pw_aff *res;
1082 isl_set *cond;
1083 isl_set *dom;
1085 if (op == BO_GT)
1086 return extract_comparison(BO_LT, RHS, LHS, comp);
1087 if (op == BO_GE)
1088 return extract_comparison(BO_LE, RHS, LHS, comp);
1090 if (op == BO_LT || op == BO_LE) {
1091 Expr *expr1, *expr2;
1092 if (is_min(RHS, expr1, expr2)) {
1093 lhs = extract_comparison(op, LHS, expr1, comp);
1094 rhs = extract_comparison(op, LHS, expr2, comp);
1095 return pw_aff_and(lhs, rhs);
1097 if (is_max(LHS, expr1, expr2)) {
1098 lhs = extract_comparison(op, expr1, RHS, comp);
1099 rhs = extract_comparison(op, expr2, RHS, comp);
1100 return pw_aff_and(lhs, rhs);
1104 lhs = extract_affine(LHS);
1105 rhs = extract_affine(RHS);
1107 dom = isl_pw_aff_domain(isl_pw_aff_copy(lhs));
1108 dom = isl_set_intersect(dom, isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1110 switch (op) {
1111 case BO_LT:
1112 cond = isl_pw_aff_lt_set(lhs, rhs);
1113 break;
1114 case BO_LE:
1115 cond = isl_pw_aff_le_set(lhs, rhs);
1116 break;
1117 case BO_EQ:
1118 cond = isl_pw_aff_eq_set(lhs, rhs);
1119 break;
1120 case BO_NE:
1121 cond = isl_pw_aff_ne_set(lhs, rhs);
1122 break;
1123 default:
1124 isl_pw_aff_free(lhs);
1125 isl_pw_aff_free(rhs);
1126 isl_set_free(dom);
1127 unsupported(comp);
1128 return NULL;
1131 cond = isl_set_coalesce(cond);
1132 res = indicator_function(cond, dom);
1134 return res;
1137 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1139 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1140 comp->getRHS(), comp);
1143 /* Extract an affine expression representing the negation (logical not)
1144 * of a subexpression.
1146 __isl_give isl_pw_aff *PetScan::extract_boolean(UnaryOperator *op)
1148 isl_set *set_cond, *dom;
1149 isl_pw_aff *cond, *res;
1151 cond = extract_condition(op->getSubExpr());
1153 dom = isl_pw_aff_domain(isl_pw_aff_copy(cond));
1155 set_cond = isl_pw_aff_zero_set(cond);
1157 res = indicator_function(set_cond, dom);
1159 return res;
1162 /* Extract an affine expression representing the disjunction (logical or)
1163 * or conjunction (logical and) of two subexpressions.
1165 __isl_give isl_pw_aff *PetScan::extract_boolean(BinaryOperator *comp)
1167 isl_pw_aff *lhs, *rhs;
1169 lhs = extract_condition(comp->getLHS());
1170 rhs = extract_condition(comp->getRHS());
1172 switch (comp->getOpcode()) {
1173 case BO_LAnd:
1174 return pw_aff_and_then(lhs, rhs);
1175 case BO_LOr:
1176 return pw_aff_or_else(lhs, rhs);
1177 default:
1178 isl_pw_aff_free(lhs);
1179 isl_pw_aff_free(rhs);
1182 unsupported(comp);
1183 return NULL;
1186 __isl_give isl_pw_aff *PetScan::extract_condition(UnaryOperator *expr)
1188 switch (expr->getOpcode()) {
1189 case UO_LNot:
1190 return extract_boolean(expr);
1191 default:
1192 unsupported(expr);
1193 return NULL;
1197 /* Extract the affine expression "expr != 0 ? 1 : 0".
1199 __isl_give isl_pw_aff *PetScan::extract_implicit_condition(Expr *expr)
1201 isl_pw_aff *res;
1202 isl_set *set, *dom;
1204 res = extract_affine(expr);
1206 dom = isl_pw_aff_domain(isl_pw_aff_copy(res));
1207 set = isl_pw_aff_non_zero_set(res);
1209 res = indicator_function(set, dom);
1211 return res;
1214 /* Extract an affine expression from a boolean expression.
1215 * In particular, return the expression "expr ? 1 : 0".
1217 * If the expression doesn't look like a condition, we assume it
1218 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1220 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1222 BinaryOperator *comp;
1224 if (!expr) {
1225 isl_set *u = isl_set_universe(isl_space_params_alloc(ctx, 0));
1226 return indicator_function(u, isl_set_copy(u));
1229 if (expr->getStmtClass() == Stmt::ParenExprClass)
1230 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1232 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1233 return extract_condition(cast<UnaryOperator>(expr));
1235 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1236 return extract_implicit_condition(expr);
1238 comp = cast<BinaryOperator>(expr);
1239 switch (comp->getOpcode()) {
1240 case BO_LT:
1241 case BO_LE:
1242 case BO_GT:
1243 case BO_GE:
1244 case BO_EQ:
1245 case BO_NE:
1246 return extract_comparison(comp);
1247 case BO_LAnd:
1248 case BO_LOr:
1249 return extract_boolean(comp);
1250 default:
1251 return extract_implicit_condition(expr);
1255 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1257 switch (kind) {
1258 case UO_Minus:
1259 return pet_op_minus;
1260 default:
1261 return pet_op_last;
1265 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1267 switch (kind) {
1268 case BO_AddAssign:
1269 return pet_op_add_assign;
1270 case BO_SubAssign:
1271 return pet_op_sub_assign;
1272 case BO_MulAssign:
1273 return pet_op_mul_assign;
1274 case BO_DivAssign:
1275 return pet_op_div_assign;
1276 case BO_Assign:
1277 return pet_op_assign;
1278 case BO_Add:
1279 return pet_op_add;
1280 case BO_Sub:
1281 return pet_op_sub;
1282 case BO_Mul:
1283 return pet_op_mul;
1284 case BO_Div:
1285 return pet_op_div;
1286 case BO_EQ:
1287 return pet_op_eq;
1288 case BO_LE:
1289 return pet_op_le;
1290 case BO_LT:
1291 return pet_op_lt;
1292 case BO_GT:
1293 return pet_op_gt;
1294 default:
1295 return pet_op_last;
1299 /* Construct a pet_expr representing a unary operator expression.
1301 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1303 struct pet_expr *arg;
1304 enum pet_op_type op;
1306 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1307 if (op == pet_op_last) {
1308 unsupported(expr);
1309 return NULL;
1312 arg = extract_expr(expr->getSubExpr());
1314 return pet_expr_new_unary(ctx, op, arg);
1317 /* Mark the given access pet_expr as a write.
1318 * If a scalar is being accessed, then mark its value
1319 * as unknown in assigned_value.
1321 void PetScan::mark_write(struct pet_expr *access)
1323 isl_id *id;
1324 ValueDecl *decl;
1326 access->acc.write = 1;
1327 access->acc.read = 0;
1329 if (isl_map_dim(access->acc.access, isl_dim_out) != 0)
1330 return;
1332 id = isl_map_get_tuple_id(access->acc.access, isl_dim_out);
1333 decl = (ValueDecl *) isl_id_get_user(id);
1334 clear_assignment(assigned_value, decl);
1335 isl_id_free(id);
1338 /* Construct a pet_expr representing a binary operator expression.
1340 * If the top level operator is an assignment and the LHS is an access,
1341 * then we mark that access as a write. If the operator is a compound
1342 * assignment, the access is marked as both a read and a write.
1344 * If "expr" assigns something to a scalar variable, then we mark
1345 * the variable as having been assigned. If, furthermore, the expression
1346 * is affine, then keep track of this value in assigned_value
1347 * so that we can plug it in when we later come across the same variable.
1349 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1351 struct pet_expr *lhs, *rhs;
1352 enum pet_op_type op;
1354 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1355 if (op == pet_op_last) {
1356 unsupported(expr);
1357 return NULL;
1360 lhs = extract_expr(expr->getLHS());
1361 rhs = extract_expr(expr->getRHS());
1363 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1364 mark_write(lhs);
1365 if (expr->isCompoundAssignmentOp())
1366 lhs->acc.read = 1;
1369 if (expr->getOpcode() == BO_Assign &&
1370 lhs && lhs->type == pet_expr_access &&
1371 isl_map_dim(lhs->acc.access, isl_dim_out) == 0) {
1372 isl_id *id = isl_map_get_tuple_id(lhs->acc.access, isl_dim_out);
1373 ValueDecl *decl = (ValueDecl *) isl_id_get_user(id);
1374 Expr *rhs = expr->getRHS();
1375 isl_pw_aff *pa = try_extract_affine(rhs);
1376 clear_assignment(assigned_value, decl);
1377 if (pa) {
1378 assigned_value[decl] = pa;
1379 insert_expression(pa);
1381 isl_id_free(id);
1384 return pet_expr_new_binary(ctx, op, lhs, rhs);
1387 /* Construct a pet_expr representing a conditional operation.
1389 * We first try to extract the condition as an affine expression.
1390 * If that fails, we construct a pet_expr tree representing the condition.
1392 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1394 struct pet_expr *cond, *lhs, *rhs;
1395 isl_pw_aff *pa;
1397 pa = try_extract_affine(expr->getCond());
1398 if (pa) {
1399 isl_set *test = isl_set_from_pw_aff(pa);
1400 cond = pet_expr_from_access(isl_map_from_range(test));
1401 } else
1402 cond = extract_expr(expr->getCond());
1403 lhs = extract_expr(expr->getTrueExpr());
1404 rhs = extract_expr(expr->getFalseExpr());
1406 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1409 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1411 return extract_expr(expr->getSubExpr());
1414 /* Construct a pet_expr representing a floating point value.
1416 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1418 return pet_expr_new_double(ctx, expr->getValueAsApproximateDouble());
1421 /* Extract an access relation from "expr" and then convert it into
1422 * a pet_expr.
1424 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1426 isl_map *access;
1427 struct pet_expr *pe;
1429 switch (expr->getStmtClass()) {
1430 case Stmt::ArraySubscriptExprClass:
1431 access = extract_access(cast<ArraySubscriptExpr>(expr));
1432 break;
1433 case Stmt::DeclRefExprClass:
1434 access = extract_access(cast<DeclRefExpr>(expr));
1435 break;
1436 case Stmt::IntegerLiteralClass:
1437 access = extract_access(cast<IntegerLiteral>(expr));
1438 break;
1439 default:
1440 unsupported(expr);
1441 return NULL;
1444 pe = pet_expr_from_access(access);
1446 return pe;
1449 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1451 return extract_expr(expr->getSubExpr());
1454 /* Construct a pet_expr representing a function call.
1456 * If we are passing along a pointer to an array element
1457 * or an entire row or even higher dimensional slice of an array,
1458 * then the function being called may write into the array.
1460 * We assume here that if the function is declared to take a pointer
1461 * to a const type, then the function will perform a read
1462 * and that otherwise, it will perform a write.
1464 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1466 struct pet_expr *res = NULL;
1467 FunctionDecl *fd;
1468 string name;
1470 fd = expr->getDirectCallee();
1471 if (!fd) {
1472 unsupported(expr);
1473 return NULL;
1476 name = fd->getDeclName().getAsString();
1477 res = pet_expr_new_call(ctx, name.c_str(), expr->getNumArgs());
1478 if (!res)
1479 return NULL;
1481 for (int i = 0; i < expr->getNumArgs(); ++i) {
1482 Expr *arg = expr->getArg(i);
1483 int is_addr = 0;
1484 pet_expr *main_arg;
1486 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
1487 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(arg);
1488 arg = ice->getSubExpr();
1490 if (arg->getStmtClass() == Stmt::UnaryOperatorClass) {
1491 UnaryOperator *op = cast<UnaryOperator>(arg);
1492 if (op->getOpcode() == UO_AddrOf) {
1493 is_addr = 1;
1494 arg = op->getSubExpr();
1497 res->args[i] = PetScan::extract_expr(arg);
1498 main_arg = res->args[i];
1499 if (is_addr)
1500 res->args[i] = pet_expr_new_unary(ctx,
1501 pet_op_address_of, res->args[i]);
1502 if (!res->args[i])
1503 goto error;
1504 if (arg->getStmtClass() == Stmt::ArraySubscriptExprClass &&
1505 array_depth(arg->getType().getTypePtr()) > 0)
1506 is_addr = 1;
1507 if (is_addr && main_arg->type == pet_expr_access) {
1508 ParmVarDecl *parm;
1509 if (!fd->hasPrototype()) {
1510 unsupported(expr, "prototype required");
1511 goto error;
1513 parm = fd->getParamDecl(i);
1514 if (!const_base(parm->getType()))
1515 mark_write(main_arg);
1519 return res;
1520 error:
1521 pet_expr_free(res);
1522 return NULL;
1525 /* Try and onstruct a pet_expr representing "expr".
1527 struct pet_expr *PetScan::extract_expr(Expr *expr)
1529 switch (expr->getStmtClass()) {
1530 case Stmt::UnaryOperatorClass:
1531 return extract_expr(cast<UnaryOperator>(expr));
1532 case Stmt::CompoundAssignOperatorClass:
1533 case Stmt::BinaryOperatorClass:
1534 return extract_expr(cast<BinaryOperator>(expr));
1535 case Stmt::ImplicitCastExprClass:
1536 return extract_expr(cast<ImplicitCastExpr>(expr));
1537 case Stmt::ArraySubscriptExprClass:
1538 case Stmt::DeclRefExprClass:
1539 case Stmt::IntegerLiteralClass:
1540 return extract_access_expr(expr);
1541 case Stmt::FloatingLiteralClass:
1542 return extract_expr(cast<FloatingLiteral>(expr));
1543 case Stmt::ParenExprClass:
1544 return extract_expr(cast<ParenExpr>(expr));
1545 case Stmt::ConditionalOperatorClass:
1546 return extract_expr(cast<ConditionalOperator>(expr));
1547 case Stmt::CallExprClass:
1548 return extract_expr(cast<CallExpr>(expr));
1549 default:
1550 unsupported(expr);
1552 return NULL;
1555 /* Check if the given initialization statement is an assignment.
1556 * If so, return that assignment. Otherwise return NULL.
1558 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1560 BinaryOperator *ass;
1562 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1563 return NULL;
1565 ass = cast<BinaryOperator>(init);
1566 if (ass->getOpcode() != BO_Assign)
1567 return NULL;
1569 return ass;
1572 /* Check if the given initialization statement is a declaration
1573 * of a single variable.
1574 * If so, return that declaration. Otherwise return NULL.
1576 Decl *PetScan::initialization_declaration(Stmt *init)
1578 DeclStmt *decl;
1580 if (init->getStmtClass() != Stmt::DeclStmtClass)
1581 return NULL;
1583 decl = cast<DeclStmt>(init);
1585 if (!decl->isSingleDecl())
1586 return NULL;
1588 return decl->getSingleDecl();
1591 /* Given the assignment operator in the initialization of a for loop,
1592 * extract the induction variable, i.e., the (integer)variable being
1593 * assigned.
1595 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1597 Expr *lhs;
1598 DeclRefExpr *ref;
1599 ValueDecl *decl;
1600 const Type *type;
1602 lhs = init->getLHS();
1603 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1604 unsupported(init);
1605 return NULL;
1608 ref = cast<DeclRefExpr>(lhs);
1609 decl = ref->getDecl();
1610 type = decl->getType().getTypePtr();
1612 if (!type->isIntegerType()) {
1613 unsupported(lhs);
1614 return NULL;
1617 return decl;
1620 /* Given the initialization statement of a for loop and the single
1621 * declaration in this initialization statement,
1622 * extract the induction variable, i.e., the (integer) variable being
1623 * declared.
1625 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1627 VarDecl *vd;
1629 vd = cast<VarDecl>(decl);
1631 const QualType type = vd->getType();
1632 if (!type->isIntegerType()) {
1633 unsupported(init);
1634 return NULL;
1637 if (!vd->getInit()) {
1638 unsupported(init);
1639 return NULL;
1642 return vd;
1645 /* Check that op is of the form iv++ or iv--.
1646 * Return an affine expression "1" or "-1" accordingly.
1648 __isl_give isl_pw_aff *PetScan::extract_unary_increment(
1649 clang::UnaryOperator *op, clang::ValueDecl *iv)
1651 Expr *sub;
1652 DeclRefExpr *ref;
1653 isl_space *space;
1654 isl_aff *aff;
1656 if (!op->isIncrementDecrementOp()) {
1657 unsupported(op);
1658 return NULL;
1661 sub = op->getSubExpr();
1662 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1663 unsupported(op);
1664 return NULL;
1667 ref = cast<DeclRefExpr>(sub);
1668 if (ref->getDecl() != iv) {
1669 unsupported(op);
1670 return NULL;
1673 space = isl_space_params_alloc(ctx, 0);
1674 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1676 if (op->isIncrementOp())
1677 aff = isl_aff_add_constant_si(aff, 1);
1678 else
1679 aff = isl_aff_add_constant_si(aff, -1);
1681 return isl_pw_aff_from_aff(aff);
1684 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1685 * has a single constant expression, then put this constant in *user.
1686 * The caller is assumed to have checked that this function will
1687 * be called exactly once.
1689 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
1690 void *user)
1692 isl_int *inc = (isl_int *)user;
1693 int res = 0;
1695 if (isl_aff_is_cst(aff))
1696 isl_aff_get_constant(aff, inc);
1697 else
1698 res = -1;
1700 isl_set_free(set);
1701 isl_aff_free(aff);
1703 return res;
1706 /* Check if op is of the form
1708 * iv = iv + inc
1710 * and return inc as an affine expression.
1712 * We extract an affine expression from the RHS, subtract iv and return
1713 * the result.
1715 __isl_give isl_pw_aff *PetScan::extract_binary_increment(BinaryOperator *op,
1716 clang::ValueDecl *iv)
1718 Expr *lhs;
1719 DeclRefExpr *ref;
1720 isl_id *id;
1721 isl_space *dim;
1722 isl_aff *aff;
1723 isl_pw_aff *val;
1725 if (op->getOpcode() != BO_Assign) {
1726 unsupported(op);
1727 return NULL;
1730 lhs = op->getLHS();
1731 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1732 unsupported(op);
1733 return NULL;
1736 ref = cast<DeclRefExpr>(lhs);
1737 if (ref->getDecl() != iv) {
1738 unsupported(op);
1739 return NULL;
1742 val = extract_affine(op->getRHS());
1744 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1746 dim = isl_space_params_alloc(ctx, 1);
1747 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1748 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1749 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1751 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
1753 return val;
1756 /* Check that op is of the form iv += cst or iv -= cst
1757 * and return an affine expression corresponding oto cst or -cst accordingly.
1759 __isl_give isl_pw_aff *PetScan::extract_compound_increment(
1760 CompoundAssignOperator *op, clang::ValueDecl *iv)
1762 Expr *lhs;
1763 DeclRefExpr *ref;
1764 bool neg = false;
1765 isl_pw_aff *val;
1766 BinaryOperatorKind opcode;
1768 opcode = op->getOpcode();
1769 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1770 unsupported(op);
1771 return NULL;
1773 if (opcode == BO_SubAssign)
1774 neg = true;
1776 lhs = op->getLHS();
1777 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1778 unsupported(op);
1779 return NULL;
1782 ref = cast<DeclRefExpr>(lhs);
1783 if (ref->getDecl() != iv) {
1784 unsupported(op);
1785 return NULL;
1788 val = extract_affine(op->getRHS());
1789 if (neg)
1790 val = isl_pw_aff_neg(val);
1792 return val;
1795 /* Check that the increment of the given for loop increments
1796 * (or decrements) the induction variable "iv" and return
1797 * the increment as an affine expression if successful.
1799 __isl_give isl_pw_aff *PetScan::extract_increment(clang::ForStmt *stmt,
1800 ValueDecl *iv)
1802 Stmt *inc = stmt->getInc();
1804 if (!inc) {
1805 unsupported(stmt);
1806 return NULL;
1809 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1810 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1811 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1812 return extract_compound_increment(
1813 cast<CompoundAssignOperator>(inc), iv);
1814 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1815 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1817 unsupported(inc);
1818 return NULL;
1821 /* Embed the given iteration domain in an extra outer loop
1822 * with induction variable "var".
1823 * If this variable appeared as a parameter in the constraints,
1824 * it is replaced by the new outermost dimension.
1826 static __isl_give isl_set *embed(__isl_take isl_set *set,
1827 __isl_take isl_id *var)
1829 int pos;
1831 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
1832 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
1833 if (pos >= 0) {
1834 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
1835 set = isl_set_project_out(set, isl_dim_param, pos, 1);
1838 isl_id_free(var);
1839 return set;
1842 /* Construct a pet_scop for an infinite loop around the given body.
1844 * We extract a pet_scop for the body and then embed it in a loop with
1845 * iteration domain
1847 * { [t] : t >= 0 }
1849 * and schedule
1851 * { [t] -> [t] }
1853 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
1855 isl_id *id;
1856 isl_space *dim;
1857 isl_set *domain;
1858 isl_map *sched;
1859 struct pet_scop *scop;
1861 scop = extract(body);
1862 if (!scop)
1863 return NULL;
1865 id = isl_id_alloc(ctx, "t", NULL);
1866 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
1867 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
1868 dim = isl_space_from_domain(isl_set_get_space(domain));
1869 dim = isl_space_add_dims(dim, isl_dim_out, 1);
1870 sched = isl_map_universe(dim);
1871 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
1872 scop = pet_scop_embed(scop, domain, sched, id);
1874 return scop;
1877 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1879 * for (;;)
1880 * body
1883 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
1885 return extract_infinite_loop(stmt->getBody());
1888 /* Check if the while loop is of the form
1890 * while (1)
1891 * body
1893 * If so, construct a scop for an infinite loop around body.
1894 * Otherwise, fail.
1896 struct pet_scop *PetScan::extract(WhileStmt *stmt)
1898 Expr *cond;
1899 isl_set *set;
1900 int is_universe;
1902 cond = stmt->getCond();
1903 if (!cond) {
1904 unsupported(stmt);
1905 return NULL;
1908 set = isl_pw_aff_non_zero_set(extract_condition(cond));
1909 is_universe = isl_set_plain_is_universe(set);
1910 isl_set_free(set);
1912 if (!is_universe) {
1913 unsupported(stmt);
1914 return NULL;
1917 return extract_infinite_loop(stmt->getBody());
1920 /* Check whether "cond" expresses a simple loop bound
1921 * on the only set dimension.
1922 * In particular, if "up" is set then "cond" should contain only
1923 * upper bounds on the set dimension.
1924 * Otherwise, it should contain only lower bounds.
1926 static bool is_simple_bound(__isl_keep isl_set *cond, isl_int inc)
1928 if (isl_int_is_pos(inc))
1929 return !isl_set_dim_has_lower_bound(cond, isl_dim_set, 0);
1930 else
1931 return !isl_set_dim_has_upper_bound(cond, isl_dim_set, 0);
1934 /* Extend a condition on a given iteration of a loop to one that
1935 * imposes the same condition on all previous iterations.
1936 * "domain" expresses the lower [upper] bound on the iterations
1937 * when inc is positive [negative].
1939 * In particular, we construct the condition (when inc is positive)
1941 * forall i' : (domain(i') and i' <= i) => cond(i')
1943 * which is equivalent to
1945 * not exists i' : domain(i') and i' <= i and not cond(i')
1947 * We construct this set by negating cond, applying a map
1949 * { [i'] -> [i] : domain(i') and i' <= i }
1951 * and then negating the result again.
1953 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
1954 __isl_take isl_set *domain, isl_int inc)
1956 isl_map *previous_to_this;
1958 if (isl_int_is_pos(inc))
1959 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
1960 else
1961 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
1963 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
1965 cond = isl_set_complement(cond);
1966 cond = isl_set_apply(cond, previous_to_this);
1967 cond = isl_set_complement(cond);
1969 return cond;
1972 /* Construct a domain of the form
1974 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
1976 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
1977 __isl_take isl_pw_aff *init, isl_int inc)
1979 isl_aff *aff;
1980 isl_space *dim;
1981 isl_set *set;
1983 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
1984 dim = isl_pw_aff_get_domain_space(init);
1985 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1986 aff = isl_aff_add_coefficient(aff, isl_dim_in, 0, inc);
1987 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
1989 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
1990 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1991 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1992 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1994 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
1996 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
1998 return isl_set_params(set);
2001 /* Assuming "cond" represents a bound on a loop where the loop
2002 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2003 * is possible.
2005 * Under the given assumptions, wrapping is only possible if "cond" allows
2006 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2007 * increasing iterator and 0 in case of a decreasing iterator.
2009 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv, isl_int inc)
2011 bool cw;
2012 isl_int limit;
2013 isl_set *test;
2015 test = isl_set_copy(cond);
2017 isl_int_init(limit);
2018 if (isl_int_is_neg(inc))
2019 isl_int_set_si(limit, 0);
2020 else {
2021 isl_int_set_si(limit, 1);
2022 isl_int_mul_2exp(limit, limit, get_type_size(iv));
2023 isl_int_sub_ui(limit, limit, 1);
2026 test = isl_set_fix(cond, isl_dim_set, 0, limit);
2027 cw = !isl_set_is_empty(test);
2028 isl_set_free(test);
2030 isl_int_clear(limit);
2032 return cw;
2035 /* Given a one-dimensional space, construct the following mapping on this
2036 * space
2038 * { [v] -> [v mod 2^width] }
2040 * where width is the number of bits used to represent the values
2041 * of the unsigned variable "iv".
2043 static __isl_give isl_map *compute_wrapping(__isl_take isl_space *dim,
2044 ValueDecl *iv)
2046 isl_int mod;
2047 isl_aff *aff;
2048 isl_map *map;
2050 isl_int_init(mod);
2051 isl_int_set_si(mod, 1);
2052 isl_int_mul_2exp(mod, mod, get_type_size(iv));
2054 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2055 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2056 aff = isl_aff_mod(aff, mod);
2058 isl_int_clear(mod);
2060 return isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2061 map = isl_map_reverse(map);
2064 /* Project out the parameter "id" from "set".
2066 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2067 __isl_keep isl_id *id)
2069 int pos;
2071 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2072 if (pos >= 0)
2073 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2075 return set;
2078 /* Compute the set of parameters for which "set1" is a subset of "set2".
2080 * set1 is a subset of set2 if
2082 * forall i in set1 : i in set2
2084 * or
2086 * not exists i in set1 and i not in set2
2088 * i.e.,
2090 * not exists i in set1 \ set2
2092 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2093 __isl_take isl_set *set2)
2095 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2098 /* Compute the set of parameter values for which "cond" holds
2099 * on the next iteration for each element of "dom".
2101 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2102 * and then compute the set of parameters for which the result is a subset
2103 * of "cond".
2105 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2106 __isl_take isl_set *dom, isl_int inc)
2108 isl_space *space;
2109 isl_aff *aff;
2110 isl_map *next;
2112 space = isl_set_get_space(dom);
2113 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2114 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2115 aff = isl_aff_add_constant(aff, inc);
2116 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2118 dom = isl_set_apply(dom, next);
2120 return enforce_subset(dom, cond);
2123 /* Construct a pet_scop for a for statement.
2124 * The for loop is required to be of the form
2126 * for (i = init; condition; ++i)
2128 * or
2130 * for (i = init; condition; --i)
2132 * The initialization of the for loop should either be an assignment
2133 * to an integer variable, or a declaration of such a variable with
2134 * initialization.
2136 * The condition is allowed to contain nested accesses, provided
2137 * they are not being written to inside the body of the loop.
2139 * We extract a pet_scop for the body and then embed it in a loop with
2140 * iteration domain and schedule
2142 * { [i] : i >= init and condition' }
2143 * { [i] -> [i] }
2145 * or
2147 * { [i] : i <= init and condition' }
2148 * { [i] -> [-i] }
2150 * Where condition' is equal to condition if the latter is
2151 * a simple upper [lower] bound and a condition that is extended
2152 * to apply to all previous iterations otherwise.
2154 * If the stride of the loop is not 1, then "i >= init" is replaced by
2156 * (exists a: i = init + stride * a and a >= 0)
2158 * If the loop iterator i is unsigned, then wrapping may occur.
2159 * During the computation, we work with a virtual iterator that
2160 * does not wrap. However, the condition in the code applies
2161 * to the wrapped value, so we need to change condition(i)
2162 * into condition([i % 2^width]).
2163 * After computing the virtual domain and schedule, we apply
2164 * the function { [v] -> [v % 2^width] } to the domain and the domain
2165 * of the schedule. In order not to lose any information, we also
2166 * need to intersect the domain of the schedule with the virtual domain
2167 * first, since some iterations in the wrapped domain may be scheduled
2168 * several times, typically an infinite number of times.
2169 * Note that there is no need to perform this final wrapping
2170 * if the loop condition (after wrapping) is simple.
2172 * Wrapping on unsigned iterators can be avoided entirely if
2173 * loop condition is simple, the loop iterator is incremented
2174 * [decremented] by one and the last value before wrapping cannot
2175 * possibly satisfy the loop condition.
2177 * Before extracting a pet_scop from the body we remove all
2178 * assignments in assigned_value to variables that are assigned
2179 * somewhere in the body of the loop.
2181 * Valid parameters for a for loop are those for which the initial
2182 * value itself, the increment on each domain iteration and
2183 * the condition on both the initial value and
2184 * the result of incrementing the iterator for each iteration of the domain
2185 * can be evaluated.
2187 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2189 BinaryOperator *ass;
2190 Decl *decl;
2191 Stmt *init;
2192 Expr *lhs, *rhs;
2193 ValueDecl *iv;
2194 isl_space *dim;
2195 isl_set *domain;
2196 isl_map *sched;
2197 isl_set *cond = NULL;
2198 isl_id *id;
2199 struct pet_scop *scop;
2200 assigned_value_cache cache(assigned_value);
2201 isl_int inc;
2202 bool is_one;
2203 bool is_unsigned;
2204 bool is_simple;
2205 bool is_virtual;
2206 isl_map *wrap = NULL;
2207 isl_pw_aff *pa, *pa_inc, *init_val;
2208 isl_set *valid_init;
2209 isl_set *valid_cond;
2210 isl_set *valid_cond_init;
2211 isl_set *valid_cond_next;
2212 isl_set *valid_inc;
2214 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2215 return extract_infinite_for(stmt);
2217 init = stmt->getInit();
2218 if (!init) {
2219 unsupported(stmt);
2220 return NULL;
2222 if ((ass = initialization_assignment(init)) != NULL) {
2223 iv = extract_induction_variable(ass);
2224 if (!iv)
2225 return NULL;
2226 lhs = ass->getLHS();
2227 rhs = ass->getRHS();
2228 } else if ((decl = initialization_declaration(init)) != NULL) {
2229 VarDecl *var = extract_induction_variable(init, decl);
2230 if (!var)
2231 return NULL;
2232 iv = var;
2233 rhs = var->getInit();
2234 lhs = create_DeclRefExpr(var);
2235 } else {
2236 unsupported(stmt->getInit());
2237 return NULL;
2240 pa_inc = extract_increment(stmt, iv);
2241 if (!pa_inc)
2242 return NULL;
2244 isl_int_init(inc);
2245 if (isl_pw_aff_n_piece(pa_inc) != 1 ||
2246 isl_pw_aff_foreach_piece(pa_inc, &extract_cst, &inc) < 0) {
2247 isl_pw_aff_free(pa_inc);
2248 unsupported(stmt->getInc());
2249 isl_int_clear(inc);
2250 return NULL;
2252 valid_inc = isl_pw_aff_domain(pa_inc);
2254 is_unsigned = iv->getType()->isUnsignedIntegerType();
2256 assigned_value.erase(iv);
2257 clear_assignments clear(assigned_value);
2258 clear.TraverseStmt(stmt->getBody());
2260 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2262 scop = extract(stmt->getBody());
2264 pa = try_extract_nested_condition(stmt->getCond());
2265 if (pa && !is_nested_allowed(pa, scop)) {
2266 isl_pw_aff_free(pa);
2267 pa = NULL;
2270 if (!pa)
2271 pa = extract_condition(stmt->getCond());
2272 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2273 cond = isl_pw_aff_non_zero_set(pa);
2274 cond = embed(cond, isl_id_copy(id));
2275 valid_cond = isl_set_coalesce(valid_cond);
2276 valid_cond = embed(valid_cond, isl_id_copy(id));
2277 valid_inc = embed(valid_inc, isl_id_copy(id));
2278 is_one = isl_int_is_one(inc) || isl_int_is_negone(inc);
2279 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
2281 init_val = extract_affine(rhs);
2282 valid_cond_init = enforce_subset(
2283 isl_set_from_pw_aff(isl_pw_aff_copy(init_val)),
2284 isl_set_copy(valid_cond));
2285 if (is_one && !is_virtual) {
2286 isl_pw_aff_free(init_val);
2287 pa = extract_comparison(isl_int_is_pos(inc) ? BO_GE : BO_LE,
2288 lhs, rhs, init);
2289 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2290 valid_init = set_project_out_by_id(valid_init, id);
2291 domain = isl_pw_aff_non_zero_set(pa);
2292 } else {
2293 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
2294 domain = strided_domain(isl_id_copy(id), init_val, inc);
2297 domain = embed(domain, isl_id_copy(id));
2298 if (is_virtual) {
2299 isl_map *rev_wrap;
2300 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2301 rev_wrap = isl_map_reverse(isl_map_copy(wrap));
2302 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
2303 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
2304 valid_inc = isl_set_apply(valid_inc, rev_wrap);
2306 cond = isl_set_gist(cond, isl_set_copy(domain));
2307 is_simple = is_simple_bound(cond, inc);
2308 if (!is_simple)
2309 cond = valid_for_each_iteration(cond,
2310 isl_set_copy(domain), inc);
2311 domain = isl_set_intersect(domain, cond);
2312 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2313 dim = isl_space_from_domain(isl_set_get_space(domain));
2314 dim = isl_space_add_dims(dim, isl_dim_out, 1);
2315 sched = isl_map_universe(dim);
2316 if (isl_int_is_pos(inc))
2317 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
2318 else
2319 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
2321 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain), inc);
2322 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
2324 if (is_virtual && !is_simple) {
2325 wrap = isl_map_set_dim_id(wrap,
2326 isl_dim_out, 0, isl_id_copy(id));
2327 sched = isl_map_intersect_domain(sched, isl_set_copy(domain));
2328 domain = isl_set_apply(domain, isl_map_copy(wrap));
2329 sched = isl_map_apply_domain(sched, wrap);
2330 } else
2331 isl_map_free(wrap);
2333 scop = pet_scop_embed(scop, domain, sched, id);
2334 scop = resolve_nested(scop);
2335 clear_assignment(assigned_value, iv);
2337 isl_int_clear(inc);
2339 scop = pet_scop_restrict_context(scop, valid_init);
2340 scop = pet_scop_restrict_context(scop, valid_inc);
2341 scop = pet_scop_restrict_context(scop, valid_cond_next);
2342 scop = pet_scop_restrict_context(scop, valid_cond_init);
2344 return scop;
2347 struct pet_scop *PetScan::extract(CompoundStmt *stmt)
2349 return extract(stmt->children());
2352 /* Does "id" refer to a nested access?
2354 static bool is_nested_parameter(__isl_keep isl_id *id)
2356 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2359 /* Does parameter "pos" of "space" refer to a nested access?
2361 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2363 bool nested;
2364 isl_id *id;
2366 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2367 nested = is_nested_parameter(id);
2368 isl_id_free(id);
2370 return nested;
2373 /* Does parameter "pos" of "map" refer to a nested access?
2375 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
2377 bool nested;
2378 isl_id *id;
2380 id = isl_map_get_dim_id(map, isl_dim_param, pos);
2381 nested = is_nested_parameter(id);
2382 isl_id_free(id);
2384 return nested;
2387 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2389 static int n_nested_parameter(__isl_keep isl_space *space)
2391 int n = 0;
2392 int nparam;
2394 nparam = isl_space_dim(space, isl_dim_param);
2395 for (int i = 0; i < nparam; ++i)
2396 if (is_nested_parameter(space, i))
2397 ++n;
2399 return n;
2402 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2404 static int n_nested_parameter(__isl_keep isl_map *map)
2406 isl_space *space;
2407 int n;
2409 space = isl_map_get_space(map);
2410 n = n_nested_parameter(space);
2411 isl_space_free(space);
2413 return n;
2416 /* For each nested access parameter in "space",
2417 * construct a corresponding pet_expr, place it in args and
2418 * record its position in "param2pos".
2419 * "n_arg" is the number of elements that are already in args.
2420 * The position recorded in "param2pos" takes this number into account.
2421 * If the pet_expr corresponding to a parameter is identical to
2422 * the pet_expr corresponding to an earlier parameter, then these two
2423 * parameters are made to refer to the same element in args.
2425 * Return the final number of elements in args or -1 if an error has occurred.
2427 int PetScan::extract_nested(__isl_keep isl_space *space,
2428 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
2430 int nparam;
2432 nparam = isl_space_dim(space, isl_dim_param);
2433 for (int i = 0; i < nparam; ++i) {
2434 int j;
2435 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2436 Expr *nested;
2438 if (!is_nested_parameter(id)) {
2439 isl_id_free(id);
2440 continue;
2443 nested = (Expr *) isl_id_get_user(id);
2444 args[n_arg] = extract_expr(nested);
2445 if (!args[n_arg])
2446 return -1;
2448 for (j = 0; j < n_arg; ++j)
2449 if (pet_expr_is_equal(args[j], args[n_arg]))
2450 break;
2452 if (j < n_arg) {
2453 pet_expr_free(args[n_arg]);
2454 args[n_arg] = NULL;
2455 param2pos[i] = j;
2456 } else
2457 param2pos[i] = n_arg++;
2459 isl_id_free(id);
2462 return n_arg;
2465 /* For each nested access parameter in the access relations in "expr",
2466 * construct a corresponding pet_expr, place it in expr->args and
2467 * record its position in "param2pos".
2468 * n is the number of nested access parameters.
2470 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
2471 std::map<int,int> &param2pos)
2473 isl_space *space;
2475 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
2476 expr->n_arg = n;
2477 if (!expr->args)
2478 goto error;
2480 space = isl_map_get_space(expr->acc.access);
2481 n = extract_nested(space, 0, expr->args, param2pos);
2482 isl_space_free(space);
2484 if (n < 0)
2485 goto error;
2487 expr->n_arg = n;
2488 return expr;
2489 error:
2490 pet_expr_free(expr);
2491 return NULL;
2494 /* Look for parameters in any access relation in "expr" that
2495 * refer to nested accesses. In particular, these are
2496 * parameters with no name.
2498 * If there are any such parameters, then the domain of the access
2499 * relation, which is still [] at this point, is replaced by
2500 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2501 * (after identifying identical nested accesses).
2502 * The parameters are then equated to the corresponding t dimensions
2503 * and subsequently projected out.
2504 * param2pos maps the position of the parameter to the position
2505 * of the corresponding t dimension.
2507 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
2509 int n;
2510 int nparam;
2511 int n_in;
2512 isl_space *dim;
2513 isl_map *map;
2514 std::map<int,int> param2pos;
2516 if (!expr)
2517 return expr;
2519 for (int i = 0; i < expr->n_arg; ++i) {
2520 expr->args[i] = resolve_nested(expr->args[i]);
2521 if (!expr->args[i]) {
2522 pet_expr_free(expr);
2523 return NULL;
2527 if (expr->type != pet_expr_access)
2528 return expr;
2530 n = n_nested_parameter(expr->acc.access);
2531 if (n == 0)
2532 return expr;
2534 expr = extract_nested(expr, n, param2pos);
2535 if (!expr)
2536 return NULL;
2538 n = expr->n_arg;
2539 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
2540 n_in = isl_map_dim(expr->acc.access, isl_dim_in);
2541 dim = isl_map_get_space(expr->acc.access);
2542 dim = isl_space_domain(dim);
2543 dim = isl_space_from_domain(dim);
2544 dim = isl_space_add_dims(dim, isl_dim_out, n);
2545 map = isl_map_universe(dim);
2546 map = isl_map_domain_map(map);
2547 map = isl_map_reverse(map);
2548 expr->acc.access = isl_map_apply_domain(expr->acc.access, map);
2550 for (int i = nparam - 1; i >= 0; --i) {
2551 isl_id *id = isl_map_get_dim_id(expr->acc.access,
2552 isl_dim_param, i);
2553 if (!is_nested_parameter(id)) {
2554 isl_id_free(id);
2555 continue;
2558 expr->acc.access = isl_map_equate(expr->acc.access,
2559 isl_dim_param, i, isl_dim_in,
2560 n_in + param2pos[i]);
2561 expr->acc.access = isl_map_project_out(expr->acc.access,
2562 isl_dim_param, i, 1);
2564 isl_id_free(id);
2567 return expr;
2568 error:
2569 pet_expr_free(expr);
2570 return NULL;
2573 /* Convert a top-level pet_expr to a pet_scop with one statement.
2574 * This mainly involves resolving nested expression parameters
2575 * and setting the name of the iteration space.
2576 * The name is given by "label" if it is non-NULL. Otherwise,
2577 * it is of the form S_<n_stmt>.
2579 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
2580 __isl_take isl_id *label)
2582 struct pet_stmt *ps;
2583 SourceLocation loc = stmt->getLocStart();
2584 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2586 expr = resolve_nested(expr);
2587 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
2588 return pet_scop_from_pet_stmt(ctx, ps);
2591 /* Check if we can extract an affine expression from "expr".
2592 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
2593 * We turn on autodetection so that we won't generate any warnings
2594 * and turn off nesting, so that we won't accept any non-affine constructs.
2596 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
2598 isl_pw_aff *pwaff;
2599 int save_autodetect = autodetect;
2600 bool save_nesting = nesting_enabled;
2602 autodetect = 1;
2603 nesting_enabled = false;
2605 pwaff = extract_affine(expr);
2607 autodetect = save_autodetect;
2608 nesting_enabled = save_nesting;
2610 return pwaff;
2613 /* Check whether "expr" is an affine expression.
2615 bool PetScan::is_affine(Expr *expr)
2617 isl_pw_aff *pwaff;
2619 pwaff = try_extract_affine(expr);
2620 isl_pw_aff_free(pwaff);
2622 return pwaff != NULL;
2625 /* Check whether "expr" is an affine constraint.
2626 * We turn on autodetection so that we won't generate any warnings
2627 * and turn off nesting, so that we won't accept any non-affine constructs.
2629 bool PetScan::is_affine_condition(Expr *expr)
2631 isl_pw_aff *cond;
2632 int save_autodetect = autodetect;
2633 bool save_nesting = nesting_enabled;
2635 autodetect = 1;
2636 nesting_enabled = false;
2638 cond = extract_condition(expr);
2639 isl_pw_aff_free(cond);
2641 autodetect = save_autodetect;
2642 nesting_enabled = save_nesting;
2644 return cond != NULL;
2647 /* Check if we can extract a condition from "expr".
2648 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
2649 * If allow_nested is set, then the condition may involve parameters
2650 * corresponding to nested accesses.
2651 * We turn on autodetection so that we won't generate any warnings.
2653 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
2655 isl_pw_aff *cond;
2656 int save_autodetect = autodetect;
2657 bool save_nesting = nesting_enabled;
2659 autodetect = 1;
2660 nesting_enabled = allow_nested;
2661 cond = extract_condition(expr);
2663 autodetect = save_autodetect;
2664 nesting_enabled = save_nesting;
2666 return cond;
2669 /* If the top-level expression of "stmt" is an assignment, then
2670 * return that assignment as a BinaryOperator.
2671 * Otherwise return NULL.
2673 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
2675 BinaryOperator *ass;
2677 if (!stmt)
2678 return NULL;
2679 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
2680 return NULL;
2682 ass = cast<BinaryOperator>(stmt);
2683 if(ass->getOpcode() != BO_Assign)
2684 return NULL;
2686 return ass;
2689 /* Check if the given if statement is a conditional assignement
2690 * with a non-affine condition. If so, construct a pet_scop
2691 * corresponding to this conditional assignment. Otherwise return NULL.
2693 * In particular we check if "stmt" is of the form
2695 * if (condition)
2696 * a = f(...);
2697 * else
2698 * a = g(...);
2700 * where a is some array or scalar access.
2701 * The constructed pet_scop then corresponds to the expression
2703 * a = condition ? f(...) : g(...)
2705 * All access relations in f(...) are intersected with condition
2706 * while all access relation in g(...) are intersected with the complement.
2708 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
2710 BinaryOperator *ass_then, *ass_else;
2711 isl_map *write_then, *write_else;
2712 isl_set *cond, *comp;
2713 isl_map *map;
2714 isl_pw_aff *pa;
2715 int equal;
2716 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
2717 bool save_nesting = nesting_enabled;
2719 ass_then = top_assignment_or_null(stmt->getThen());
2720 ass_else = top_assignment_or_null(stmt->getElse());
2722 if (!ass_then || !ass_else)
2723 return NULL;
2725 if (is_affine_condition(stmt->getCond()))
2726 return NULL;
2728 write_then = extract_access(ass_then->getLHS());
2729 write_else = extract_access(ass_else->getLHS());
2731 equal = isl_map_is_equal(write_then, write_else);
2732 isl_map_free(write_else);
2733 if (equal < 0 || !equal) {
2734 isl_map_free(write_then);
2735 return NULL;
2738 nesting_enabled = allow_nested;
2739 pa = extract_condition(stmt->getCond());
2740 nesting_enabled = save_nesting;
2741 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
2742 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
2743 map = isl_map_from_range(isl_set_from_pw_aff(pa));
2745 pe_cond = pet_expr_from_access(map);
2747 pe_then = extract_expr(ass_then->getRHS());
2748 pe_then = pet_expr_restrict(pe_then, cond);
2749 pe_else = extract_expr(ass_else->getRHS());
2750 pe_else = pet_expr_restrict(pe_else, comp);
2752 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
2753 pe_write = pet_expr_from_access(write_then);
2754 if (pe_write) {
2755 pe_write->acc.write = 1;
2756 pe_write->acc.read = 0;
2758 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
2759 return extract(stmt, pe);
2762 /* Create an access to a virtual array representing the result
2763 * of a condition.
2764 * Unlike other accessed data, the id of the array is NULL as
2765 * there is no ValueDecl in the program corresponding to the virtual
2766 * array.
2767 * The array starts out as a scalar, but grows along with the
2768 * statement writing to the array in pet_scop_embed.
2770 static __isl_give isl_map *create_test_access(isl_ctx *ctx, int test_nr)
2772 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2773 isl_id *id;
2774 char name[50];
2776 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2777 id = isl_id_alloc(ctx, name, NULL);
2778 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2779 return isl_map_universe(dim);
2782 /* Create a pet_scop with a single statement evaluating "cond"
2783 * and writing the result to a virtual scalar, as expressed by
2784 * "access".
2786 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond,
2787 __isl_take isl_map *access)
2789 struct pet_expr *expr, *write;
2790 struct pet_stmt *ps;
2791 SourceLocation loc = cond->getLocStart();
2792 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2794 write = pet_expr_from_access(access);
2795 if (write) {
2796 write->acc.write = 1;
2797 write->acc.read = 0;
2799 expr = extract_expr(cond);
2800 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
2801 ps = pet_stmt_from_pet_expr(ctx, line, NULL, n_stmt++, expr);
2802 return pet_scop_from_pet_stmt(ctx, ps);
2805 /* Add an array with the given extent ("access") to the list
2806 * of arrays in "scop" and return the extended pet_scop.
2807 * The array is marked as attaining values 0 and 1 only.
2809 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2810 __isl_keep isl_map *access, clang::ASTContext &ast_ctx)
2812 isl_ctx *ctx = isl_map_get_ctx(access);
2813 isl_space *dim;
2814 struct pet_array **arrays;
2815 struct pet_array *array;
2817 if (!scop)
2818 return NULL;
2819 if (!ctx)
2820 goto error;
2822 arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2823 scop->n_array + 1);
2824 if (!arrays)
2825 goto error;
2826 scop->arrays = arrays;
2828 array = isl_calloc_type(ctx, struct pet_array);
2829 if (!array)
2830 goto error;
2832 array->extent = isl_map_range(isl_map_copy(access));
2833 dim = isl_space_params_alloc(ctx, 0);
2834 array->context = isl_set_universe(dim);
2835 dim = isl_space_set_alloc(ctx, 0, 1);
2836 array->value_bounds = isl_set_universe(dim);
2837 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2838 isl_dim_set, 0, 0);
2839 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2840 isl_dim_set, 0, 1);
2841 array->element_type = strdup("int");
2842 array->element_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2844 scop->arrays[scop->n_array] = array;
2845 scop->n_array++;
2847 if (!array->extent || !array->context)
2848 goto error;
2850 return scop;
2851 error:
2852 pet_scop_free(scop);
2853 return NULL;
2856 extern "C" {
2857 static __isl_give isl_map *embed_access(__isl_take isl_map *access,
2858 void *user);
2861 /* Apply the map pointed to by "user" to the domain of the access
2862 * relation, thereby embedding it in the range of the map.
2863 * The domain of both relations is the zero-dimensional domain.
2865 static __isl_give isl_map *embed_access(__isl_take isl_map *access, void *user)
2867 isl_map *map = (isl_map *) user;
2869 return isl_map_apply_domain(access, isl_map_copy(map));
2872 /* Apply "map" to all access relations in "expr".
2874 static struct pet_expr *embed(struct pet_expr *expr, __isl_keep isl_map *map)
2876 return pet_expr_foreach_access(expr, &embed_access, map);
2879 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
2881 static int n_nested_parameter(__isl_keep isl_set *set)
2883 isl_space *space;
2884 int n;
2886 space = isl_set_get_space(set);
2887 n = n_nested_parameter(space);
2888 isl_space_free(space);
2890 return n;
2893 /* Remove all parameters from "map" that refer to nested accesses.
2895 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
2897 int nparam;
2898 isl_space *space;
2900 space = isl_map_get_space(map);
2901 nparam = isl_space_dim(space, isl_dim_param);
2902 for (int i = nparam - 1; i >= 0; --i)
2903 if (is_nested_parameter(space, i))
2904 map = isl_map_project_out(map, isl_dim_param, i, 1);
2905 isl_space_free(space);
2907 return map;
2910 extern "C" {
2911 static __isl_give isl_map *access_remove_nested_parameters(
2912 __isl_take isl_map *access, void *user);
2915 static __isl_give isl_map *access_remove_nested_parameters(
2916 __isl_take isl_map *access, void *user)
2918 return remove_nested_parameters(access);
2921 /* Remove all nested access parameters from the schedule and all
2922 * accesses of "stmt".
2923 * There is no need to remove them from the domain as these parameters
2924 * have already been removed from the domain when this function is called.
2926 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
2928 if (!stmt)
2929 return NULL;
2930 stmt->schedule = remove_nested_parameters(stmt->schedule);
2931 stmt->body = pet_expr_foreach_access(stmt->body,
2932 &access_remove_nested_parameters, NULL);
2933 if (!stmt->schedule || !stmt->body)
2934 goto error;
2935 for (int i = 0; i < stmt->n_arg; ++i) {
2936 stmt->args[i] = pet_expr_foreach_access(stmt->args[i],
2937 &access_remove_nested_parameters, NULL);
2938 if (!stmt->args[i])
2939 goto error;
2942 return stmt;
2943 error:
2944 pet_stmt_free(stmt);
2945 return NULL;
2948 /* For each nested access parameter in the domain of "stmt",
2949 * construct a corresponding pet_expr, place it in stmt->args and
2950 * record its position in "param2pos".
2951 * n is the number of nested access parameters.
2953 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
2954 std::map<int,int> &param2pos)
2956 isl_space *space;
2957 unsigned n_arg;
2958 struct pet_expr **args;
2960 n_arg = stmt->n_arg;
2961 args = isl_realloc_array(ctx, stmt->args, struct pet_expr *, n_arg + n);
2962 if (!args)
2963 goto error;
2964 stmt->args = args;
2965 stmt->n_arg += n;
2967 space = isl_set_get_space(stmt->domain);
2968 n = extract_nested(space, n_arg, stmt->args, param2pos);
2969 isl_space_free(space);
2971 if (n < 0)
2972 goto error;
2974 stmt->n_arg = n;
2975 return stmt;
2976 error:
2977 pet_stmt_free(stmt);
2978 return NULL;
2981 /* Look for parameters in the iteration domain of "stmt" that
2982 * refer to nested accesses. In particular, these are
2983 * parameters with no name.
2985 * If there are any such parameters, then as many extra variables
2986 * (after identifying identical nested accesses) are added to the
2987 * range of the map wrapped inside the domain.
2988 * If the original domain is not a wrapped map, then a new wrapped
2989 * map is created with zero output dimensions.
2990 * The parameters are then equated to the corresponding output dimensions
2991 * and subsequently projected out, from the iteration domain,
2992 * the schedule and the access relations.
2993 * For each of the output dimensions, a corresponding argument
2994 * expression is added. Initially they are created with
2995 * a zero-dimensional domain, so they have to be embedded
2996 * in the current iteration domain.
2997 * param2pos maps the position of the parameter to the position
2998 * of the corresponding output dimension in the wrapped map.
3000 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3002 int n;
3003 int nparam;
3004 unsigned n_arg;
3005 isl_map *map;
3006 std::map<int,int> param2pos;
3008 if (!stmt)
3009 return NULL;
3011 n = n_nested_parameter(stmt->domain);
3012 if (n == 0)
3013 return stmt;
3015 n_arg = stmt->n_arg;
3016 stmt = extract_nested(stmt, n, param2pos);
3017 if (!stmt)
3018 return NULL;
3020 n = stmt->n_arg - n_arg;
3021 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3022 if (isl_set_is_wrapping(stmt->domain))
3023 map = isl_set_unwrap(stmt->domain);
3024 else
3025 map = isl_map_from_domain(stmt->domain);
3026 map = isl_map_add_dims(map, isl_dim_out, n);
3028 for (int i = nparam - 1; i >= 0; --i) {
3029 isl_id *id;
3031 if (!is_nested_parameter(map, i))
3032 continue;
3034 id = isl_map_get_tuple_id(stmt->args[param2pos[i]]->acc.access,
3035 isl_dim_out);
3036 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3037 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3038 param2pos[i]);
3039 map = isl_map_project_out(map, isl_dim_param, i, 1);
3042 stmt->domain = isl_map_wrap(map);
3044 map = isl_set_unwrap(isl_set_copy(stmt->domain));
3045 map = isl_map_from_range(isl_map_domain(map));
3046 for (int pos = n_arg; pos < stmt->n_arg; ++pos)
3047 stmt->args[pos] = embed(stmt->args[pos], map);
3048 isl_map_free(map);
3050 stmt = remove_nested_parameters(stmt);
3052 return stmt;
3053 error:
3054 pet_stmt_free(stmt);
3055 return NULL;
3058 /* For each statement in "scop", move the parameters that correspond
3059 * to nested access into the ranges of the domains and create
3060 * corresponding argument expressions.
3062 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3064 if (!scop)
3065 return NULL;
3067 for (int i = 0; i < scop->n_stmt; ++i) {
3068 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3069 if (!scop->stmts[i])
3070 goto error;
3073 return scop;
3074 error:
3075 pet_scop_free(scop);
3076 return NULL;
3079 /* Does "space" involve any parameters that refer to nested
3080 * accesses, i.e., parameters with no name?
3082 static bool has_nested(__isl_keep isl_space *space)
3084 int nparam;
3086 nparam = isl_space_dim(space, isl_dim_param);
3087 for (int i = 0; i < nparam; ++i)
3088 if (is_nested_parameter(space, i))
3089 return true;
3091 return false;
3094 /* Does "pa" involve any parameters that refer to nested
3095 * accesses, i.e., parameters with no name?
3097 static bool has_nested(__isl_keep isl_pw_aff *pa)
3099 isl_space *space;
3100 bool nested;
3102 space = isl_pw_aff_get_space(pa);
3103 nested = has_nested(space);
3104 isl_space_free(space);
3106 return nested;
3109 /* Given an access expression "expr", is the variable accessed by
3110 * "expr" assigned anywhere inside "scop"?
3112 static bool is_assigned(pet_expr *expr, pet_scop *scop)
3114 bool assigned = false;
3115 isl_id *id;
3117 id = isl_map_get_tuple_id(expr->acc.access, isl_dim_out);
3118 assigned = pet_scop_writes(scop, id);
3119 isl_id_free(id);
3121 return assigned;
3124 /* Are all nested access parameters in "pa" allowed given "scop".
3125 * In particular, is none of them written by anywhere inside "scop".
3127 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3129 int nparam;
3131 nparam = isl_pw_aff_dim(pa, isl_dim_param);
3132 for (int i = 0; i < nparam; ++i) {
3133 Expr *nested;
3134 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
3135 pet_expr *expr;
3136 bool allowed;
3138 if (!is_nested_parameter(id)) {
3139 isl_id_free(id);
3140 continue;
3143 nested = (Expr *) isl_id_get_user(id);
3144 expr = extract_expr(nested);
3145 allowed = expr && expr->type == pet_expr_access &&
3146 !is_assigned(expr, scop);
3148 pet_expr_free(expr);
3149 isl_id_free(id);
3151 if (!allowed)
3152 return false;
3155 return true;
3158 /* Construct a pet_scop for an if statement.
3160 * If the condition fits the pattern of a conditional assignment,
3161 * then it is handled by extract_conditional_assignment.
3162 * Otherwise, we do the following.
3164 * If the condition is affine, then the condition is added
3165 * to the iteration domains of the then branch, while the
3166 * opposite of the condition in added to the iteration domains
3167 * of the else branch, if any.
3168 * We allow the condition to be dynamic, i.e., to refer to
3169 * scalars or array elements that may be written to outside
3170 * of the given if statement. These nested accesses are then represented
3171 * as output dimensions in the wrapping iteration domain.
3172 * If it also written _inside_ the then or else branch, then
3173 * we treat the condition as non-affine.
3174 * As explained below, this will introduce an extra statement.
3175 * For aesthetic reasons, we want this statement to have a statement
3176 * number that is lower than those of the then and else branches.
3177 * In order to evaluate if will need such a statement, however, we
3178 * first construct scops for the then and else branches.
3179 * We therefore reserve a statement number if we might have to
3180 * introduce such an extra statement.
3182 * If the condition is not affine, then we create a separate
3183 * statement that writes the result of the condition to a virtual scalar.
3184 * A constraint requiring the value of this virtual scalar to be one
3185 * is added to the iteration domains of the then branch.
3186 * Similarly, a constraint requiring the value of this virtual scalar
3187 * to be zero is added to the iteration domains of the else branch, if any.
3188 * We adjust the schedules to ensure that the virtual scalar is written
3189 * before it is read.
3191 struct pet_scop *PetScan::extract(IfStmt *stmt)
3193 struct pet_scop *scop_then, *scop_else, *scop;
3194 assigned_value_cache cache(assigned_value);
3195 isl_map *test_access = NULL;
3196 isl_pw_aff *cond;
3197 int stmt_id;
3199 scop = extract_conditional_assignment(stmt);
3200 if (scop)
3201 return scop;
3203 cond = try_extract_nested_condition(stmt->getCond());
3204 if (allow_nested && (!cond || has_nested(cond)))
3205 stmt_id = n_stmt++;
3207 scop_then = extract(stmt->getThen());
3209 if (stmt->getElse()) {
3210 scop_else = extract(stmt->getElse());
3211 if (autodetect) {
3212 if (scop_then && !scop_else) {
3213 partial = true;
3214 isl_pw_aff_free(cond);
3215 return scop_then;
3217 if (!scop_then && scop_else) {
3218 partial = true;
3219 isl_pw_aff_free(cond);
3220 return scop_else;
3225 if (cond &&
3226 (!is_nested_allowed(cond, scop_then) ||
3227 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
3228 isl_pw_aff_free(cond);
3229 cond = NULL;
3231 if (allow_nested && !cond) {
3232 int save_n_stmt = n_stmt;
3233 test_access = create_test_access(ctx, n_test++);
3234 n_stmt = stmt_id;
3235 scop = extract_non_affine_condition(stmt->getCond(),
3236 isl_map_copy(test_access));
3237 n_stmt = save_n_stmt;
3238 scop = scop_add_array(scop, test_access, ast_context);
3239 if (!scop) {
3240 pet_scop_free(scop_then);
3241 pet_scop_free(scop_else);
3242 isl_map_free(test_access);
3243 return NULL;
3247 if (!scop) {
3248 isl_set *set;
3249 isl_set *valid;
3251 if (!cond)
3252 cond = extract_condition(stmt->getCond());
3253 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
3254 set = isl_pw_aff_non_zero_set(cond);
3255 scop = pet_scop_restrict(scop_then, isl_set_copy(set));
3257 if (stmt->getElse()) {
3258 set = isl_set_subtract(isl_set_copy(valid), set);
3259 scop_else = pet_scop_restrict(scop_else, set);
3260 scop = pet_scop_add(ctx, scop, scop_else);
3261 } else
3262 isl_set_free(set);
3263 scop = resolve_nested(scop);
3264 scop = pet_scop_restrict_context(scop, valid);
3265 } else {
3266 scop = pet_scop_prefix(scop, 0);
3267 scop_then = pet_scop_prefix(scop_then, 1);
3268 scop_then = pet_scop_filter(scop_then,
3269 isl_map_copy(test_access), 1);
3270 scop = pet_scop_add(ctx, scop, scop_then);
3271 if (stmt->getElse()) {
3272 scop_else = pet_scop_prefix(scop_else, 1);
3273 scop_else = pet_scop_filter(scop_else, test_access, 0);
3274 scop = pet_scop_add(ctx, scop, scop_else);
3275 } else
3276 isl_map_free(test_access);
3279 return scop;
3282 /* Try and construct a pet_scop for a label statement.
3283 * We currently only allow labels on expression statements.
3285 struct pet_scop *PetScan::extract(LabelStmt *stmt)
3287 isl_id *label;
3288 Stmt *sub;
3290 sub = stmt->getSubStmt();
3291 if (!isa<Expr>(sub)) {
3292 unsupported(stmt);
3293 return NULL;
3296 label = isl_id_alloc(ctx, stmt->getName(), NULL);
3298 return extract(sub, extract_expr(cast<Expr>(sub)), label);
3301 /* Try and construct a pet_scop corresponding to "stmt".
3303 struct pet_scop *PetScan::extract(Stmt *stmt)
3305 if (isa<Expr>(stmt))
3306 return extract(stmt, extract_expr(cast<Expr>(stmt)));
3308 switch (stmt->getStmtClass()) {
3309 case Stmt::WhileStmtClass:
3310 return extract(cast<WhileStmt>(stmt));
3311 case Stmt::ForStmtClass:
3312 return extract_for(cast<ForStmt>(stmt));
3313 case Stmt::IfStmtClass:
3314 return extract(cast<IfStmt>(stmt));
3315 case Stmt::CompoundStmtClass:
3316 return extract(cast<CompoundStmt>(stmt));
3317 case Stmt::LabelStmtClass:
3318 return extract(cast<LabelStmt>(stmt));
3319 default:
3320 unsupported(stmt);
3323 return NULL;
3326 /* Try and construct a pet_scop corresponding to (part of)
3327 * a sequence of statements.
3329 struct pet_scop *PetScan::extract(StmtRange stmt_range)
3331 pet_scop *scop;
3332 StmtIterator i;
3333 int j;
3334 bool partial_range = false;
3336 scop = pet_scop_empty(ctx);
3337 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
3338 Stmt *child = *i;
3339 struct pet_scop *scop_i;
3340 scop_i = extract(child);
3341 if (scop && partial) {
3342 pet_scop_free(scop_i);
3343 break;
3345 scop_i = pet_scop_prefix(scop_i, j);
3346 if (autodetect) {
3347 if (scop_i)
3348 scop = pet_scop_add(ctx, scop, scop_i);
3349 else
3350 partial_range = true;
3351 if (scop->n_stmt != 0 && !scop_i)
3352 partial = true;
3353 } else {
3354 scop = pet_scop_add(ctx, scop, scop_i);
3356 if (partial)
3357 break;
3360 if (scop && partial_range)
3361 partial = true;
3363 return scop;
3366 /* Check if the scop marked by the user is exactly this Stmt
3367 * or part of this Stmt.
3368 * If so, return a pet_scop corresponding to the marked region.
3369 * Otherwise, return NULL.
3371 struct pet_scop *PetScan::scan(Stmt *stmt)
3373 SourceManager &SM = PP.getSourceManager();
3374 unsigned start_off, end_off;
3376 start_off = SM.getFileOffset(stmt->getLocStart());
3377 end_off = SM.getFileOffset(stmt->getLocEnd());
3379 if (start_off > loc.end)
3380 return NULL;
3381 if (end_off < loc.start)
3382 return NULL;
3383 if (start_off >= loc.start && end_off <= loc.end) {
3384 return extract(stmt);
3387 StmtIterator start;
3388 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
3389 Stmt *child = *start;
3390 if (!child)
3391 continue;
3392 start_off = SM.getFileOffset(child->getLocStart());
3393 end_off = SM.getFileOffset(child->getLocEnd());
3394 if (start_off < loc.start && end_off > loc.end)
3395 return scan(child);
3396 if (start_off >= loc.start)
3397 break;
3400 StmtIterator end;
3401 for (end = start; end != stmt->child_end(); ++end) {
3402 Stmt *child = *end;
3403 start_off = SM.getFileOffset(child->getLocStart());
3404 if (start_off >= loc.end)
3405 break;
3408 return extract(StmtRange(start, end));
3411 /* Set the size of index "pos" of "array" to "size".
3412 * In particular, add a constraint of the form
3414 * i_pos < size
3416 * to array->extent and a constraint of the form
3418 * size >= 0
3420 * to array->context.
3422 static struct pet_array *update_size(struct pet_array *array, int pos,
3423 __isl_take isl_pw_aff *size)
3425 isl_set *valid;
3426 isl_set *univ;
3427 isl_set *bound;
3428 isl_space *dim;
3429 isl_aff *aff;
3430 isl_pw_aff *index;
3431 isl_id *id;
3433 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
3434 array->context = isl_set_intersect(array->context, valid);
3436 dim = isl_set_get_space(array->extent);
3437 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
3438 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
3439 univ = isl_set_universe(isl_aff_get_domain_space(aff));
3440 index = isl_pw_aff_alloc(univ, aff);
3442 size = isl_pw_aff_add_dims(size, isl_dim_in,
3443 isl_set_dim(array->extent, isl_dim_set));
3444 id = isl_set_get_tuple_id(array->extent);
3445 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
3446 bound = isl_pw_aff_lt_set(index, size);
3448 array->extent = isl_set_intersect(array->extent, bound);
3450 if (!array->context || !array->extent)
3451 goto error;
3453 return array;
3454 error:
3455 pet_array_free(array);
3456 return NULL;
3459 /* Figure out the size of the array at position "pos" and all
3460 * subsequent positions from "type" and update "array" accordingly.
3462 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
3463 const Type *type, int pos)
3465 const ArrayType *atype;
3466 isl_pw_aff *size;
3468 if (!array)
3469 return NULL;
3471 if (type->isPointerType()) {
3472 type = type->getPointeeType().getTypePtr();
3473 return set_upper_bounds(array, type, pos + 1);
3475 if (!type->isArrayType())
3476 return array;
3478 type = type->getCanonicalTypeInternal().getTypePtr();
3479 atype = cast<ArrayType>(type);
3481 if (type->isConstantArrayType()) {
3482 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
3483 size = extract_affine(ca->getSize());
3484 array = update_size(array, pos, size);
3485 } else if (type->isVariableArrayType()) {
3486 const VariableArrayType *vla = cast<VariableArrayType>(atype);
3487 size = extract_affine(vla->getSizeExpr());
3488 array = update_size(array, pos, size);
3491 type = atype->getElementType().getTypePtr();
3493 return set_upper_bounds(array, type, pos + 1);
3496 /* Construct and return a pet_array corresponding to the variable "decl".
3497 * In particular, initialize array->extent to
3499 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
3501 * and then call set_upper_bounds to set the upper bounds on the indices
3502 * based on the type of the variable.
3504 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl)
3506 struct pet_array *array;
3507 QualType qt = decl->getType();
3508 const Type *type = qt.getTypePtr();
3509 int depth = array_depth(type);
3510 QualType base = base_type(qt);
3511 string name;
3512 isl_id *id;
3513 isl_space *dim;
3515 array = isl_calloc_type(ctx, struct pet_array);
3516 if (!array)
3517 return NULL;
3519 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
3520 dim = isl_space_set_alloc(ctx, 0, depth);
3521 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
3523 array->extent = isl_set_nat_universe(dim);
3525 dim = isl_space_params_alloc(ctx, 0);
3526 array->context = isl_set_universe(dim);
3528 array = set_upper_bounds(array, type, 0);
3529 if (!array)
3530 return NULL;
3532 name = base.getAsString();
3533 array->element_type = strdup(name.c_str());
3534 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
3536 return array;
3539 /* Construct a list of pet_arrays, one for each array (or scalar)
3540 * accessed inside "scop" add this list to "scop" and return the result.
3542 * The context of "scop" is updated with the intesection of
3543 * the contexts of all arrays, i.e., constraints on the parameters
3544 * that ensure that the arrays have a valid (non-negative) size.
3546 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
3548 int i;
3549 set<ValueDecl *> arrays;
3550 set<ValueDecl *>::iterator it;
3551 int n_array;
3552 struct pet_array **scop_arrays;
3554 if (!scop)
3555 return NULL;
3557 pet_scop_collect_arrays(scop, arrays);
3558 if (arrays.size() == 0)
3559 return scop;
3561 n_array = scop->n_array;
3563 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
3564 n_array + arrays.size());
3565 if (!scop_arrays)
3566 goto error;
3567 scop->arrays = scop_arrays;
3569 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
3570 struct pet_array *array;
3571 scop->arrays[n_array + i] = array = extract_array(ctx, *it);
3572 if (!scop->arrays[n_array + i])
3573 goto error;
3574 scop->n_array++;
3575 scop->context = isl_set_intersect(scop->context,
3576 isl_set_copy(array->context));
3577 if (!scop->context)
3578 goto error;
3581 return scop;
3582 error:
3583 pet_scop_free(scop);
3584 return NULL;
3587 /* Bound all parameters in scop->context to the possible values
3588 * of the corresponding C variable.
3590 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
3592 int n;
3594 if (!scop)
3595 return NULL;
3597 n = isl_set_dim(scop->context, isl_dim_param);
3598 for (int i = 0; i < n; ++i) {
3599 isl_id *id;
3600 ValueDecl *decl;
3602 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
3603 decl = (ValueDecl *) isl_id_get_user(id);
3604 isl_id_free(id);
3606 scop->context = set_parameter_bounds(scop->context, i, decl);
3608 if (!scop->context)
3609 goto error;
3612 return scop;
3613 error:
3614 pet_scop_free(scop);
3615 return NULL;
3618 /* Construct a pet_scop from the given function.
3620 struct pet_scop *PetScan::scan(FunctionDecl *fd)
3622 pet_scop *scop;
3623 Stmt *stmt;
3625 stmt = fd->getBody();
3627 if (autodetect)
3628 scop = extract(stmt);
3629 else
3630 scop = scan(stmt);
3631 scop = pet_scop_detect_parameter_accesses(scop);
3632 scop = scan_arrays(scop);
3633 scop = add_parameter_bounds(scop);
3634 scop = pet_scop_gist(scop, value_bounds);
3636 return scop;