scan.cc: fix typos in comments
[pet.git] / scan.cc
blob35b44ca7f69ca88fde8d19041a011b136be7d073
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 "options.h"
48 #include "scan.h"
49 #include "scop.h"
50 #include "scop_plus.h"
52 #include "config.h"
54 using namespace std;
55 using namespace clang;
57 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
58 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
60 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
61 SourceLocation(), var, false, var->getInnerLocStart(),
62 var->getType(), VK_LValue);
64 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
65 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
67 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
68 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
69 VK_LValue);
71 #else
72 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
74 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
75 var, var->getInnerLocStart(), var->getType(), VK_LValue);
77 #endif
79 /* Check if the element type corresponding to the given array type
80 * has a const qualifier.
82 static bool const_base(QualType qt)
84 const Type *type = qt.getTypePtr();
86 if (type->isPointerType())
87 return const_base(type->getPointeeType());
88 if (type->isArrayType()) {
89 const ArrayType *atype;
90 type = type->getCanonicalTypeInternal().getTypePtr();
91 atype = cast<ArrayType>(type);
92 return const_base(atype->getElementType());
95 return qt.isConstQualified();
98 /* Mark "decl" as having an unknown value in "assigned_value".
100 * If no (known or unknown) value was assigned to "decl" before,
101 * then it may have been treated as a parameter before and may
102 * therefore appear in a value assigned to another variable.
103 * If so, this assignment needs to be turned into an unknown value too.
105 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
106 ValueDecl *decl)
108 map<ValueDecl *, isl_pw_aff *>::iterator it;
110 it = assigned_value.find(decl);
112 assigned_value[decl] = NULL;
114 if (it == assigned_value.end())
115 return;
117 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
118 isl_pw_aff *pa = it->second;
119 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
121 for (int i = 0; i < nparam; ++i) {
122 isl_id *id;
124 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
125 continue;
126 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
127 if (isl_id_get_user(id) == decl)
128 it->second = NULL;
129 isl_id_free(id);
134 /* Look for any assignments to scalar variables in part of the parse
135 * tree and set assigned_value to NULL for each of them.
136 * Also reset assigned_value if the address of a scalar variable
137 * is being taken. As an exception, if the address is passed to a function
138 * that is declared to receive a const pointer, then assigned_value is
139 * not reset.
141 * This ensures that we won't use any previously stored value
142 * in the current subtree and its parents.
144 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
145 map<ValueDecl *, isl_pw_aff *> &assigned_value;
146 set<UnaryOperator *> skip;
148 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
149 assigned_value(assigned_value) {}
151 /* Check for "address of" operators whose value is passed
152 * to a const pointer argument and add them to "skip", so that
153 * we can skip them in VisitUnaryOperator.
155 bool VisitCallExpr(CallExpr *expr) {
156 FunctionDecl *fd;
157 fd = expr->getDirectCallee();
158 if (!fd)
159 return true;
160 for (int i = 0; i < expr->getNumArgs(); ++i) {
161 Expr *arg = expr->getArg(i);
162 UnaryOperator *op;
163 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
164 ImplicitCastExpr *ice;
165 ice = cast<ImplicitCastExpr>(arg);
166 arg = ice->getSubExpr();
168 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
169 continue;
170 op = cast<UnaryOperator>(arg);
171 if (op->getOpcode() != UO_AddrOf)
172 continue;
173 if (const_base(fd->getParamDecl(i)->getType()))
174 skip.insert(op);
176 return true;
179 bool VisitUnaryOperator(UnaryOperator *expr) {
180 Expr *arg;
181 DeclRefExpr *ref;
182 ValueDecl *decl;
184 if (expr->getOpcode() != UO_AddrOf)
185 return true;
186 if (skip.find(expr) != skip.end())
187 return true;
189 arg = expr->getSubExpr();
190 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
191 return true;
192 ref = cast<DeclRefExpr>(arg);
193 decl = ref->getDecl();
194 clear_assignment(assigned_value, decl);
195 return true;
198 bool VisitBinaryOperator(BinaryOperator *expr) {
199 Expr *lhs;
200 DeclRefExpr *ref;
201 ValueDecl *decl;
203 if (!expr->isAssignmentOp())
204 return true;
205 lhs = expr->getLHS();
206 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
207 return true;
208 ref = cast<DeclRefExpr>(lhs);
209 decl = ref->getDecl();
210 clear_assignment(assigned_value, decl);
211 return true;
215 /* Keep a copy of the currently assigned values.
217 * Any variable that is assigned a value inside the current scope
218 * is removed again when we leave the scope (either because it wasn't
219 * stored in the cache or because it has a different value in the cache).
221 struct assigned_value_cache {
222 map<ValueDecl *, isl_pw_aff *> &assigned_value;
223 map<ValueDecl *, isl_pw_aff *> cache;
225 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
226 assigned_value(assigned_value), cache(assigned_value) {}
227 ~assigned_value_cache() {
228 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
229 for (it = assigned_value.begin(); it != assigned_value.end();
230 ++it) {
231 if (!it->second ||
232 (cache.find(it->first) != cache.end() &&
233 cache[it->first] != it->second))
234 cache[it->first] = NULL;
236 assigned_value = cache;
240 /* Insert an expression into the collection of expressions,
241 * provided it is not already in there.
242 * The isl_pw_affs are freed in the destructor.
244 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
246 std::set<isl_pw_aff *>::iterator it;
248 if (expressions.find(expr) == expressions.end())
249 expressions.insert(expr);
250 else
251 isl_pw_aff_free(expr);
254 PetScan::~PetScan()
256 std::set<isl_pw_aff *>::iterator it;
258 for (it = expressions.begin(); it != expressions.end(); ++it)
259 isl_pw_aff_free(*it);
261 isl_union_map_free(value_bounds);
264 /* Called if we found something we (currently) cannot handle.
265 * We'll provide more informative warnings later.
267 * We only actually complain if autodetect is false.
269 void PetScan::unsupported(Stmt *stmt, const char *msg)
271 if (options->autodetect)
272 return;
274 SourceLocation loc = stmt->getLocStart();
275 DiagnosticsEngine &diag = PP.getDiagnostics();
276 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
277 msg ? msg : "unsupported");
278 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
281 /* Extract an integer from "expr" and store it in "v".
283 int PetScan::extract_int(IntegerLiteral *expr, isl_int *v)
285 const Type *type = expr->getType().getTypePtr();
286 int is_signed = type->hasSignedIntegerRepresentation();
288 if (is_signed) {
289 int64_t i = expr->getValue().getSExtValue();
290 isl_int_set_si(*v, i);
291 } else {
292 uint64_t i = expr->getValue().getZExtValue();
293 isl_int_set_ui(*v, i);
296 return 0;
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::ParenExpr *expr, isl_int *v)
304 return extract_int(expr->getSubExpr(), v);
307 /* Extract an integer from "expr" and store it in "v".
308 * Return -1 if "expr" does not (obviously) represent an integer.
310 int PetScan::extract_int(clang::Expr *expr, isl_int *v)
312 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
313 return extract_int(cast<IntegerLiteral>(expr), v);
314 if (expr->getStmtClass() == Stmt::ParenExprClass)
315 return extract_int(cast<ParenExpr>(expr), v);
317 unsupported(expr);
318 return -1;
321 /* Extract an affine expression from the IntegerLiteral "expr".
323 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
325 isl_space *dim = isl_space_params_alloc(ctx, 0);
326 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
327 isl_aff *aff = isl_aff_zero_on_domain(ls);
328 isl_set *dom = isl_set_universe(dim);
329 isl_int v;
331 isl_int_init(v);
332 extract_int(expr, &v);
333 aff = isl_aff_add_constant(aff, v);
334 isl_int_clear(v);
336 return isl_pw_aff_alloc(dom, aff);
339 /* Extract an affine expression from the APInt "val".
341 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
343 isl_space *dim = isl_space_params_alloc(ctx, 0);
344 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
345 isl_aff *aff = isl_aff_zero_on_domain(ls);
346 isl_set *dom = isl_set_universe(dim);
347 isl_int v;
349 isl_int_init(v);
350 isl_int_set_ui(v, val.getZExtValue());
351 aff = isl_aff_add_constant(aff, v);
352 isl_int_clear(v);
354 return isl_pw_aff_alloc(dom, aff);
357 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
359 return extract_affine(expr->getSubExpr());
362 static unsigned get_type_size(ValueDecl *decl)
364 return decl->getASTContext().getIntWidth(decl->getType());
367 /* Bound parameter "pos" of "set" to the possible values of "decl".
369 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
370 unsigned pos, ValueDecl *decl)
372 unsigned width;
373 isl_int v;
375 isl_int_init(v);
377 width = get_type_size(decl);
378 if (decl->getType()->isUnsignedIntegerType()) {
379 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
380 isl_int_set_si(v, 1);
381 isl_int_mul_2exp(v, v, width);
382 isl_int_sub_ui(v, v, 1);
383 set = isl_set_upper_bound(set, isl_dim_param, pos, v);
384 } else {
385 isl_int_set_si(v, 1);
386 isl_int_mul_2exp(v, v, width - 1);
387 isl_int_sub_ui(v, v, 1);
388 set = isl_set_upper_bound(set, isl_dim_param, pos, v);
389 isl_int_neg(v, v);
390 isl_int_sub_ui(v, v, 1);
391 set = isl_set_lower_bound(set, isl_dim_param, pos, v);
394 isl_int_clear(v);
396 return set;
399 /* Extract an affine expression from the DeclRefExpr "expr".
401 * If the variable has been assigned a value, then we check whether
402 * we know what (affine) value was assigned.
403 * If so, we return this value. Otherwise we convert "expr"
404 * to an extra parameter (provided nesting_enabled is set).
406 * Otherwise, we simply return an expression that is equal
407 * to a parameter corresponding to the referenced variable.
409 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
411 ValueDecl *decl = expr->getDecl();
412 const Type *type = decl->getType().getTypePtr();
413 isl_id *id;
414 isl_space *dim;
415 isl_aff *aff;
416 isl_set *dom;
418 if (!type->isIntegerType()) {
419 unsupported(expr);
420 return NULL;
423 if (assigned_value.find(decl) != assigned_value.end()) {
424 if (assigned_value[decl])
425 return isl_pw_aff_copy(assigned_value[decl]);
426 else
427 return nested_access(expr);
430 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
431 dim = isl_space_params_alloc(ctx, 1);
433 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
435 dom = isl_set_universe(isl_space_copy(dim));
436 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
437 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
439 return isl_pw_aff_alloc(dom, aff);
442 /* Extract an affine expression from an integer division operation.
443 * In particular, if "expr" is lhs/rhs, then return
445 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
447 * The second argument (rhs) is required to be a (positive) integer constant.
449 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
451 Expr *rhs_expr;
452 isl_pw_aff *lhs, *lhs_f, *lhs_c;
453 isl_pw_aff *res;
454 isl_int v;
455 isl_set *cond;
457 rhs_expr = expr->getRHS();
458 isl_int_init(v);
459 if (extract_int(rhs_expr, &v) < 0) {
460 isl_int_clear(v);
461 return NULL;
464 lhs = extract_affine(expr->getLHS());
465 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
467 lhs = isl_pw_aff_scale_down(lhs, v);
468 isl_int_clear(v);
470 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(lhs));
471 lhs_c = isl_pw_aff_ceil(lhs);
472 res = isl_pw_aff_cond(isl_set_indicator_function(cond), lhs_f, lhs_c);
474 return res;
477 /* Extract an affine expression from a modulo operation.
478 * In particular, if "expr" is lhs/rhs, then return
480 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
482 * The second argument (rhs) is required to be a (positive) integer constant.
484 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
486 Expr *rhs_expr;
487 isl_pw_aff *lhs, *lhs_f, *lhs_c;
488 isl_pw_aff *res;
489 isl_int v;
490 isl_set *cond;
492 rhs_expr = expr->getRHS();
493 if (rhs_expr->getStmtClass() != Stmt::IntegerLiteralClass) {
494 unsupported(expr);
495 return NULL;
498 lhs = extract_affine(expr->getLHS());
499 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
501 isl_int_init(v);
502 extract_int(cast<IntegerLiteral>(rhs_expr), &v);
503 res = isl_pw_aff_scale_down(isl_pw_aff_copy(lhs), v);
505 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(res));
506 lhs_c = isl_pw_aff_ceil(res);
507 res = isl_pw_aff_cond(isl_set_indicator_function(cond), lhs_f, lhs_c);
509 res = isl_pw_aff_scale(res, v);
510 isl_int_clear(v);
512 res = isl_pw_aff_sub(lhs, res);
514 return res;
517 /* Extract an affine expression from a multiplication operation.
518 * This is only allowed if at least one of the two arguments
519 * is a (piecewise) constant.
521 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
523 isl_pw_aff *lhs;
524 isl_pw_aff *rhs;
526 lhs = extract_affine(expr->getLHS());
527 rhs = extract_affine(expr->getRHS());
529 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
530 isl_pw_aff_free(lhs);
531 isl_pw_aff_free(rhs);
532 unsupported(expr);
533 return NULL;
536 return isl_pw_aff_mul(lhs, rhs);
539 /* Extract an affine expression from an addition or subtraction operation.
541 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
543 isl_pw_aff *lhs;
544 isl_pw_aff *rhs;
546 lhs = extract_affine(expr->getLHS());
547 rhs = extract_affine(expr->getRHS());
549 switch (expr->getOpcode()) {
550 case BO_Add:
551 return isl_pw_aff_add(lhs, rhs);
552 case BO_Sub:
553 return isl_pw_aff_sub(lhs, rhs);
554 default:
555 isl_pw_aff_free(lhs);
556 isl_pw_aff_free(rhs);
557 return NULL;
562 /* Compute
564 * pwaff mod 2^width
566 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
567 unsigned width)
569 isl_int mod;
571 isl_int_init(mod);
572 isl_int_set_si(mod, 1);
573 isl_int_mul_2exp(mod, mod, width);
575 pwaff = isl_pw_aff_mod(pwaff, mod);
577 isl_int_clear(mod);
579 return pwaff;
582 /* Limit the domain of "pwaff" to those elements where the function
583 * value satisfies
585 * 2^{width-1} <= pwaff < 2^{width-1}
587 static __isl_give isl_pw_aff *avoid_overflow(__isl_take isl_pw_aff *pwaff,
588 unsigned width)
590 isl_int v;
591 isl_space *space = isl_pw_aff_get_domain_space(pwaff);
592 isl_local_space *ls = isl_local_space_from_space(space);
593 isl_aff *bound;
594 isl_set *dom;
595 isl_pw_aff *b;
597 isl_int_init(v);
598 isl_int_set_si(v, 1);
599 isl_int_mul_2exp(v, v, width - 1);
601 bound = isl_aff_zero_on_domain(ls);
602 bound = isl_aff_add_constant(bound, v);
603 b = isl_pw_aff_from_aff(bound);
605 dom = isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff), isl_pw_aff_copy(b));
606 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
608 b = isl_pw_aff_neg(b);
609 dom = isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff), b);
610 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
612 isl_int_clear(v);
614 return pwaff;
617 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
619 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
620 __isl_take isl_set *dom)
622 isl_pw_aff *pa;
623 pa = isl_set_indicator_function(set);
624 pa = isl_pw_aff_intersect_domain(pa, dom);
625 return pa;
628 /* Extract an affine expression from some binary operations.
629 * If the result of the expression is unsigned, then we wrap it
630 * based on the size of the type. Otherwise, we ensure that
631 * no overflow occurs.
633 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
635 isl_pw_aff *res;
636 unsigned width;
638 switch (expr->getOpcode()) {
639 case BO_Add:
640 case BO_Sub:
641 res = extract_affine_add(expr);
642 break;
643 case BO_Div:
644 res = extract_affine_div(expr);
645 break;
646 case BO_Rem:
647 res = extract_affine_mod(expr);
648 break;
649 case BO_Mul:
650 res = extract_affine_mul(expr);
651 break;
652 case BO_LT:
653 case BO_LE:
654 case BO_GT:
655 case BO_GE:
656 case BO_EQ:
657 case BO_NE:
658 case BO_LAnd:
659 case BO_LOr:
660 return extract_condition(expr);
661 default:
662 unsupported(expr);
663 return NULL;
666 width = ast_context.getIntWidth(expr->getType());
667 if (expr->getType()->isUnsignedIntegerType())
668 res = wrap(res, width);
669 else
670 res = avoid_overflow(res, width);
672 return res;
675 /* Extract an affine expression from a negation operation.
677 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
679 if (expr->getOpcode() == UO_Minus)
680 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
681 if (expr->getOpcode() == UO_LNot)
682 return extract_condition(expr);
684 unsupported(expr);
685 return NULL;
688 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
690 return extract_affine(expr->getSubExpr());
693 /* Extract an affine expression from some special function calls.
694 * In particular, we handle "min", "max", "ceild" and "floord".
695 * In case of the latter two, the second argument needs to be
696 * a (positive) integer constant.
698 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
700 FunctionDecl *fd;
701 string name;
702 isl_pw_aff *aff1, *aff2;
704 fd = expr->getDirectCallee();
705 if (!fd) {
706 unsupported(expr);
707 return NULL;
710 name = fd->getDeclName().getAsString();
711 if (!(expr->getNumArgs() == 2 && name == "min") &&
712 !(expr->getNumArgs() == 2 && name == "max") &&
713 !(expr->getNumArgs() == 2 && name == "floord") &&
714 !(expr->getNumArgs() == 2 && name == "ceild")) {
715 unsupported(expr);
716 return NULL;
719 if (name == "min" || name == "max") {
720 aff1 = extract_affine(expr->getArg(0));
721 aff2 = extract_affine(expr->getArg(1));
723 if (name == "min")
724 aff1 = isl_pw_aff_min(aff1, aff2);
725 else
726 aff1 = isl_pw_aff_max(aff1, aff2);
727 } else if (name == "floord" || name == "ceild") {
728 isl_int v;
729 Expr *arg2 = expr->getArg(1);
731 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
732 unsupported(expr);
733 return NULL;
735 aff1 = extract_affine(expr->getArg(0));
736 isl_int_init(v);
737 extract_int(cast<IntegerLiteral>(arg2), &v);
738 aff1 = isl_pw_aff_scale_down(aff1, v);
739 isl_int_clear(v);
740 if (name == "floord")
741 aff1 = isl_pw_aff_floor(aff1);
742 else
743 aff1 = isl_pw_aff_ceil(aff1);
744 } else {
745 unsupported(expr);
746 return NULL;
749 return aff1;
753 /* This method is called when we come across an access that is
754 * nested in what is supposed to be an affine expression.
755 * If nesting is allowed, we return a new parameter that corresponds
756 * to this nested access. Otherwise, we simply complain.
758 * Note that we currently don't allow nested accesses themselves
759 * to contain any nested accesses, so we check if we can extract
760 * the access without any nesting and complain if we can't.
762 * The new parameter is resolved in resolve_nested.
764 isl_pw_aff *PetScan::nested_access(Expr *expr)
766 isl_id *id;
767 isl_space *dim;
768 isl_aff *aff;
769 isl_set *dom;
770 isl_map *access;
772 if (!nesting_enabled) {
773 unsupported(expr);
774 return NULL;
777 allow_nested = false;
778 access = extract_access(expr);
779 allow_nested = true;
780 if (!access) {
781 unsupported(expr);
782 return NULL;
784 isl_map_free(access);
786 id = isl_id_alloc(ctx, NULL, expr);
787 dim = isl_space_params_alloc(ctx, 1);
789 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
791 dom = isl_set_universe(isl_space_copy(dim));
792 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
793 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
795 return isl_pw_aff_alloc(dom, aff);
798 /* Affine expressions are not supposed to contain array accesses,
799 * but if nesting is allowed, we return a parameter corresponding
800 * to the array access.
802 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
804 return nested_access(expr);
807 /* Extract an affine expression from a conditional operation.
809 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
811 isl_pw_aff *cond, *lhs, *rhs, *res;
813 cond = extract_condition(expr->getCond());
814 lhs = extract_affine(expr->getTrueExpr());
815 rhs = extract_affine(expr->getFalseExpr());
817 return isl_pw_aff_cond(cond, lhs, rhs);
820 /* Extract an affine expression, if possible, from "expr".
821 * Otherwise return NULL.
823 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
825 switch (expr->getStmtClass()) {
826 case Stmt::ImplicitCastExprClass:
827 return extract_affine(cast<ImplicitCastExpr>(expr));
828 case Stmt::IntegerLiteralClass:
829 return extract_affine(cast<IntegerLiteral>(expr));
830 case Stmt::DeclRefExprClass:
831 return extract_affine(cast<DeclRefExpr>(expr));
832 case Stmt::BinaryOperatorClass:
833 return extract_affine(cast<BinaryOperator>(expr));
834 case Stmt::UnaryOperatorClass:
835 return extract_affine(cast<UnaryOperator>(expr));
836 case Stmt::ParenExprClass:
837 return extract_affine(cast<ParenExpr>(expr));
838 case Stmt::CallExprClass:
839 return extract_affine(cast<CallExpr>(expr));
840 case Stmt::ArraySubscriptExprClass:
841 return extract_affine(cast<ArraySubscriptExpr>(expr));
842 case Stmt::ConditionalOperatorClass:
843 return extract_affine(cast<ConditionalOperator>(expr));
844 default:
845 unsupported(expr);
847 return NULL;
850 __isl_give isl_map *PetScan::extract_access(ImplicitCastExpr *expr)
852 return extract_access(expr->getSubExpr());
855 /* Return the depth of an array of the given type.
857 static int array_depth(const Type *type)
859 if (type->isPointerType())
860 return 1 + array_depth(type->getPointeeType().getTypePtr());
861 if (type->isArrayType()) {
862 const ArrayType *atype;
863 type = type->getCanonicalTypeInternal().getTypePtr();
864 atype = cast<ArrayType>(type);
865 return 1 + array_depth(atype->getElementType().getTypePtr());
867 return 0;
870 /* Return the element type of the given array type.
872 static QualType base_type(QualType qt)
874 const Type *type = qt.getTypePtr();
876 if (type->isPointerType())
877 return base_type(type->getPointeeType());
878 if (type->isArrayType()) {
879 const ArrayType *atype;
880 type = type->getCanonicalTypeInternal().getTypePtr();
881 atype = cast<ArrayType>(type);
882 return base_type(atype->getElementType());
884 return qt;
887 /* Extract an access relation from a reference to a variable.
888 * If the variable has name "A" and its type corresponds to an
889 * array of depth d, then the returned access relation is of the
890 * form
892 * { [] -> A[i_1,...,i_d] }
894 __isl_give isl_map *PetScan::extract_access(DeclRefExpr *expr)
896 ValueDecl *decl = expr->getDecl();
897 int depth = array_depth(decl->getType().getTypePtr());
898 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
899 isl_space *dim = isl_space_alloc(ctx, 0, 0, depth);
900 isl_map *access_rel;
902 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
904 access_rel = isl_map_universe(dim);
906 return access_rel;
909 /* Extract an access relation from an integer contant.
910 * If the value of the constant is "v", then the returned access relation
911 * is
913 * { [] -> [v] }
915 __isl_give isl_map *PetScan::extract_access(IntegerLiteral *expr)
917 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr)));
920 /* Try and extract an access relation from the given Expr.
921 * Return NULL if it doesn't work out.
923 __isl_give isl_map *PetScan::extract_access(Expr *expr)
925 switch (expr->getStmtClass()) {
926 case Stmt::ImplicitCastExprClass:
927 return extract_access(cast<ImplicitCastExpr>(expr));
928 case Stmt::DeclRefExprClass:
929 return extract_access(cast<DeclRefExpr>(expr));
930 case Stmt::ArraySubscriptExprClass:
931 return extract_access(cast<ArraySubscriptExpr>(expr));
932 case Stmt::IntegerLiteralClass:
933 return extract_access(cast<IntegerLiteral>(expr));
934 default:
935 unsupported(expr);
937 return NULL;
940 /* Assign the affine expression "index" to the output dimension "pos" of "map",
941 * restrict the domain to those values that result in a non-negative index
942 * and return the result.
944 __isl_give isl_map *set_index(__isl_take isl_map *map, int pos,
945 __isl_take isl_pw_aff *index)
947 isl_map *index_map;
948 int len = isl_map_dim(map, isl_dim_out);
949 isl_id *id;
950 isl_set *domain;
952 domain = isl_pw_aff_nonneg_set(isl_pw_aff_copy(index));
953 index = isl_pw_aff_intersect_domain(index, domain);
954 index_map = isl_map_from_range(isl_set_from_pw_aff(index));
955 index_map = isl_map_insert_dims(index_map, isl_dim_out, 0, pos);
956 index_map = isl_map_add_dims(index_map, isl_dim_out, len - pos - 1);
957 id = isl_map_get_tuple_id(map, isl_dim_out);
958 index_map = isl_map_set_tuple_id(index_map, isl_dim_out, id);
960 map = isl_map_intersect(map, index_map);
962 return map;
965 /* Extract an access relation from the given array subscript expression.
966 * If nesting is allowed in general, then we turn it on while
967 * examining the index expression.
969 * We first extract an access relation from the base.
970 * This will result in an access relation with a range that corresponds
971 * to the array being accessed and with earlier indices filled in already.
972 * We then extract the current index and fill that in as well.
973 * The position of the current index is based on the type of base.
974 * If base is the actual array variable, then the depth of this type
975 * will be the same as the depth of the array and we will fill in
976 * the first array index.
977 * Otherwise, the depth of the base type will be smaller and we will fill
978 * in a later index.
980 __isl_give isl_map *PetScan::extract_access(ArraySubscriptExpr *expr)
982 Expr *base = expr->getBase();
983 Expr *idx = expr->getIdx();
984 isl_pw_aff *index;
985 isl_map *base_access;
986 isl_map *access;
987 int depth = array_depth(base->getType().getTypePtr());
988 int pos;
989 bool save_nesting = nesting_enabled;
991 nesting_enabled = allow_nested;
993 base_access = extract_access(base);
994 index = extract_affine(idx);
996 nesting_enabled = save_nesting;
998 pos = isl_map_dim(base_access, isl_dim_out) - depth;
999 access = set_index(base_access, pos, index);
1001 return access;
1004 /* Check if "expr" calls function "minmax" with two arguments and if so
1005 * make lhs and rhs refer to these two arguments.
1007 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
1009 CallExpr *call;
1010 FunctionDecl *fd;
1011 string name;
1013 if (expr->getStmtClass() != Stmt::CallExprClass)
1014 return false;
1016 call = cast<CallExpr>(expr);
1017 fd = call->getDirectCallee();
1018 if (!fd)
1019 return false;
1021 if (call->getNumArgs() != 2)
1022 return false;
1024 name = fd->getDeclName().getAsString();
1025 if (name != minmax)
1026 return false;
1028 lhs = call->getArg(0);
1029 rhs = call->getArg(1);
1031 return true;
1034 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1035 * lhs and rhs refer to the two arguments.
1037 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
1039 return is_minmax(expr, "min", lhs, rhs);
1042 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1043 * lhs and rhs refer to the two arguments.
1045 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
1047 return is_minmax(expr, "max", lhs, rhs);
1050 /* Return "lhs && rhs", defined on the shared definition domain.
1052 static __isl_give isl_pw_aff *pw_aff_and(__isl_take isl_pw_aff *lhs,
1053 __isl_take isl_pw_aff *rhs)
1055 isl_set *cond;
1056 isl_set *dom;
1058 dom = isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs)),
1059 isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1060 cond = isl_set_intersect(isl_pw_aff_non_zero_set(lhs),
1061 isl_pw_aff_non_zero_set(rhs));
1062 return indicator_function(cond, dom);
1065 /* Return "lhs && rhs", with shortcut semantics.
1066 * That is, if lhs is false, then the result is defined even if rhs is not.
1067 * In practice, we compute lhs ? rhs : lhs.
1069 static __isl_give isl_pw_aff *pw_aff_and_then(__isl_take isl_pw_aff *lhs,
1070 __isl_take isl_pw_aff *rhs)
1072 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), rhs, lhs);
1075 /* Return "lhs || rhs", with shortcut semantics.
1076 * That is, if lhs is true, then the result is defined even if rhs is not.
1077 * In practice, we compute lhs ? lhs : rhs.
1079 static __isl_give isl_pw_aff *pw_aff_or_else(__isl_take isl_pw_aff *lhs,
1080 __isl_take isl_pw_aff *rhs)
1082 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), lhs, rhs);
1085 /* Extract an affine expressions representing the comparison "LHS op RHS"
1086 * "comp" is the original statement that "LHS op RHS" is derived from
1087 * and is used for diagnostics.
1089 * If the comparison is of the form
1091 * a <= min(b,c)
1093 * then the expression is constructed as the conjunction of
1094 * the comparisons
1096 * a <= b and a <= c
1098 * A similar optimization is performed for max(a,b) <= c.
1099 * We do this because that will lead to simpler representations
1100 * of the expression.
1101 * If isl is ever enhanced to explicitly deal with min and max expressions,
1102 * this optimization can be removed.
1104 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
1105 Expr *LHS, Expr *RHS, Stmt *comp)
1107 isl_pw_aff *lhs;
1108 isl_pw_aff *rhs;
1109 isl_pw_aff *res;
1110 isl_set *cond;
1111 isl_set *dom;
1113 if (op == BO_GT)
1114 return extract_comparison(BO_LT, RHS, LHS, comp);
1115 if (op == BO_GE)
1116 return extract_comparison(BO_LE, RHS, LHS, comp);
1118 if (op == BO_LT || op == BO_LE) {
1119 Expr *expr1, *expr2;
1120 if (is_min(RHS, expr1, expr2)) {
1121 lhs = extract_comparison(op, LHS, expr1, comp);
1122 rhs = extract_comparison(op, LHS, expr2, comp);
1123 return pw_aff_and(lhs, rhs);
1125 if (is_max(LHS, expr1, expr2)) {
1126 lhs = extract_comparison(op, expr1, RHS, comp);
1127 rhs = extract_comparison(op, expr2, RHS, comp);
1128 return pw_aff_and(lhs, rhs);
1132 lhs = extract_affine(LHS);
1133 rhs = extract_affine(RHS);
1135 dom = isl_pw_aff_domain(isl_pw_aff_copy(lhs));
1136 dom = isl_set_intersect(dom, isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1138 switch (op) {
1139 case BO_LT:
1140 cond = isl_pw_aff_lt_set(lhs, rhs);
1141 break;
1142 case BO_LE:
1143 cond = isl_pw_aff_le_set(lhs, rhs);
1144 break;
1145 case BO_EQ:
1146 cond = isl_pw_aff_eq_set(lhs, rhs);
1147 break;
1148 case BO_NE:
1149 cond = isl_pw_aff_ne_set(lhs, rhs);
1150 break;
1151 default:
1152 isl_pw_aff_free(lhs);
1153 isl_pw_aff_free(rhs);
1154 isl_set_free(dom);
1155 unsupported(comp);
1156 return NULL;
1159 cond = isl_set_coalesce(cond);
1160 res = indicator_function(cond, dom);
1162 return res;
1165 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1167 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1168 comp->getRHS(), comp);
1171 /* Extract an affine expression representing the negation (logical not)
1172 * of a subexpression.
1174 __isl_give isl_pw_aff *PetScan::extract_boolean(UnaryOperator *op)
1176 isl_set *set_cond, *dom;
1177 isl_pw_aff *cond, *res;
1179 cond = extract_condition(op->getSubExpr());
1181 dom = isl_pw_aff_domain(isl_pw_aff_copy(cond));
1183 set_cond = isl_pw_aff_zero_set(cond);
1185 res = indicator_function(set_cond, dom);
1187 return res;
1190 /* Extract an affine expression representing the disjunction (logical or)
1191 * or conjunction (logical and) of two subexpressions.
1193 __isl_give isl_pw_aff *PetScan::extract_boolean(BinaryOperator *comp)
1195 isl_pw_aff *lhs, *rhs;
1197 lhs = extract_condition(comp->getLHS());
1198 rhs = extract_condition(comp->getRHS());
1200 switch (comp->getOpcode()) {
1201 case BO_LAnd:
1202 return pw_aff_and_then(lhs, rhs);
1203 case BO_LOr:
1204 return pw_aff_or_else(lhs, rhs);
1205 default:
1206 isl_pw_aff_free(lhs);
1207 isl_pw_aff_free(rhs);
1210 unsupported(comp);
1211 return NULL;
1214 __isl_give isl_pw_aff *PetScan::extract_condition(UnaryOperator *expr)
1216 switch (expr->getOpcode()) {
1217 case UO_LNot:
1218 return extract_boolean(expr);
1219 default:
1220 unsupported(expr);
1221 return NULL;
1225 /* Extract the affine expression "expr != 0 ? 1 : 0".
1227 __isl_give isl_pw_aff *PetScan::extract_implicit_condition(Expr *expr)
1229 isl_pw_aff *res;
1230 isl_set *set, *dom;
1232 res = extract_affine(expr);
1234 dom = isl_pw_aff_domain(isl_pw_aff_copy(res));
1235 set = isl_pw_aff_non_zero_set(res);
1237 res = indicator_function(set, dom);
1239 return res;
1242 /* Extract an affine expression from a boolean expression.
1243 * In particular, return the expression "expr ? 1 : 0".
1245 * If the expression doesn't look like a condition, we assume it
1246 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1248 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1250 BinaryOperator *comp;
1252 if (!expr) {
1253 isl_set *u = isl_set_universe(isl_space_params_alloc(ctx, 0));
1254 return indicator_function(u, isl_set_copy(u));
1257 if (expr->getStmtClass() == Stmt::ParenExprClass)
1258 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1260 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1261 return extract_condition(cast<UnaryOperator>(expr));
1263 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1264 return extract_implicit_condition(expr);
1266 comp = cast<BinaryOperator>(expr);
1267 switch (comp->getOpcode()) {
1268 case BO_LT:
1269 case BO_LE:
1270 case BO_GT:
1271 case BO_GE:
1272 case BO_EQ:
1273 case BO_NE:
1274 return extract_comparison(comp);
1275 case BO_LAnd:
1276 case BO_LOr:
1277 return extract_boolean(comp);
1278 default:
1279 return extract_implicit_condition(expr);
1283 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1285 switch (kind) {
1286 case UO_Minus:
1287 return pet_op_minus;
1288 default:
1289 return pet_op_last;
1293 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1295 switch (kind) {
1296 case BO_AddAssign:
1297 return pet_op_add_assign;
1298 case BO_SubAssign:
1299 return pet_op_sub_assign;
1300 case BO_MulAssign:
1301 return pet_op_mul_assign;
1302 case BO_DivAssign:
1303 return pet_op_div_assign;
1304 case BO_Assign:
1305 return pet_op_assign;
1306 case BO_Add:
1307 return pet_op_add;
1308 case BO_Sub:
1309 return pet_op_sub;
1310 case BO_Mul:
1311 return pet_op_mul;
1312 case BO_Div:
1313 return pet_op_div;
1314 case BO_EQ:
1315 return pet_op_eq;
1316 case BO_LE:
1317 return pet_op_le;
1318 case BO_LT:
1319 return pet_op_lt;
1320 case BO_GT:
1321 return pet_op_gt;
1322 default:
1323 return pet_op_last;
1327 /* Construct a pet_expr representing a unary operator expression.
1329 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1331 struct pet_expr *arg;
1332 enum pet_op_type op;
1334 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1335 if (op == pet_op_last) {
1336 unsupported(expr);
1337 return NULL;
1340 arg = extract_expr(expr->getSubExpr());
1342 return pet_expr_new_unary(ctx, op, arg);
1345 /* Mark the given access pet_expr as a write.
1346 * If a scalar is being accessed, then mark its value
1347 * as unknown in assigned_value.
1349 void PetScan::mark_write(struct pet_expr *access)
1351 isl_id *id;
1352 ValueDecl *decl;
1354 access->acc.write = 1;
1355 access->acc.read = 0;
1357 if (isl_map_dim(access->acc.access, isl_dim_out) != 0)
1358 return;
1360 id = isl_map_get_tuple_id(access->acc.access, isl_dim_out);
1361 decl = (ValueDecl *) isl_id_get_user(id);
1362 clear_assignment(assigned_value, decl);
1363 isl_id_free(id);
1366 /* Construct a pet_expr representing a binary operator expression.
1368 * If the top level operator is an assignment and the LHS is an access,
1369 * then we mark that access as a write. If the operator is a compound
1370 * assignment, the access is marked as both a read and a write.
1372 * If "expr" assigns something to a scalar variable, then we mark
1373 * the variable as having been assigned. If, furthermore, the expression
1374 * is affine, then keep track of this value in assigned_value
1375 * so that we can plug it in when we later come across the same variable.
1377 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1379 struct pet_expr *lhs, *rhs;
1380 enum pet_op_type op;
1382 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1383 if (op == pet_op_last) {
1384 unsupported(expr);
1385 return NULL;
1388 lhs = extract_expr(expr->getLHS());
1389 rhs = extract_expr(expr->getRHS());
1391 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1392 mark_write(lhs);
1393 if (expr->isCompoundAssignmentOp())
1394 lhs->acc.read = 1;
1397 if (expr->getOpcode() == BO_Assign &&
1398 lhs && lhs->type == pet_expr_access &&
1399 isl_map_dim(lhs->acc.access, isl_dim_out) == 0) {
1400 isl_id *id = isl_map_get_tuple_id(lhs->acc.access, isl_dim_out);
1401 ValueDecl *decl = (ValueDecl *) isl_id_get_user(id);
1402 Expr *rhs = expr->getRHS();
1403 isl_pw_aff *pa = try_extract_affine(rhs);
1404 clear_assignment(assigned_value, decl);
1405 if (pa) {
1406 assigned_value[decl] = pa;
1407 insert_expression(pa);
1409 isl_id_free(id);
1412 return pet_expr_new_binary(ctx, op, lhs, rhs);
1415 /* Construct a pet_expr representing a conditional operation.
1417 * We first try to extract the condition as an affine expression.
1418 * If that fails, we construct a pet_expr tree representing the condition.
1420 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1422 struct pet_expr *cond, *lhs, *rhs;
1423 isl_pw_aff *pa;
1425 pa = try_extract_affine(expr->getCond());
1426 if (pa) {
1427 isl_set *test = isl_set_from_pw_aff(pa);
1428 cond = pet_expr_from_access(isl_map_from_range(test));
1429 } else
1430 cond = extract_expr(expr->getCond());
1431 lhs = extract_expr(expr->getTrueExpr());
1432 rhs = extract_expr(expr->getFalseExpr());
1434 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1437 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1439 return extract_expr(expr->getSubExpr());
1442 /* Construct a pet_expr representing a floating point value.
1444 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1446 return pet_expr_new_double(ctx, expr->getValueAsApproximateDouble());
1449 /* Extract an access relation from "expr" and then convert it into
1450 * a pet_expr.
1452 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1454 isl_map *access;
1455 struct pet_expr *pe;
1457 access = extract_access(expr);
1459 pe = pet_expr_from_access(access);
1461 return pe;
1464 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1466 return extract_expr(expr->getSubExpr());
1469 /* Construct a pet_expr representing a function call.
1471 * If we are passing along a pointer to an array element
1472 * or an entire row or even higher dimensional slice of an array,
1473 * then the function being called may write into the array.
1475 * We assume here that if the function is declared to take a pointer
1476 * to a const type, then the function will perform a read
1477 * and that otherwise, it will perform a write.
1479 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1481 struct pet_expr *res = NULL;
1482 FunctionDecl *fd;
1483 string name;
1485 fd = expr->getDirectCallee();
1486 if (!fd) {
1487 unsupported(expr);
1488 return NULL;
1491 name = fd->getDeclName().getAsString();
1492 res = pet_expr_new_call(ctx, name.c_str(), expr->getNumArgs());
1493 if (!res)
1494 return NULL;
1496 for (int i = 0; i < expr->getNumArgs(); ++i) {
1497 Expr *arg = expr->getArg(i);
1498 int is_addr = 0;
1499 pet_expr *main_arg;
1501 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
1502 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(arg);
1503 arg = ice->getSubExpr();
1505 if (arg->getStmtClass() == Stmt::UnaryOperatorClass) {
1506 UnaryOperator *op = cast<UnaryOperator>(arg);
1507 if (op->getOpcode() == UO_AddrOf) {
1508 is_addr = 1;
1509 arg = op->getSubExpr();
1512 res->args[i] = PetScan::extract_expr(arg);
1513 main_arg = res->args[i];
1514 if (is_addr)
1515 res->args[i] = pet_expr_new_unary(ctx,
1516 pet_op_address_of, res->args[i]);
1517 if (!res->args[i])
1518 goto error;
1519 if (arg->getStmtClass() == Stmt::ArraySubscriptExprClass &&
1520 array_depth(arg->getType().getTypePtr()) > 0)
1521 is_addr = 1;
1522 if (is_addr && main_arg->type == pet_expr_access) {
1523 ParmVarDecl *parm;
1524 if (!fd->hasPrototype()) {
1525 unsupported(expr, "prototype required");
1526 goto error;
1528 parm = fd->getParamDecl(i);
1529 if (!const_base(parm->getType()))
1530 mark_write(main_arg);
1534 return res;
1535 error:
1536 pet_expr_free(res);
1537 return NULL;
1540 /* Try and onstruct a pet_expr representing "expr".
1542 struct pet_expr *PetScan::extract_expr(Expr *expr)
1544 switch (expr->getStmtClass()) {
1545 case Stmt::UnaryOperatorClass:
1546 return extract_expr(cast<UnaryOperator>(expr));
1547 case Stmt::CompoundAssignOperatorClass:
1548 case Stmt::BinaryOperatorClass:
1549 return extract_expr(cast<BinaryOperator>(expr));
1550 case Stmt::ImplicitCastExprClass:
1551 return extract_expr(cast<ImplicitCastExpr>(expr));
1552 case Stmt::ArraySubscriptExprClass:
1553 case Stmt::DeclRefExprClass:
1554 case Stmt::IntegerLiteralClass:
1555 return extract_access_expr(expr);
1556 case Stmt::FloatingLiteralClass:
1557 return extract_expr(cast<FloatingLiteral>(expr));
1558 case Stmt::ParenExprClass:
1559 return extract_expr(cast<ParenExpr>(expr));
1560 case Stmt::ConditionalOperatorClass:
1561 return extract_expr(cast<ConditionalOperator>(expr));
1562 case Stmt::CallExprClass:
1563 return extract_expr(cast<CallExpr>(expr));
1564 default:
1565 unsupported(expr);
1567 return NULL;
1570 /* Check if the given initialization statement is an assignment.
1571 * If so, return that assignment. Otherwise return NULL.
1573 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1575 BinaryOperator *ass;
1577 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1578 return NULL;
1580 ass = cast<BinaryOperator>(init);
1581 if (ass->getOpcode() != BO_Assign)
1582 return NULL;
1584 return ass;
1587 /* Check if the given initialization statement is a declaration
1588 * of a single variable.
1589 * If so, return that declaration. Otherwise return NULL.
1591 Decl *PetScan::initialization_declaration(Stmt *init)
1593 DeclStmt *decl;
1595 if (init->getStmtClass() != Stmt::DeclStmtClass)
1596 return NULL;
1598 decl = cast<DeclStmt>(init);
1600 if (!decl->isSingleDecl())
1601 return NULL;
1603 return decl->getSingleDecl();
1606 /* Given the assignment operator in the initialization of a for loop,
1607 * extract the induction variable, i.e., the (integer)variable being
1608 * assigned.
1610 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1612 Expr *lhs;
1613 DeclRefExpr *ref;
1614 ValueDecl *decl;
1615 const Type *type;
1617 lhs = init->getLHS();
1618 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1619 unsupported(init);
1620 return NULL;
1623 ref = cast<DeclRefExpr>(lhs);
1624 decl = ref->getDecl();
1625 type = decl->getType().getTypePtr();
1627 if (!type->isIntegerType()) {
1628 unsupported(lhs);
1629 return NULL;
1632 return decl;
1635 /* Given the initialization statement of a for loop and the single
1636 * declaration in this initialization statement,
1637 * extract the induction variable, i.e., the (integer) variable being
1638 * declared.
1640 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1642 VarDecl *vd;
1644 vd = cast<VarDecl>(decl);
1646 const QualType type = vd->getType();
1647 if (!type->isIntegerType()) {
1648 unsupported(init);
1649 return NULL;
1652 if (!vd->getInit()) {
1653 unsupported(init);
1654 return NULL;
1657 return vd;
1660 /* Check that op is of the form iv++ or iv--.
1661 * Return an affine expression "1" or "-1" accordingly.
1663 __isl_give isl_pw_aff *PetScan::extract_unary_increment(
1664 clang::UnaryOperator *op, clang::ValueDecl *iv)
1666 Expr *sub;
1667 DeclRefExpr *ref;
1668 isl_space *space;
1669 isl_aff *aff;
1671 if (!op->isIncrementDecrementOp()) {
1672 unsupported(op);
1673 return NULL;
1676 sub = op->getSubExpr();
1677 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1678 unsupported(op);
1679 return NULL;
1682 ref = cast<DeclRefExpr>(sub);
1683 if (ref->getDecl() != iv) {
1684 unsupported(op);
1685 return NULL;
1688 space = isl_space_params_alloc(ctx, 0);
1689 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1691 if (op->isIncrementOp())
1692 aff = isl_aff_add_constant_si(aff, 1);
1693 else
1694 aff = isl_aff_add_constant_si(aff, -1);
1696 return isl_pw_aff_from_aff(aff);
1699 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1700 * has a single constant expression, then put this constant in *user.
1701 * The caller is assumed to have checked that this function will
1702 * be called exactly once.
1704 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
1705 void *user)
1707 isl_int *inc = (isl_int *)user;
1708 int res = 0;
1710 if (isl_aff_is_cst(aff))
1711 isl_aff_get_constant(aff, inc);
1712 else
1713 res = -1;
1715 isl_set_free(set);
1716 isl_aff_free(aff);
1718 return res;
1721 /* Check if op is of the form
1723 * iv = iv + inc
1725 * and return inc as an affine expression.
1727 * We extract an affine expression from the RHS, subtract iv and return
1728 * the result.
1730 __isl_give isl_pw_aff *PetScan::extract_binary_increment(BinaryOperator *op,
1731 clang::ValueDecl *iv)
1733 Expr *lhs;
1734 DeclRefExpr *ref;
1735 isl_id *id;
1736 isl_space *dim;
1737 isl_aff *aff;
1738 isl_pw_aff *val;
1740 if (op->getOpcode() != BO_Assign) {
1741 unsupported(op);
1742 return NULL;
1745 lhs = op->getLHS();
1746 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1747 unsupported(op);
1748 return NULL;
1751 ref = cast<DeclRefExpr>(lhs);
1752 if (ref->getDecl() != iv) {
1753 unsupported(op);
1754 return NULL;
1757 val = extract_affine(op->getRHS());
1759 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1761 dim = isl_space_params_alloc(ctx, 1);
1762 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1763 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1764 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1766 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
1768 return val;
1771 /* Check that op is of the form iv += cst or iv -= cst
1772 * and return an affine expression corresponding oto cst or -cst accordingly.
1774 __isl_give isl_pw_aff *PetScan::extract_compound_increment(
1775 CompoundAssignOperator *op, clang::ValueDecl *iv)
1777 Expr *lhs;
1778 DeclRefExpr *ref;
1779 bool neg = false;
1780 isl_pw_aff *val;
1781 BinaryOperatorKind opcode;
1783 opcode = op->getOpcode();
1784 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1785 unsupported(op);
1786 return NULL;
1788 if (opcode == BO_SubAssign)
1789 neg = true;
1791 lhs = op->getLHS();
1792 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1793 unsupported(op);
1794 return NULL;
1797 ref = cast<DeclRefExpr>(lhs);
1798 if (ref->getDecl() != iv) {
1799 unsupported(op);
1800 return NULL;
1803 val = extract_affine(op->getRHS());
1804 if (neg)
1805 val = isl_pw_aff_neg(val);
1807 return val;
1810 /* Check that the increment of the given for loop increments
1811 * (or decrements) the induction variable "iv" and return
1812 * the increment as an affine expression if successful.
1814 __isl_give isl_pw_aff *PetScan::extract_increment(clang::ForStmt *stmt,
1815 ValueDecl *iv)
1817 Stmt *inc = stmt->getInc();
1819 if (!inc) {
1820 unsupported(stmt);
1821 return NULL;
1824 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1825 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1826 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1827 return extract_compound_increment(
1828 cast<CompoundAssignOperator>(inc), iv);
1829 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1830 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1832 unsupported(inc);
1833 return NULL;
1836 /* Embed the given iteration domain in an extra outer loop
1837 * with induction variable "var".
1838 * If this variable appeared as a parameter in the constraints,
1839 * it is replaced by the new outermost dimension.
1841 static __isl_give isl_set *embed(__isl_take isl_set *set,
1842 __isl_take isl_id *var)
1844 int pos;
1846 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
1847 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
1848 if (pos >= 0) {
1849 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
1850 set = isl_set_project_out(set, isl_dim_param, pos, 1);
1853 isl_id_free(var);
1854 return set;
1857 /* Construct a pet_scop for an infinite loop around the given body.
1859 * We extract a pet_scop for the body and then embed it in a loop with
1860 * iteration domain
1862 * { [t] : t >= 0 }
1864 * and schedule
1866 * { [t] -> [t] }
1868 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
1870 isl_id *id;
1871 isl_space *dim;
1872 isl_set *domain;
1873 isl_map *sched;
1874 struct pet_scop *scop;
1876 scop = extract(body);
1877 if (!scop)
1878 return NULL;
1880 id = isl_id_alloc(ctx, "t", NULL);
1881 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
1882 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
1883 dim = isl_space_from_domain(isl_set_get_space(domain));
1884 dim = isl_space_add_dims(dim, isl_dim_out, 1);
1885 sched = isl_map_universe(dim);
1886 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
1887 scop = pet_scop_embed(scop, domain, sched, id);
1889 return scop;
1892 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1894 * for (;;)
1895 * body
1898 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
1900 return extract_infinite_loop(stmt->getBody());
1903 /* Check if the while loop is of the form
1905 * while (affine expression)
1906 * body
1908 * If so, construct a scop for an infinite loop around body and intersect
1909 * the domain with the affine expression, which may result in an empty loop.
1910 * Otherwise, fail.
1912 struct pet_scop *PetScan::extract(WhileStmt *stmt)
1914 Expr *cond;
1915 isl_pw_aff *pa;
1917 cond = stmt->getCond();
1918 if (!cond) {
1919 unsupported(stmt);
1920 return NULL;
1923 pa = try_extract_affine_condition(cond);
1924 if (pa) {
1925 struct pet_scop *scop;
1926 isl_set *dom;
1927 isl_set *valid;
1929 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
1930 dom = isl_pw_aff_non_zero_set(pa);
1931 scop = extract_infinite_loop(stmt->getBody());
1932 scop = pet_scop_restrict(scop, dom);
1933 scop = pet_scop_restrict_context(scop, valid);
1935 return scop;
1938 unsupported(stmt);
1939 return NULL;
1943 /* Check whether "cond" expresses a simple loop bound
1944 * on the only set dimension.
1945 * In particular, if "up" is set then "cond" should contain only
1946 * upper bounds on the set dimension.
1947 * Otherwise, it should contain only lower bounds.
1949 static bool is_simple_bound(__isl_keep isl_set *cond, isl_int inc)
1951 if (isl_int_is_pos(inc))
1952 return !isl_set_dim_has_lower_bound(cond, isl_dim_set, 0);
1953 else
1954 return !isl_set_dim_has_upper_bound(cond, isl_dim_set, 0);
1957 /* Extend a condition on a given iteration of a loop to one that
1958 * imposes the same condition on all previous iterations.
1959 * "domain" expresses the lower [upper] bound on the iterations
1960 * when inc is positive [negative].
1962 * In particular, we construct the condition (when inc is positive)
1964 * forall i' : (domain(i') and i' <= i) => cond(i')
1966 * which is equivalent to
1968 * not exists i' : domain(i') and i' <= i and not cond(i')
1970 * We construct this set by negating cond, applying a map
1972 * { [i'] -> [i] : domain(i') and i' <= i }
1974 * and then negating the result again.
1976 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
1977 __isl_take isl_set *domain, isl_int inc)
1979 isl_map *previous_to_this;
1981 if (isl_int_is_pos(inc))
1982 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
1983 else
1984 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
1986 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
1988 cond = isl_set_complement(cond);
1989 cond = isl_set_apply(cond, previous_to_this);
1990 cond = isl_set_complement(cond);
1992 return cond;
1995 /* Construct a domain of the form
1997 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
1999 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2000 __isl_take isl_pw_aff *init, isl_int inc)
2002 isl_aff *aff;
2003 isl_space *dim;
2004 isl_set *set;
2006 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2007 dim = isl_pw_aff_get_domain_space(init);
2008 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2009 aff = isl_aff_add_coefficient(aff, isl_dim_in, 0, inc);
2010 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2012 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2013 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2014 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2015 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2017 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2019 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2021 return isl_set_params(set);
2024 /* Assuming "cond" represents a bound on a loop where the loop
2025 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2026 * is possible.
2028 * Under the given assumptions, wrapping is only possible if "cond" allows
2029 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2030 * increasing iterator and 0 in case of a decreasing iterator.
2032 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv, isl_int inc)
2034 bool cw;
2035 isl_int limit;
2036 isl_set *test;
2038 test = isl_set_copy(cond);
2040 isl_int_init(limit);
2041 if (isl_int_is_neg(inc))
2042 isl_int_set_si(limit, 0);
2043 else {
2044 isl_int_set_si(limit, 1);
2045 isl_int_mul_2exp(limit, limit, get_type_size(iv));
2046 isl_int_sub_ui(limit, limit, 1);
2049 test = isl_set_fix(cond, isl_dim_set, 0, limit);
2050 cw = !isl_set_is_empty(test);
2051 isl_set_free(test);
2053 isl_int_clear(limit);
2055 return cw;
2058 /* Given a one-dimensional space, construct the following mapping on this
2059 * space
2061 * { [v] -> [v mod 2^width] }
2063 * where width is the number of bits used to represent the values
2064 * of the unsigned variable "iv".
2066 static __isl_give isl_map *compute_wrapping(__isl_take isl_space *dim,
2067 ValueDecl *iv)
2069 isl_int mod;
2070 isl_aff *aff;
2071 isl_map *map;
2073 isl_int_init(mod);
2074 isl_int_set_si(mod, 1);
2075 isl_int_mul_2exp(mod, mod, get_type_size(iv));
2077 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2078 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2079 aff = isl_aff_mod(aff, mod);
2081 isl_int_clear(mod);
2083 return isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2084 map = isl_map_reverse(map);
2087 /* Project out the parameter "id" from "set".
2089 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2090 __isl_keep isl_id *id)
2092 int pos;
2094 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2095 if (pos >= 0)
2096 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2098 return set;
2101 /* Compute the set of parameters for which "set1" is a subset of "set2".
2103 * set1 is a subset of set2 if
2105 * forall i in set1 : i in set2
2107 * or
2109 * not exists i in set1 and i not in set2
2111 * i.e.,
2113 * not exists i in set1 \ set2
2115 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2116 __isl_take isl_set *set2)
2118 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2121 /* Compute the set of parameter values for which "cond" holds
2122 * on the next iteration for each element of "dom".
2124 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2125 * and then compute the set of parameters for which the result is a subset
2126 * of "cond".
2128 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2129 __isl_take isl_set *dom, isl_int inc)
2131 isl_space *space;
2132 isl_aff *aff;
2133 isl_map *next;
2135 space = isl_set_get_space(dom);
2136 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2137 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2138 aff = isl_aff_add_constant(aff, inc);
2139 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2141 dom = isl_set_apply(dom, next);
2143 return enforce_subset(dom, cond);
2146 /* Construct a pet_scop for a for statement.
2147 * The for loop is required to be of the form
2149 * for (i = init; condition; ++i)
2151 * or
2153 * for (i = init; condition; --i)
2155 * The initialization of the for loop should either be an assignment
2156 * to an integer variable, or a declaration of such a variable with
2157 * initialization.
2159 * The condition is allowed to contain nested accesses, provided
2160 * they are not being written to inside the body of the loop.
2162 * We extract a pet_scop for the body and then embed it in a loop with
2163 * iteration domain and schedule
2165 * { [i] : i >= init and condition' }
2166 * { [i] -> [i] }
2168 * or
2170 * { [i] : i <= init and condition' }
2171 * { [i] -> [-i] }
2173 * Where condition' is equal to condition if the latter is
2174 * a simple upper [lower] bound and a condition that is extended
2175 * to apply to all previous iterations otherwise.
2177 * If the stride of the loop is not 1, then "i >= init" is replaced by
2179 * (exists a: i = init + stride * a and a >= 0)
2181 * If the loop iterator i is unsigned, then wrapping may occur.
2182 * During the computation, we work with a virtual iterator that
2183 * does not wrap. However, the condition in the code applies
2184 * to the wrapped value, so we need to change condition(i)
2185 * into condition([i % 2^width]).
2186 * After computing the virtual domain and schedule, we apply
2187 * the function { [v] -> [v % 2^width] } to the domain and the domain
2188 * of the schedule. In order not to lose any information, we also
2189 * need to intersect the domain of the schedule with the virtual domain
2190 * first, since some iterations in the wrapped domain may be scheduled
2191 * several times, typically an infinite number of times.
2192 * Note that there is no need to perform this final wrapping
2193 * if the loop condition (after wrapping) is simple.
2195 * Wrapping on unsigned iterators can be avoided entirely if
2196 * loop condition is simple, the loop iterator is incremented
2197 * [decremented] by one and the last value before wrapping cannot
2198 * possibly satisfy the loop condition.
2200 * Before extracting a pet_scop from the body we remove all
2201 * assignments in assigned_value to variables that are assigned
2202 * somewhere in the body of the loop.
2204 * Valid parameters for a for loop are those for which the initial
2205 * value itself, the increment on each domain iteration and
2206 * the condition on both the initial value and
2207 * the result of incrementing the iterator for each iteration of the domain
2208 * can be evaluated.
2210 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2212 BinaryOperator *ass;
2213 Decl *decl;
2214 Stmt *init;
2215 Expr *lhs, *rhs;
2216 ValueDecl *iv;
2217 isl_space *dim;
2218 isl_set *domain;
2219 isl_map *sched;
2220 isl_set *cond = NULL;
2221 isl_id *id;
2222 struct pet_scop *scop;
2223 assigned_value_cache cache(assigned_value);
2224 isl_int inc;
2225 bool is_one;
2226 bool is_unsigned;
2227 bool is_simple;
2228 bool is_virtual;
2229 isl_map *wrap = NULL;
2230 isl_pw_aff *pa, *pa_inc, *init_val;
2231 isl_set *valid_init;
2232 isl_set *valid_cond;
2233 isl_set *valid_cond_init;
2234 isl_set *valid_cond_next;
2235 isl_set *valid_inc;
2237 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2238 return extract_infinite_for(stmt);
2240 init = stmt->getInit();
2241 if (!init) {
2242 unsupported(stmt);
2243 return NULL;
2245 if ((ass = initialization_assignment(init)) != NULL) {
2246 iv = extract_induction_variable(ass);
2247 if (!iv)
2248 return NULL;
2249 lhs = ass->getLHS();
2250 rhs = ass->getRHS();
2251 } else if ((decl = initialization_declaration(init)) != NULL) {
2252 VarDecl *var = extract_induction_variable(init, decl);
2253 if (!var)
2254 return NULL;
2255 iv = var;
2256 rhs = var->getInit();
2257 lhs = create_DeclRefExpr(var);
2258 } else {
2259 unsupported(stmt->getInit());
2260 return NULL;
2263 pa_inc = extract_increment(stmt, iv);
2264 if (!pa_inc)
2265 return NULL;
2267 isl_int_init(inc);
2268 if (isl_pw_aff_n_piece(pa_inc) != 1 ||
2269 isl_pw_aff_foreach_piece(pa_inc, &extract_cst, &inc) < 0) {
2270 isl_pw_aff_free(pa_inc);
2271 unsupported(stmt->getInc());
2272 isl_int_clear(inc);
2273 return NULL;
2275 valid_inc = isl_pw_aff_domain(pa_inc);
2277 is_unsigned = iv->getType()->isUnsignedIntegerType();
2279 assigned_value.erase(iv);
2280 clear_assignments clear(assigned_value);
2281 clear.TraverseStmt(stmt->getBody());
2283 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2285 scop = extract(stmt->getBody());
2287 pa = try_extract_nested_condition(stmt->getCond());
2288 if (pa && !is_nested_allowed(pa, scop)) {
2289 isl_pw_aff_free(pa);
2290 pa = NULL;
2293 if (!pa)
2294 pa = extract_condition(stmt->getCond());
2295 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2296 cond = isl_pw_aff_non_zero_set(pa);
2297 cond = embed(cond, isl_id_copy(id));
2298 valid_cond = isl_set_coalesce(valid_cond);
2299 valid_cond = embed(valid_cond, isl_id_copy(id));
2300 valid_inc = embed(valid_inc, isl_id_copy(id));
2301 is_one = isl_int_is_one(inc) || isl_int_is_negone(inc);
2302 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
2304 init_val = extract_affine(rhs);
2305 valid_cond_init = enforce_subset(
2306 isl_set_from_pw_aff(isl_pw_aff_copy(init_val)),
2307 isl_set_copy(valid_cond));
2308 if (is_one && !is_virtual) {
2309 isl_pw_aff_free(init_val);
2310 pa = extract_comparison(isl_int_is_pos(inc) ? BO_GE : BO_LE,
2311 lhs, rhs, init);
2312 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2313 valid_init = set_project_out_by_id(valid_init, id);
2314 domain = isl_pw_aff_non_zero_set(pa);
2315 } else {
2316 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
2317 domain = strided_domain(isl_id_copy(id), init_val, inc);
2320 domain = embed(domain, isl_id_copy(id));
2321 if (is_virtual) {
2322 isl_map *rev_wrap;
2323 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2324 rev_wrap = isl_map_reverse(isl_map_copy(wrap));
2325 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
2326 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
2327 valid_inc = isl_set_apply(valid_inc, rev_wrap);
2329 cond = isl_set_gist(cond, isl_set_copy(domain));
2330 is_simple = is_simple_bound(cond, inc);
2331 if (!is_simple)
2332 cond = valid_for_each_iteration(cond,
2333 isl_set_copy(domain), inc);
2334 domain = isl_set_intersect(domain, cond);
2335 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2336 dim = isl_space_from_domain(isl_set_get_space(domain));
2337 dim = isl_space_add_dims(dim, isl_dim_out, 1);
2338 sched = isl_map_universe(dim);
2339 if (isl_int_is_pos(inc))
2340 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
2341 else
2342 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
2344 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain), inc);
2345 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
2347 if (is_virtual && !is_simple) {
2348 wrap = isl_map_set_dim_id(wrap,
2349 isl_dim_out, 0, isl_id_copy(id));
2350 sched = isl_map_intersect_domain(sched, isl_set_copy(domain));
2351 domain = isl_set_apply(domain, isl_map_copy(wrap));
2352 sched = isl_map_apply_domain(sched, wrap);
2353 } else
2354 isl_map_free(wrap);
2356 scop = pet_scop_embed(scop, domain, sched, id);
2357 scop = resolve_nested(scop);
2358 clear_assignment(assigned_value, iv);
2360 isl_int_clear(inc);
2362 scop = pet_scop_restrict_context(scop, valid_init);
2363 scop = pet_scop_restrict_context(scop, valid_inc);
2364 scop = pet_scop_restrict_context(scop, valid_cond_next);
2365 scop = pet_scop_restrict_context(scop, valid_cond_init);
2367 return scop;
2370 struct pet_scop *PetScan::extract(CompoundStmt *stmt)
2372 return extract(stmt->children());
2375 /* Does "id" refer to a nested access?
2377 static bool is_nested_parameter(__isl_keep isl_id *id)
2379 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2382 /* Does parameter "pos" of "space" refer to a nested access?
2384 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2386 bool nested;
2387 isl_id *id;
2389 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2390 nested = is_nested_parameter(id);
2391 isl_id_free(id);
2393 return nested;
2396 /* Does parameter "pos" of "map" refer to a nested access?
2398 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
2400 bool nested;
2401 isl_id *id;
2403 id = isl_map_get_dim_id(map, isl_dim_param, pos);
2404 nested = is_nested_parameter(id);
2405 isl_id_free(id);
2407 return nested;
2410 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2412 static int n_nested_parameter(__isl_keep isl_space *space)
2414 int n = 0;
2415 int nparam;
2417 nparam = isl_space_dim(space, isl_dim_param);
2418 for (int i = 0; i < nparam; ++i)
2419 if (is_nested_parameter(space, i))
2420 ++n;
2422 return n;
2425 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2427 static int n_nested_parameter(__isl_keep isl_map *map)
2429 isl_space *space;
2430 int n;
2432 space = isl_map_get_space(map);
2433 n = n_nested_parameter(space);
2434 isl_space_free(space);
2436 return n;
2439 /* For each nested access parameter in "space",
2440 * construct a corresponding pet_expr, place it in args and
2441 * record its position in "param2pos".
2442 * "n_arg" is the number of elements that are already in args.
2443 * The position recorded in "param2pos" takes this number into account.
2444 * If the pet_expr corresponding to a parameter is identical to
2445 * the pet_expr corresponding to an earlier parameter, then these two
2446 * parameters are made to refer to the same element in args.
2448 * Return the final number of elements in args or -1 if an error has occurred.
2450 int PetScan::extract_nested(__isl_keep isl_space *space,
2451 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
2453 int nparam;
2455 nparam = isl_space_dim(space, isl_dim_param);
2456 for (int i = 0; i < nparam; ++i) {
2457 int j;
2458 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2459 Expr *nested;
2461 if (!is_nested_parameter(id)) {
2462 isl_id_free(id);
2463 continue;
2466 nested = (Expr *) isl_id_get_user(id);
2467 args[n_arg] = extract_expr(nested);
2468 if (!args[n_arg])
2469 return -1;
2471 for (j = 0; j < n_arg; ++j)
2472 if (pet_expr_is_equal(args[j], args[n_arg]))
2473 break;
2475 if (j < n_arg) {
2476 pet_expr_free(args[n_arg]);
2477 args[n_arg] = NULL;
2478 param2pos[i] = j;
2479 } else
2480 param2pos[i] = n_arg++;
2482 isl_id_free(id);
2485 return n_arg;
2488 /* For each nested access parameter in the access relations in "expr",
2489 * construct a corresponding pet_expr, place it in expr->args and
2490 * record its position in "param2pos".
2491 * n is the number of nested access parameters.
2493 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
2494 std::map<int,int> &param2pos)
2496 isl_space *space;
2498 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
2499 expr->n_arg = n;
2500 if (!expr->args)
2501 goto error;
2503 space = isl_map_get_space(expr->acc.access);
2504 n = extract_nested(space, 0, expr->args, param2pos);
2505 isl_space_free(space);
2507 if (n < 0)
2508 goto error;
2510 expr->n_arg = n;
2511 return expr;
2512 error:
2513 pet_expr_free(expr);
2514 return NULL;
2517 /* Look for parameters in any access relation in "expr" that
2518 * refer to nested accesses. In particular, these are
2519 * parameters with no name.
2521 * If there are any such parameters, then the domain of the access
2522 * relation, which is still [] at this point, is replaced by
2523 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2524 * (after identifying identical nested accesses).
2525 * The parameters are then equated to the corresponding t dimensions
2526 * and subsequently projected out.
2527 * param2pos maps the position of the parameter to the position
2528 * of the corresponding t dimension.
2530 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
2532 int n;
2533 int nparam;
2534 int n_in;
2535 isl_space *dim;
2536 isl_map *map;
2537 std::map<int,int> param2pos;
2539 if (!expr)
2540 return expr;
2542 for (int i = 0; i < expr->n_arg; ++i) {
2543 expr->args[i] = resolve_nested(expr->args[i]);
2544 if (!expr->args[i]) {
2545 pet_expr_free(expr);
2546 return NULL;
2550 if (expr->type != pet_expr_access)
2551 return expr;
2553 n = n_nested_parameter(expr->acc.access);
2554 if (n == 0)
2555 return expr;
2557 expr = extract_nested(expr, n, param2pos);
2558 if (!expr)
2559 return NULL;
2561 n = expr->n_arg;
2562 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
2563 n_in = isl_map_dim(expr->acc.access, isl_dim_in);
2564 dim = isl_map_get_space(expr->acc.access);
2565 dim = isl_space_domain(dim);
2566 dim = isl_space_from_domain(dim);
2567 dim = isl_space_add_dims(dim, isl_dim_out, n);
2568 map = isl_map_universe(dim);
2569 map = isl_map_domain_map(map);
2570 map = isl_map_reverse(map);
2571 expr->acc.access = isl_map_apply_domain(expr->acc.access, map);
2573 for (int i = nparam - 1; i >= 0; --i) {
2574 isl_id *id = isl_map_get_dim_id(expr->acc.access,
2575 isl_dim_param, i);
2576 if (!is_nested_parameter(id)) {
2577 isl_id_free(id);
2578 continue;
2581 expr->acc.access = isl_map_equate(expr->acc.access,
2582 isl_dim_param, i, isl_dim_in,
2583 n_in + param2pos[i]);
2584 expr->acc.access = isl_map_project_out(expr->acc.access,
2585 isl_dim_param, i, 1);
2587 isl_id_free(id);
2590 return expr;
2591 error:
2592 pet_expr_free(expr);
2593 return NULL;
2596 /* Convert a top-level pet_expr to a pet_scop with one statement.
2597 * This mainly involves resolving nested expression parameters
2598 * and setting the name of the iteration space.
2599 * The name is given by "label" if it is non-NULL. Otherwise,
2600 * it is of the form S_<n_stmt>.
2602 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
2603 __isl_take isl_id *label)
2605 struct pet_stmt *ps;
2606 SourceLocation loc = stmt->getLocStart();
2607 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2609 expr = resolve_nested(expr);
2610 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
2611 return pet_scop_from_pet_stmt(ctx, ps);
2614 /* Check if we can extract an affine expression from "expr".
2615 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
2616 * We turn on autodetection so that we won't generate any warnings
2617 * and turn off nesting, so that we won't accept any non-affine constructs.
2619 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
2621 isl_pw_aff *pwaff;
2622 int save_autodetect = options->autodetect;
2623 bool save_nesting = nesting_enabled;
2625 options->autodetect = 1;
2626 nesting_enabled = false;
2628 pwaff = extract_affine(expr);
2630 options->autodetect = save_autodetect;
2631 nesting_enabled = save_nesting;
2633 return pwaff;
2636 /* Check whether "expr" is an affine expression.
2638 bool PetScan::is_affine(Expr *expr)
2640 isl_pw_aff *pwaff;
2642 pwaff = try_extract_affine(expr);
2643 isl_pw_aff_free(pwaff);
2645 return pwaff != NULL;
2648 /* Check if we can extract an affine constraint from "expr".
2649 * Return the constraint as an isl_set if we can and NULL otherwise.
2650 * We turn on autodetection so that we won't generate any warnings
2651 * and turn off nesting, so that we won't accept any non-affine constructs.
2653 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
2655 isl_pw_aff *cond;
2656 int save_autodetect = options->autodetect;
2657 bool save_nesting = nesting_enabled;
2659 options->autodetect = 1;
2660 nesting_enabled = false;
2662 cond = extract_condition(expr);
2664 options->autodetect = save_autodetect;
2665 nesting_enabled = save_nesting;
2667 return cond;
2670 /* Check whether "expr" is an affine constraint.
2672 bool PetScan::is_affine_condition(Expr *expr)
2674 isl_pw_aff *cond;
2676 cond = try_extract_affine_condition(expr);
2677 isl_pw_aff_free(cond);
2679 return cond != NULL;
2682 /* Check if we can extract a condition from "expr".
2683 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
2684 * If allow_nested is set, then the condition may involve parameters
2685 * corresponding to nested accesses.
2686 * We turn on autodetection so that we won't generate any warnings.
2688 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
2690 isl_pw_aff *cond;
2691 int save_autodetect = options->autodetect;
2692 bool save_nesting = nesting_enabled;
2694 options->autodetect = 1;
2695 nesting_enabled = allow_nested;
2696 cond = extract_condition(expr);
2698 options->autodetect = save_autodetect;
2699 nesting_enabled = save_nesting;
2701 return cond;
2704 /* If the top-level expression of "stmt" is an assignment, then
2705 * return that assignment as a BinaryOperator.
2706 * Otherwise return NULL.
2708 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
2710 BinaryOperator *ass;
2712 if (!stmt)
2713 return NULL;
2714 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
2715 return NULL;
2717 ass = cast<BinaryOperator>(stmt);
2718 if(ass->getOpcode() != BO_Assign)
2719 return NULL;
2721 return ass;
2724 /* Check if the given if statement is a conditional assignement
2725 * with a non-affine condition. If so, construct a pet_scop
2726 * corresponding to this conditional assignment. Otherwise return NULL.
2728 * In particular we check if "stmt" is of the form
2730 * if (condition)
2731 * a = f(...);
2732 * else
2733 * a = g(...);
2735 * where a is some array or scalar access.
2736 * The constructed pet_scop then corresponds to the expression
2738 * a = condition ? f(...) : g(...)
2740 * All access relations in f(...) are intersected with condition
2741 * while all access relation in g(...) are intersected with the complement.
2743 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
2745 BinaryOperator *ass_then, *ass_else;
2746 isl_map *write_then, *write_else;
2747 isl_set *cond, *comp;
2748 isl_map *map;
2749 isl_pw_aff *pa;
2750 int equal;
2751 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
2752 bool save_nesting = nesting_enabled;
2754 if (!options->detect_conditional_assignment)
2755 return NULL;
2757 ass_then = top_assignment_or_null(stmt->getThen());
2758 ass_else = top_assignment_or_null(stmt->getElse());
2760 if (!ass_then || !ass_else)
2761 return NULL;
2763 if (is_affine_condition(stmt->getCond()))
2764 return NULL;
2766 write_then = extract_access(ass_then->getLHS());
2767 write_else = extract_access(ass_else->getLHS());
2769 equal = isl_map_is_equal(write_then, write_else);
2770 isl_map_free(write_else);
2771 if (equal < 0 || !equal) {
2772 isl_map_free(write_then);
2773 return NULL;
2776 nesting_enabled = allow_nested;
2777 pa = extract_condition(stmt->getCond());
2778 nesting_enabled = save_nesting;
2779 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
2780 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
2781 map = isl_map_from_range(isl_set_from_pw_aff(pa));
2783 pe_cond = pet_expr_from_access(map);
2785 pe_then = extract_expr(ass_then->getRHS());
2786 pe_then = pet_expr_restrict(pe_then, cond);
2787 pe_else = extract_expr(ass_else->getRHS());
2788 pe_else = pet_expr_restrict(pe_else, comp);
2790 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
2791 pe_write = pet_expr_from_access(write_then);
2792 if (pe_write) {
2793 pe_write->acc.write = 1;
2794 pe_write->acc.read = 0;
2796 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
2797 return extract(stmt, pe);
2800 /* Create an access to a virtual array representing the result
2801 * of a condition.
2802 * Unlike other accessed data, the id of the array is NULL as
2803 * there is no ValueDecl in the program corresponding to the virtual
2804 * array.
2805 * The array starts out as a scalar, but grows along with the
2806 * statement writing to the array in pet_scop_embed.
2808 static __isl_give isl_map *create_test_access(isl_ctx *ctx, int test_nr)
2810 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2811 isl_id *id;
2812 char name[50];
2814 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2815 id = isl_id_alloc(ctx, name, NULL);
2816 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2817 return isl_map_universe(dim);
2820 /* Create a pet_scop with a single statement evaluating "cond"
2821 * and writing the result to a virtual scalar, as expressed by
2822 * "access".
2824 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond,
2825 __isl_take isl_map *access)
2827 struct pet_expr *expr, *write;
2828 struct pet_stmt *ps;
2829 struct pet_scop *scop;
2830 SourceLocation loc = cond->getLocStart();
2831 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2833 write = pet_expr_from_access(access);
2834 if (write) {
2835 write->acc.write = 1;
2836 write->acc.read = 0;
2838 expr = extract_expr(cond);
2839 expr = resolve_nested(expr);
2840 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
2841 ps = pet_stmt_from_pet_expr(ctx, line, NULL, n_stmt++, expr);
2842 scop = pet_scop_from_pet_stmt(ctx, ps);
2843 scop = resolve_nested(scop);
2845 return scop;
2848 /* Add an array with the given extent ("access") to the list
2849 * of arrays in "scop" and return the extended pet_scop.
2850 * The array is marked as attaining values 0 and 1 only and
2851 * as each element being assigned at most once.
2853 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2854 __isl_keep isl_map *access, clang::ASTContext &ast_ctx)
2856 isl_ctx *ctx = isl_map_get_ctx(access);
2857 isl_space *dim;
2858 struct pet_array **arrays;
2859 struct pet_array *array;
2861 if (!scop)
2862 return NULL;
2863 if (!ctx)
2864 goto error;
2866 arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2867 scop->n_array + 1);
2868 if (!arrays)
2869 goto error;
2870 scop->arrays = arrays;
2872 array = isl_calloc_type(ctx, struct pet_array);
2873 if (!array)
2874 goto error;
2876 array->extent = isl_map_range(isl_map_copy(access));
2877 dim = isl_space_params_alloc(ctx, 0);
2878 array->context = isl_set_universe(dim);
2879 dim = isl_space_set_alloc(ctx, 0, 1);
2880 array->value_bounds = isl_set_universe(dim);
2881 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2882 isl_dim_set, 0, 0);
2883 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2884 isl_dim_set, 0, 1);
2885 array->element_type = strdup("int");
2886 array->element_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2887 array->uniquely_defined = 1;
2889 scop->arrays[scop->n_array] = array;
2890 scop->n_array++;
2892 if (!array->extent || !array->context)
2893 goto error;
2895 return scop;
2896 error:
2897 pet_scop_free(scop);
2898 return NULL;
2901 extern "C" {
2902 static __isl_give isl_map *embed_access(__isl_take isl_map *access,
2903 void *user);
2906 /* Apply the map pointed to by "user" to the domain of the access
2907 * relation, thereby embedding it in the range of the map.
2908 * The domain of both relations is the zero-dimensional domain.
2910 static __isl_give isl_map *embed_access(__isl_take isl_map *access, void *user)
2912 isl_map *map = (isl_map *) user;
2914 return isl_map_apply_domain(access, isl_map_copy(map));
2917 /* Apply "map" to all access relations in "expr".
2919 static struct pet_expr *embed(struct pet_expr *expr, __isl_keep isl_map *map)
2921 return pet_expr_foreach_access(expr, &embed_access, map);
2924 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
2926 static int n_nested_parameter(__isl_keep isl_set *set)
2928 isl_space *space;
2929 int n;
2931 space = isl_set_get_space(set);
2932 n = n_nested_parameter(space);
2933 isl_space_free(space);
2935 return n;
2938 /* Remove all parameters from "map" that refer to nested accesses.
2940 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
2942 int nparam;
2943 isl_space *space;
2945 space = isl_map_get_space(map);
2946 nparam = isl_space_dim(space, isl_dim_param);
2947 for (int i = nparam - 1; i >= 0; --i)
2948 if (is_nested_parameter(space, i))
2949 map = isl_map_project_out(map, isl_dim_param, i, 1);
2950 isl_space_free(space);
2952 return map;
2955 extern "C" {
2956 static __isl_give isl_map *access_remove_nested_parameters(
2957 __isl_take isl_map *access, void *user);
2960 static __isl_give isl_map *access_remove_nested_parameters(
2961 __isl_take isl_map *access, void *user)
2963 return remove_nested_parameters(access);
2966 /* Remove all nested access parameters from the schedule and all
2967 * accesses of "stmt".
2968 * There is no need to remove them from the domain as these parameters
2969 * have already been removed from the domain when this function is called.
2971 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
2973 if (!stmt)
2974 return NULL;
2975 stmt->schedule = remove_nested_parameters(stmt->schedule);
2976 stmt->body = pet_expr_foreach_access(stmt->body,
2977 &access_remove_nested_parameters, NULL);
2978 if (!stmt->schedule || !stmt->body)
2979 goto error;
2980 for (int i = 0; i < stmt->n_arg; ++i) {
2981 stmt->args[i] = pet_expr_foreach_access(stmt->args[i],
2982 &access_remove_nested_parameters, NULL);
2983 if (!stmt->args[i])
2984 goto error;
2987 return stmt;
2988 error:
2989 pet_stmt_free(stmt);
2990 return NULL;
2993 /* For each nested access parameter in the domain of "stmt",
2994 * construct a corresponding pet_expr, place it before the original
2995 * elements in stmt->args and record its position in "param2pos".
2996 * n is the number of nested access parameters.
2998 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
2999 std::map<int,int> &param2pos)
3001 int i;
3002 isl_space *space;
3003 int n_arg;
3004 struct pet_expr **args;
3006 n_arg = stmt->n_arg;
3007 args = isl_calloc_array(ctx, struct pet_expr *, n + n_arg);
3008 if (!args)
3009 goto error;
3011 space = isl_set_get_space(stmt->domain);
3012 n_arg = extract_nested(space, 0, args, param2pos);
3013 isl_space_free(space);
3015 if (n_arg < 0)
3016 goto error;
3018 for (i = 0; i < stmt->n_arg; ++i)
3019 args[n_arg + i] = stmt->args[i];
3020 free(stmt->args);
3021 stmt->args = args;
3022 stmt->n_arg += n_arg;
3024 return stmt;
3025 error:
3026 if (args) {
3027 for (i = 0; i < n; ++i)
3028 pet_expr_free(args[i]);
3029 free(args);
3031 pet_stmt_free(stmt);
3032 return NULL;
3035 /* Check whether any of the arguments i of "stmt" starting at position "n"
3036 * is equal to one of the first "n" arguments j.
3037 * If so, combine the constraints on arguments i and j and remove
3038 * argument i.
3040 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3042 int i, j;
3043 isl_map *map;
3045 if (!stmt)
3046 return NULL;
3047 if (n == 0)
3048 return stmt;
3049 if (n == stmt->n_arg)
3050 return stmt;
3052 map = isl_set_unwrap(stmt->domain);
3054 for (i = stmt->n_arg - 1; i >= n; --i) {
3055 for (j = 0; j < n; ++j)
3056 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3057 break;
3058 if (j >= n)
3059 continue;
3061 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3062 map = isl_map_project_out(map, isl_dim_out, i, 1);
3064 pet_expr_free(stmt->args[i]);
3065 for (j = i; j + 1 < stmt->n_arg; ++j)
3066 stmt->args[j] = stmt->args[j + 1];
3067 stmt->n_arg--;
3070 stmt->domain = isl_map_wrap(map);
3071 if (!stmt->domain)
3072 goto error;
3073 return stmt;
3074 error:
3075 pet_stmt_free(stmt);
3076 return NULL;
3079 /* Look for parameters in the iteration domain of "stmt" that
3080 * refer to nested accesses. In particular, these are
3081 * parameters with no name.
3083 * If there are any such parameters, then as many extra variables
3084 * (after identifying identical nested accesses) are inserted in the
3085 * range of the map wrapped inside the domain, before the original variables.
3086 * If the original domain is not a wrapped map, then a new wrapped
3087 * map is created with zero output dimensions.
3088 * The parameters are then equated to the corresponding output dimensions
3089 * and subsequently projected out, from the iteration domain,
3090 * the schedule and the access relations.
3091 * For each of the output dimensions, a corresponding argument
3092 * expression is inserted. Initially they are created with
3093 * a zero-dimensional domain, so they have to be embedded
3094 * in the current iteration domain.
3095 * param2pos maps the position of the parameter to the position
3096 * of the corresponding output dimension in the wrapped map.
3098 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3100 int n;
3101 int nparam;
3102 unsigned n_arg;
3103 isl_map *map;
3104 std::map<int,int> param2pos;
3106 if (!stmt)
3107 return NULL;
3109 n = n_nested_parameter(stmt->domain);
3110 if (n == 0)
3111 return stmt;
3113 n_arg = stmt->n_arg;
3114 stmt = extract_nested(stmt, n, param2pos);
3115 if (!stmt)
3116 return NULL;
3118 n = stmt->n_arg - n_arg;
3119 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3120 if (isl_set_is_wrapping(stmt->domain))
3121 map = isl_set_unwrap(stmt->domain);
3122 else
3123 map = isl_map_from_domain(stmt->domain);
3124 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3126 for (int i = nparam - 1; i >= 0; --i) {
3127 isl_id *id;
3129 if (!is_nested_parameter(map, i))
3130 continue;
3132 id = isl_map_get_tuple_id(stmt->args[param2pos[i]]->acc.access,
3133 isl_dim_out);
3134 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3135 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3136 param2pos[i]);
3137 map = isl_map_project_out(map, isl_dim_param, i, 1);
3140 stmt->domain = isl_map_wrap(map);
3142 map = isl_set_unwrap(isl_set_copy(stmt->domain));
3143 map = isl_map_from_range(isl_map_domain(map));
3144 for (int pos = 0; pos < n; ++pos)
3145 stmt->args[pos] = embed(stmt->args[pos], map);
3146 isl_map_free(map);
3148 stmt = remove_nested_parameters(stmt);
3149 stmt = remove_duplicate_arguments(stmt, n);
3151 return stmt;
3152 error:
3153 pet_stmt_free(stmt);
3154 return NULL;
3157 /* For each statement in "scop", move the parameters that correspond
3158 * to nested access into the ranges of the domains and create
3159 * corresponding argument expressions.
3161 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3163 if (!scop)
3164 return NULL;
3166 for (int i = 0; i < scop->n_stmt; ++i) {
3167 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3168 if (!scop->stmts[i])
3169 goto error;
3172 return scop;
3173 error:
3174 pet_scop_free(scop);
3175 return NULL;
3178 /* Does "space" involve any parameters that refer to nested
3179 * accesses, i.e., parameters with no name?
3181 static bool has_nested(__isl_keep isl_space *space)
3183 int nparam;
3185 nparam = isl_space_dim(space, isl_dim_param);
3186 for (int i = 0; i < nparam; ++i)
3187 if (is_nested_parameter(space, i))
3188 return true;
3190 return false;
3193 /* Does "pa" involve any parameters that refer to nested
3194 * accesses, i.e., parameters with no name?
3196 static bool has_nested(__isl_keep isl_pw_aff *pa)
3198 isl_space *space;
3199 bool nested;
3201 space = isl_pw_aff_get_space(pa);
3202 nested = has_nested(space);
3203 isl_space_free(space);
3205 return nested;
3208 /* Given an access expression "expr", is the variable accessed by
3209 * "expr" assigned anywhere inside "scop"?
3211 static bool is_assigned(pet_expr *expr, pet_scop *scop)
3213 bool assigned = false;
3214 isl_id *id;
3216 id = isl_map_get_tuple_id(expr->acc.access, isl_dim_out);
3217 assigned = pet_scop_writes(scop, id);
3218 isl_id_free(id);
3220 return assigned;
3223 /* Are all nested access parameters in "pa" allowed given "scop".
3224 * In particular, is none of them written by anywhere inside "scop".
3226 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3228 int nparam;
3230 nparam = isl_pw_aff_dim(pa, isl_dim_param);
3231 for (int i = 0; i < nparam; ++i) {
3232 Expr *nested;
3233 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
3234 pet_expr *expr;
3235 bool allowed;
3237 if (!is_nested_parameter(id)) {
3238 isl_id_free(id);
3239 continue;
3242 nested = (Expr *) isl_id_get_user(id);
3243 expr = extract_expr(nested);
3244 allowed = expr && expr->type == pet_expr_access &&
3245 !is_assigned(expr, scop);
3247 pet_expr_free(expr);
3248 isl_id_free(id);
3250 if (!allowed)
3251 return false;
3254 return true;
3257 /* Construct a pet_scop for an if statement.
3259 * If the condition fits the pattern of a conditional assignment,
3260 * then it is handled by extract_conditional_assignment.
3261 * Otherwise, we do the following.
3263 * If the condition is affine, then the condition is added
3264 * to the iteration domains of the then branch, while the
3265 * opposite of the condition in added to the iteration domains
3266 * of the else branch, if any.
3267 * We allow the condition to be dynamic, i.e., to refer to
3268 * scalars or array elements that may be written to outside
3269 * of the given if statement. These nested accesses are then represented
3270 * as output dimensions in the wrapping iteration domain.
3271 * If it also written _inside_ the then or else branch, then
3272 * we treat the condition as non-affine.
3273 * As explained below, this will introduce an extra statement.
3274 * For aesthetic reasons, we want this statement to have a statement
3275 * number that is lower than those of the then and else branches.
3276 * In order to evaluate if will need such a statement, however, we
3277 * first construct scops for the then and else branches.
3278 * We therefore reserve a statement number if we might have to
3279 * introduce such an extra statement.
3281 * If the condition is not affine, then we create a separate
3282 * statement that writes the result of the condition to a virtual scalar.
3283 * A constraint requiring the value of this virtual scalar to be one
3284 * is added to the iteration domains of the then branch.
3285 * Similarly, a constraint requiring the value of this virtual scalar
3286 * to be zero is added to the iteration domains of the else branch, if any.
3287 * We adjust the schedules to ensure that the virtual scalar is written
3288 * before it is read.
3290 struct pet_scop *PetScan::extract(IfStmt *stmt)
3292 struct pet_scop *scop_then, *scop_else, *scop;
3293 isl_map *test_access = NULL;
3294 isl_pw_aff *cond;
3295 int stmt_id;
3297 scop = extract_conditional_assignment(stmt);
3298 if (scop)
3299 return scop;
3301 cond = try_extract_nested_condition(stmt->getCond());
3302 if (allow_nested && (!cond || has_nested(cond)))
3303 stmt_id = n_stmt++;
3306 assigned_value_cache cache(assigned_value);
3307 scop_then = extract(stmt->getThen());
3310 if (stmt->getElse()) {
3311 assigned_value_cache cache(assigned_value);
3312 scop_else = extract(stmt->getElse());
3313 if (options->autodetect) {
3314 if (scop_then && !scop_else) {
3315 partial = true;
3316 isl_pw_aff_free(cond);
3317 return scop_then;
3319 if (!scop_then && scop_else) {
3320 partial = true;
3321 isl_pw_aff_free(cond);
3322 return scop_else;
3327 if (cond &&
3328 (!is_nested_allowed(cond, scop_then) ||
3329 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
3330 isl_pw_aff_free(cond);
3331 cond = NULL;
3333 if (allow_nested && !cond) {
3334 int save_n_stmt = n_stmt;
3335 test_access = create_test_access(ctx, n_test++);
3336 n_stmt = stmt_id;
3337 scop = extract_non_affine_condition(stmt->getCond(),
3338 isl_map_copy(test_access));
3339 n_stmt = save_n_stmt;
3340 scop = scop_add_array(scop, test_access, ast_context);
3341 if (!scop) {
3342 pet_scop_free(scop_then);
3343 pet_scop_free(scop_else);
3344 isl_map_free(test_access);
3345 return NULL;
3349 if (!scop) {
3350 isl_set *set;
3351 isl_set *valid;
3353 if (!cond)
3354 cond = extract_condition(stmt->getCond());
3355 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
3356 set = isl_pw_aff_non_zero_set(cond);
3357 scop = pet_scop_restrict(scop_then, isl_set_copy(set));
3359 if (stmt->getElse()) {
3360 set = isl_set_subtract(isl_set_copy(valid), set);
3361 scop_else = pet_scop_restrict(scop_else, set);
3362 scop = pet_scop_add(ctx, scop, scop_else);
3363 } else
3364 isl_set_free(set);
3365 scop = resolve_nested(scop);
3366 scop = pet_scop_restrict_context(scop, valid);
3367 } else {
3368 scop = pet_scop_prefix(scop, 0);
3369 scop_then = pet_scop_prefix(scop_then, 1);
3370 scop_then = pet_scop_filter(scop_then,
3371 isl_map_copy(test_access), 1);
3372 scop = pet_scop_add(ctx, scop, scop_then);
3373 if (stmt->getElse()) {
3374 scop_else = pet_scop_prefix(scop_else, 1);
3375 scop_else = pet_scop_filter(scop_else, test_access, 0);
3376 scop = pet_scop_add(ctx, scop, scop_else);
3377 } else
3378 isl_map_free(test_access);
3381 return scop;
3384 /* Try and construct a pet_scop for a label statement.
3385 * We currently only allow labels on expression statements.
3387 struct pet_scop *PetScan::extract(LabelStmt *stmt)
3389 isl_id *label;
3390 Stmt *sub;
3392 sub = stmt->getSubStmt();
3393 if (!isa<Expr>(sub)) {
3394 unsupported(stmt);
3395 return NULL;
3398 label = isl_id_alloc(ctx, stmt->getName(), NULL);
3400 return extract(sub, extract_expr(cast<Expr>(sub)), label);
3403 /* Try and construct a pet_scop corresponding to "stmt".
3405 struct pet_scop *PetScan::extract(Stmt *stmt)
3407 if (isa<Expr>(stmt))
3408 return extract(stmt, extract_expr(cast<Expr>(stmt)));
3410 switch (stmt->getStmtClass()) {
3411 case Stmt::WhileStmtClass:
3412 return extract(cast<WhileStmt>(stmt));
3413 case Stmt::ForStmtClass:
3414 return extract_for(cast<ForStmt>(stmt));
3415 case Stmt::IfStmtClass:
3416 return extract(cast<IfStmt>(stmt));
3417 case Stmt::CompoundStmtClass:
3418 return extract(cast<CompoundStmt>(stmt));
3419 case Stmt::LabelStmtClass:
3420 return extract(cast<LabelStmt>(stmt));
3421 default:
3422 unsupported(stmt);
3425 return NULL;
3428 /* Try and construct a pet_scop corresponding to (part of)
3429 * a sequence of statements.
3431 struct pet_scop *PetScan::extract(StmtRange stmt_range)
3433 pet_scop *scop;
3434 StmtIterator i;
3435 int j;
3436 bool partial_range = false;
3438 scop = pet_scop_empty(ctx);
3439 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
3440 Stmt *child = *i;
3441 struct pet_scop *scop_i;
3442 scop_i = extract(child);
3443 if (scop && partial) {
3444 pet_scop_free(scop_i);
3445 break;
3447 scop_i = pet_scop_prefix(scop_i, j);
3448 if (options->autodetect) {
3449 if (scop_i)
3450 scop = pet_scop_add(ctx, scop, scop_i);
3451 else
3452 partial_range = true;
3453 if (scop->n_stmt != 0 && !scop_i)
3454 partial = true;
3455 } else {
3456 scop = pet_scop_add(ctx, scop, scop_i);
3458 if (partial)
3459 break;
3462 if (scop && partial_range)
3463 partial = true;
3465 return scop;
3468 /* Check if the scop marked by the user is exactly this Stmt
3469 * or part of this Stmt.
3470 * If so, return a pet_scop corresponding to the marked region.
3471 * Otherwise, return NULL.
3473 struct pet_scop *PetScan::scan(Stmt *stmt)
3475 SourceManager &SM = PP.getSourceManager();
3476 unsigned start_off, end_off;
3478 start_off = SM.getFileOffset(stmt->getLocStart());
3479 end_off = SM.getFileOffset(stmt->getLocEnd());
3481 if (start_off > loc.end)
3482 return NULL;
3483 if (end_off < loc.start)
3484 return NULL;
3485 if (start_off >= loc.start && end_off <= loc.end) {
3486 return extract(stmt);
3489 StmtIterator start;
3490 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
3491 Stmt *child = *start;
3492 if (!child)
3493 continue;
3494 start_off = SM.getFileOffset(child->getLocStart());
3495 end_off = SM.getFileOffset(child->getLocEnd());
3496 if (start_off < loc.start && end_off > loc.end)
3497 return scan(child);
3498 if (start_off >= loc.start)
3499 break;
3502 StmtIterator end;
3503 for (end = start; end != stmt->child_end(); ++end) {
3504 Stmt *child = *end;
3505 start_off = SM.getFileOffset(child->getLocStart());
3506 if (start_off >= loc.end)
3507 break;
3510 return extract(StmtRange(start, end));
3513 /* Set the size of index "pos" of "array" to "size".
3514 * In particular, add a constraint of the form
3516 * i_pos < size
3518 * to array->extent and a constraint of the form
3520 * size >= 0
3522 * to array->context.
3524 static struct pet_array *update_size(struct pet_array *array, int pos,
3525 __isl_take isl_pw_aff *size)
3527 isl_set *valid;
3528 isl_set *univ;
3529 isl_set *bound;
3530 isl_space *dim;
3531 isl_aff *aff;
3532 isl_pw_aff *index;
3533 isl_id *id;
3535 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
3536 array->context = isl_set_intersect(array->context, valid);
3538 dim = isl_set_get_space(array->extent);
3539 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
3540 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
3541 univ = isl_set_universe(isl_aff_get_domain_space(aff));
3542 index = isl_pw_aff_alloc(univ, aff);
3544 size = isl_pw_aff_add_dims(size, isl_dim_in,
3545 isl_set_dim(array->extent, isl_dim_set));
3546 id = isl_set_get_tuple_id(array->extent);
3547 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
3548 bound = isl_pw_aff_lt_set(index, size);
3550 array->extent = isl_set_intersect(array->extent, bound);
3552 if (!array->context || !array->extent)
3553 goto error;
3555 return array;
3556 error:
3557 pet_array_free(array);
3558 return NULL;
3561 /* Figure out the size of the array at position "pos" and all
3562 * subsequent positions from "type" and update "array" accordingly.
3564 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
3565 const Type *type, int pos)
3567 const ArrayType *atype;
3568 isl_pw_aff *size;
3570 if (!array)
3571 return NULL;
3573 if (type->isPointerType()) {
3574 type = type->getPointeeType().getTypePtr();
3575 return set_upper_bounds(array, type, pos + 1);
3577 if (!type->isArrayType())
3578 return array;
3580 type = type->getCanonicalTypeInternal().getTypePtr();
3581 atype = cast<ArrayType>(type);
3583 if (type->isConstantArrayType()) {
3584 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
3585 size = extract_affine(ca->getSize());
3586 array = update_size(array, pos, size);
3587 } else if (type->isVariableArrayType()) {
3588 const VariableArrayType *vla = cast<VariableArrayType>(atype);
3589 size = extract_affine(vla->getSizeExpr());
3590 array = update_size(array, pos, size);
3593 type = atype->getElementType().getTypePtr();
3595 return set_upper_bounds(array, type, pos + 1);
3598 /* Construct and return a pet_array corresponding to the variable "decl".
3599 * In particular, initialize array->extent to
3601 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
3603 * and then call set_upper_bounds to set the upper bounds on the indices
3604 * based on the type of the variable.
3606 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl)
3608 struct pet_array *array;
3609 QualType qt = decl->getType();
3610 const Type *type = qt.getTypePtr();
3611 int depth = array_depth(type);
3612 QualType base = base_type(qt);
3613 string name;
3614 isl_id *id;
3615 isl_space *dim;
3617 array = isl_calloc_type(ctx, struct pet_array);
3618 if (!array)
3619 return NULL;
3621 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
3622 dim = isl_space_set_alloc(ctx, 0, depth);
3623 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
3625 array->extent = isl_set_nat_universe(dim);
3627 dim = isl_space_params_alloc(ctx, 0);
3628 array->context = isl_set_universe(dim);
3630 array = set_upper_bounds(array, type, 0);
3631 if (!array)
3632 return NULL;
3634 name = base.getAsString();
3635 array->element_type = strdup(name.c_str());
3636 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
3638 return array;
3641 /* Construct a list of pet_arrays, one for each array (or scalar)
3642 * accessed inside "scop", add this list to "scop" and return the result.
3644 * The context of "scop" is updated with the intersection of
3645 * the contexts of all arrays, i.e., constraints on the parameters
3646 * that ensure that the arrays have a valid (non-negative) size.
3648 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
3650 int i;
3651 set<ValueDecl *> arrays;
3652 set<ValueDecl *>::iterator it;
3653 int n_array;
3654 struct pet_array **scop_arrays;
3656 if (!scop)
3657 return NULL;
3659 pet_scop_collect_arrays(scop, arrays);
3660 if (arrays.size() == 0)
3661 return scop;
3663 n_array = scop->n_array;
3665 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
3666 n_array + arrays.size());
3667 if (!scop_arrays)
3668 goto error;
3669 scop->arrays = scop_arrays;
3671 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
3672 struct pet_array *array;
3673 scop->arrays[n_array + i] = array = extract_array(ctx, *it);
3674 if (!scop->arrays[n_array + i])
3675 goto error;
3676 scop->n_array++;
3677 scop->context = isl_set_intersect(scop->context,
3678 isl_set_copy(array->context));
3679 if (!scop->context)
3680 goto error;
3683 return scop;
3684 error:
3685 pet_scop_free(scop);
3686 return NULL;
3689 /* Bound all parameters in scop->context to the possible values
3690 * of the corresponding C variable.
3692 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
3694 int n;
3696 if (!scop)
3697 return NULL;
3699 n = isl_set_dim(scop->context, isl_dim_param);
3700 for (int i = 0; i < n; ++i) {
3701 isl_id *id;
3702 ValueDecl *decl;
3704 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
3705 if (is_nested_parameter(id)) {
3706 isl_id_free(id);
3707 isl_die(isl_set_get_ctx(scop->context),
3708 isl_error_internal,
3709 "unresolved nested parameter", goto error);
3711 decl = (ValueDecl *) isl_id_get_user(id);
3712 isl_id_free(id);
3714 scop->context = set_parameter_bounds(scop->context, i, decl);
3716 if (!scop->context)
3717 goto error;
3720 return scop;
3721 error:
3722 pet_scop_free(scop);
3723 return NULL;
3726 /* Construct a pet_scop from the given function.
3728 struct pet_scop *PetScan::scan(FunctionDecl *fd)
3730 pet_scop *scop;
3731 Stmt *stmt;
3733 stmt = fd->getBody();
3735 if (options->autodetect)
3736 scop = extract(stmt);
3737 else
3738 scop = scan(stmt);
3739 scop = pet_scop_detect_parameter_accesses(scop);
3740 scop = scan_arrays(scop);
3741 scop = add_parameter_bounds(scop);
3742 scop = pet_scop_gist(scop, value_bounds);
3744 return scop;