scop_add_break: try and merge filters
[pet.git] / scan.cc
blob371cc03540be94c06ca33d081d794291d6005727
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;
752 /* This method is called when we come across an access that is
753 * nested in what is supposed to be an affine expression.
754 * If nesting is allowed, we return a new parameter that corresponds
755 * to this nested access. Otherwise, we simply complain.
757 * Note that we currently don't allow nested accesses themselves
758 * to contain any nested accesses, so we check if we can extract
759 * the access without any nesting and complain if we can't.
761 * The new parameter is resolved in resolve_nested.
763 isl_pw_aff *PetScan::nested_access(Expr *expr)
765 isl_id *id;
766 isl_space *dim;
767 isl_aff *aff;
768 isl_set *dom;
769 isl_map *access;
771 if (!nesting_enabled) {
772 unsupported(expr);
773 return NULL;
776 allow_nested = false;
777 access = extract_access(expr);
778 allow_nested = true;
779 if (!access) {
780 unsupported(expr);
781 return NULL;
783 isl_map_free(access);
785 id = isl_id_alloc(ctx, NULL, expr);
786 dim = isl_space_params_alloc(ctx, 1);
788 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
790 dom = isl_set_universe(isl_space_copy(dim));
791 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
792 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
794 return isl_pw_aff_alloc(dom, aff);
797 /* Affine expressions are not supposed to contain array accesses,
798 * but if nesting is allowed, we return a parameter corresponding
799 * to the array access.
801 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
803 return nested_access(expr);
806 /* Extract an affine expression from a conditional operation.
808 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
810 isl_pw_aff *cond, *lhs, *rhs, *res;
812 cond = extract_condition(expr->getCond());
813 lhs = extract_affine(expr->getTrueExpr());
814 rhs = extract_affine(expr->getFalseExpr());
816 return isl_pw_aff_cond(cond, lhs, rhs);
819 /* Extract an affine expression, if possible, from "expr".
820 * Otherwise return NULL.
822 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
824 switch (expr->getStmtClass()) {
825 case Stmt::ImplicitCastExprClass:
826 return extract_affine(cast<ImplicitCastExpr>(expr));
827 case Stmt::IntegerLiteralClass:
828 return extract_affine(cast<IntegerLiteral>(expr));
829 case Stmt::DeclRefExprClass:
830 return extract_affine(cast<DeclRefExpr>(expr));
831 case Stmt::BinaryOperatorClass:
832 return extract_affine(cast<BinaryOperator>(expr));
833 case Stmt::UnaryOperatorClass:
834 return extract_affine(cast<UnaryOperator>(expr));
835 case Stmt::ParenExprClass:
836 return extract_affine(cast<ParenExpr>(expr));
837 case Stmt::CallExprClass:
838 return extract_affine(cast<CallExpr>(expr));
839 case Stmt::ArraySubscriptExprClass:
840 return extract_affine(cast<ArraySubscriptExpr>(expr));
841 case Stmt::ConditionalOperatorClass:
842 return extract_affine(cast<ConditionalOperator>(expr));
843 default:
844 unsupported(expr);
846 return NULL;
849 __isl_give isl_map *PetScan::extract_access(ImplicitCastExpr *expr)
851 return extract_access(expr->getSubExpr());
854 /* Return the depth of an array of the given type.
856 static int array_depth(const Type *type)
858 if (type->isPointerType())
859 return 1 + array_depth(type->getPointeeType().getTypePtr());
860 if (type->isArrayType()) {
861 const ArrayType *atype;
862 type = type->getCanonicalTypeInternal().getTypePtr();
863 atype = cast<ArrayType>(type);
864 return 1 + array_depth(atype->getElementType().getTypePtr());
866 return 0;
869 /* Return the element type of the given array type.
871 static QualType base_type(QualType qt)
873 const Type *type = qt.getTypePtr();
875 if (type->isPointerType())
876 return base_type(type->getPointeeType());
877 if (type->isArrayType()) {
878 const ArrayType *atype;
879 type = type->getCanonicalTypeInternal().getTypePtr();
880 atype = cast<ArrayType>(type);
881 return base_type(atype->getElementType());
883 return qt;
886 /* Extract an access relation from a reference to a variable.
887 * If the variable has name "A" and its type corresponds to an
888 * array of depth d, then the returned access relation is of the
889 * form
891 * { [] -> A[i_1,...,i_d] }
893 __isl_give isl_map *PetScan::extract_access(DeclRefExpr *expr)
895 ValueDecl *decl = expr->getDecl();
896 int depth = array_depth(decl->getType().getTypePtr());
897 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
898 isl_space *dim = isl_space_alloc(ctx, 0, 0, depth);
899 isl_map *access_rel;
901 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
903 access_rel = isl_map_universe(dim);
905 return access_rel;
908 /* Extract an access relation from an integer contant.
909 * If the value of the constant is "v", then the returned access relation
910 * is
912 * { [] -> [v] }
914 __isl_give isl_map *PetScan::extract_access(IntegerLiteral *expr)
916 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr)));
919 /* Try and extract an access relation from the given Expr.
920 * Return NULL if it doesn't work out.
922 __isl_give isl_map *PetScan::extract_access(Expr *expr)
924 switch (expr->getStmtClass()) {
925 case Stmt::ImplicitCastExprClass:
926 return extract_access(cast<ImplicitCastExpr>(expr));
927 case Stmt::DeclRefExprClass:
928 return extract_access(cast<DeclRefExpr>(expr));
929 case Stmt::ArraySubscriptExprClass:
930 return extract_access(cast<ArraySubscriptExpr>(expr));
931 case Stmt::IntegerLiteralClass:
932 return extract_access(cast<IntegerLiteral>(expr));
933 default:
934 unsupported(expr);
936 return NULL;
939 /* Assign the affine expression "index" to the output dimension "pos" of "map",
940 * restrict the domain to those values that result in a non-negative index
941 * and return the result.
943 __isl_give isl_map *set_index(__isl_take isl_map *map, int pos,
944 __isl_take isl_pw_aff *index)
946 isl_map *index_map;
947 int len = isl_map_dim(map, isl_dim_out);
948 isl_id *id;
949 isl_set *domain;
951 domain = isl_pw_aff_nonneg_set(isl_pw_aff_copy(index));
952 index = isl_pw_aff_intersect_domain(index, domain);
953 index_map = isl_map_from_range(isl_set_from_pw_aff(index));
954 index_map = isl_map_insert_dims(index_map, isl_dim_out, 0, pos);
955 index_map = isl_map_add_dims(index_map, isl_dim_out, len - pos - 1);
956 id = isl_map_get_tuple_id(map, isl_dim_out);
957 index_map = isl_map_set_tuple_id(index_map, isl_dim_out, id);
959 map = isl_map_intersect(map, index_map);
961 return map;
964 /* Extract an access relation from the given array subscript expression.
965 * If nesting is allowed in general, then we turn it on while
966 * examining the index expression.
968 * We first extract an access relation from the base.
969 * This will result in an access relation with a range that corresponds
970 * to the array being accessed and with earlier indices filled in already.
971 * We then extract the current index and fill that in as well.
972 * The position of the current index is based on the type of base.
973 * If base is the actual array variable, then the depth of this type
974 * will be the same as the depth of the array and we will fill in
975 * the first array index.
976 * Otherwise, the depth of the base type will be smaller and we will fill
977 * in a later index.
979 __isl_give isl_map *PetScan::extract_access(ArraySubscriptExpr *expr)
981 Expr *base = expr->getBase();
982 Expr *idx = expr->getIdx();
983 isl_pw_aff *index;
984 isl_map *base_access;
985 isl_map *access;
986 int depth = array_depth(base->getType().getTypePtr());
987 int pos;
988 bool save_nesting = nesting_enabled;
990 nesting_enabled = allow_nested;
992 base_access = extract_access(base);
993 index = extract_affine(idx);
995 nesting_enabled = save_nesting;
997 pos = isl_map_dim(base_access, isl_dim_out) - depth;
998 access = set_index(base_access, pos, index);
1000 return access;
1003 /* Check if "expr" calls function "minmax" with two arguments and if so
1004 * make lhs and rhs refer to these two arguments.
1006 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
1008 CallExpr *call;
1009 FunctionDecl *fd;
1010 string name;
1012 if (expr->getStmtClass() != Stmt::CallExprClass)
1013 return false;
1015 call = cast<CallExpr>(expr);
1016 fd = call->getDirectCallee();
1017 if (!fd)
1018 return false;
1020 if (call->getNumArgs() != 2)
1021 return false;
1023 name = fd->getDeclName().getAsString();
1024 if (name != minmax)
1025 return false;
1027 lhs = call->getArg(0);
1028 rhs = call->getArg(1);
1030 return true;
1033 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1034 * lhs and rhs refer to the two arguments.
1036 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
1038 return is_minmax(expr, "min", lhs, rhs);
1041 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1042 * lhs and rhs refer to the two arguments.
1044 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
1046 return is_minmax(expr, "max", lhs, rhs);
1049 /* Return "lhs && rhs", defined on the shared definition domain.
1051 static __isl_give isl_pw_aff *pw_aff_and(__isl_take isl_pw_aff *lhs,
1052 __isl_take isl_pw_aff *rhs)
1054 isl_set *cond;
1055 isl_set *dom;
1057 dom = isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs)),
1058 isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1059 cond = isl_set_intersect(isl_pw_aff_non_zero_set(lhs),
1060 isl_pw_aff_non_zero_set(rhs));
1061 return indicator_function(cond, dom);
1064 /* Return "lhs && rhs", with shortcut semantics.
1065 * That is, if lhs is false, then the result is defined even if rhs is not.
1066 * In practice, we compute lhs ? rhs : lhs.
1068 static __isl_give isl_pw_aff *pw_aff_and_then(__isl_take isl_pw_aff *lhs,
1069 __isl_take isl_pw_aff *rhs)
1071 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), rhs, lhs);
1074 /* Return "lhs || rhs", with shortcut semantics.
1075 * That is, if lhs is true, then the result is defined even if rhs is not.
1076 * In practice, we compute lhs ? lhs : rhs.
1078 static __isl_give isl_pw_aff *pw_aff_or_else(__isl_take isl_pw_aff *lhs,
1079 __isl_take isl_pw_aff *rhs)
1081 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), lhs, rhs);
1084 /* Extract an affine expressions representing the comparison "LHS op RHS"
1085 * "comp" is the original statement that "LHS op RHS" is derived from
1086 * and is used for diagnostics.
1088 * If the comparison is of the form
1090 * a <= min(b,c)
1092 * then the expression is constructed as the conjunction of
1093 * the comparisons
1095 * a <= b and a <= c
1097 * A similar optimization is performed for max(a,b) <= c.
1098 * We do this because that will lead to simpler representations
1099 * of the expression.
1100 * If isl is ever enhanced to explicitly deal with min and max expressions,
1101 * this optimization can be removed.
1103 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
1104 Expr *LHS, Expr *RHS, Stmt *comp)
1106 isl_pw_aff *lhs;
1107 isl_pw_aff *rhs;
1108 isl_pw_aff *res;
1109 isl_set *cond;
1110 isl_set *dom;
1112 if (op == BO_GT)
1113 return extract_comparison(BO_LT, RHS, LHS, comp);
1114 if (op == BO_GE)
1115 return extract_comparison(BO_LE, RHS, LHS, comp);
1117 if (op == BO_LT || op == BO_LE) {
1118 Expr *expr1, *expr2;
1119 if (is_min(RHS, expr1, expr2)) {
1120 lhs = extract_comparison(op, LHS, expr1, comp);
1121 rhs = extract_comparison(op, LHS, expr2, comp);
1122 return pw_aff_and(lhs, rhs);
1124 if (is_max(LHS, expr1, expr2)) {
1125 lhs = extract_comparison(op, expr1, RHS, comp);
1126 rhs = extract_comparison(op, expr2, RHS, comp);
1127 return pw_aff_and(lhs, rhs);
1131 lhs = extract_affine(LHS);
1132 rhs = extract_affine(RHS);
1134 dom = isl_pw_aff_domain(isl_pw_aff_copy(lhs));
1135 dom = isl_set_intersect(dom, isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1137 switch (op) {
1138 case BO_LT:
1139 cond = isl_pw_aff_lt_set(lhs, rhs);
1140 break;
1141 case BO_LE:
1142 cond = isl_pw_aff_le_set(lhs, rhs);
1143 break;
1144 case BO_EQ:
1145 cond = isl_pw_aff_eq_set(lhs, rhs);
1146 break;
1147 case BO_NE:
1148 cond = isl_pw_aff_ne_set(lhs, rhs);
1149 break;
1150 default:
1151 isl_pw_aff_free(lhs);
1152 isl_pw_aff_free(rhs);
1153 isl_set_free(dom);
1154 unsupported(comp);
1155 return NULL;
1158 cond = isl_set_coalesce(cond);
1159 res = indicator_function(cond, dom);
1161 return res;
1164 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1166 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1167 comp->getRHS(), comp);
1170 /* Extract an affine expression representing the negation (logical not)
1171 * of a subexpression.
1173 __isl_give isl_pw_aff *PetScan::extract_boolean(UnaryOperator *op)
1175 isl_set *set_cond, *dom;
1176 isl_pw_aff *cond, *res;
1178 cond = extract_condition(op->getSubExpr());
1180 dom = isl_pw_aff_domain(isl_pw_aff_copy(cond));
1182 set_cond = isl_pw_aff_zero_set(cond);
1184 res = indicator_function(set_cond, dom);
1186 return res;
1189 /* Extract an affine expression representing the disjunction (logical or)
1190 * or conjunction (logical and) of two subexpressions.
1192 __isl_give isl_pw_aff *PetScan::extract_boolean(BinaryOperator *comp)
1194 isl_pw_aff *lhs, *rhs;
1196 lhs = extract_condition(comp->getLHS());
1197 rhs = extract_condition(comp->getRHS());
1199 switch (comp->getOpcode()) {
1200 case BO_LAnd:
1201 return pw_aff_and_then(lhs, rhs);
1202 case BO_LOr:
1203 return pw_aff_or_else(lhs, rhs);
1204 default:
1205 isl_pw_aff_free(lhs);
1206 isl_pw_aff_free(rhs);
1209 unsupported(comp);
1210 return NULL;
1213 __isl_give isl_pw_aff *PetScan::extract_condition(UnaryOperator *expr)
1215 switch (expr->getOpcode()) {
1216 case UO_LNot:
1217 return extract_boolean(expr);
1218 default:
1219 unsupported(expr);
1220 return NULL;
1224 /* Extract the affine expression "expr != 0 ? 1 : 0".
1226 __isl_give isl_pw_aff *PetScan::extract_implicit_condition(Expr *expr)
1228 isl_pw_aff *res;
1229 isl_set *set, *dom;
1231 res = extract_affine(expr);
1233 dom = isl_pw_aff_domain(isl_pw_aff_copy(res));
1234 set = isl_pw_aff_non_zero_set(res);
1236 res = indicator_function(set, dom);
1238 return res;
1241 /* Extract an affine expression from a boolean expression.
1242 * In particular, return the expression "expr ? 1 : 0".
1244 * If the expression doesn't look like a condition, we assume it
1245 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1247 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1249 BinaryOperator *comp;
1251 if (!expr) {
1252 isl_set *u = isl_set_universe(isl_space_params_alloc(ctx, 0));
1253 return indicator_function(u, isl_set_copy(u));
1256 if (expr->getStmtClass() == Stmt::ParenExprClass)
1257 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1259 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1260 return extract_condition(cast<UnaryOperator>(expr));
1262 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1263 return extract_implicit_condition(expr);
1265 comp = cast<BinaryOperator>(expr);
1266 switch (comp->getOpcode()) {
1267 case BO_LT:
1268 case BO_LE:
1269 case BO_GT:
1270 case BO_GE:
1271 case BO_EQ:
1272 case BO_NE:
1273 return extract_comparison(comp);
1274 case BO_LAnd:
1275 case BO_LOr:
1276 return extract_boolean(comp);
1277 default:
1278 return extract_implicit_condition(expr);
1282 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1284 switch (kind) {
1285 case UO_Minus:
1286 return pet_op_minus;
1287 case UO_PostInc:
1288 return pet_op_post_inc;
1289 case UO_PostDec:
1290 return pet_op_post_dec;
1291 case UO_PreInc:
1292 return pet_op_pre_inc;
1293 case UO_PreDec:
1294 return pet_op_pre_dec;
1295 default:
1296 return pet_op_last;
1300 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1302 switch (kind) {
1303 case BO_AddAssign:
1304 return pet_op_add_assign;
1305 case BO_SubAssign:
1306 return pet_op_sub_assign;
1307 case BO_MulAssign:
1308 return pet_op_mul_assign;
1309 case BO_DivAssign:
1310 return pet_op_div_assign;
1311 case BO_Assign:
1312 return pet_op_assign;
1313 case BO_Add:
1314 return pet_op_add;
1315 case BO_Sub:
1316 return pet_op_sub;
1317 case BO_Mul:
1318 return pet_op_mul;
1319 case BO_Div:
1320 return pet_op_div;
1321 case BO_EQ:
1322 return pet_op_eq;
1323 case BO_LE:
1324 return pet_op_le;
1325 case BO_LT:
1326 return pet_op_lt;
1327 case BO_GT:
1328 return pet_op_gt;
1329 default:
1330 return pet_op_last;
1334 /* Construct a pet_expr representing a unary operator expression.
1336 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1338 struct pet_expr *arg;
1339 enum pet_op_type op;
1341 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1342 if (op == pet_op_last) {
1343 unsupported(expr);
1344 return NULL;
1347 arg = extract_expr(expr->getSubExpr());
1349 if (expr->isIncrementDecrementOp() &&
1350 arg && arg->type == pet_expr_access) {
1351 mark_write(arg);
1352 arg->acc.read = 1;
1355 return pet_expr_new_unary(ctx, op, arg);
1358 /* Mark the given access pet_expr as a write.
1359 * If a scalar is being accessed, then mark its value
1360 * as unknown in assigned_value.
1362 void PetScan::mark_write(struct pet_expr *access)
1364 isl_id *id;
1365 ValueDecl *decl;
1367 access->acc.write = 1;
1368 access->acc.read = 0;
1370 if (isl_map_dim(access->acc.access, isl_dim_out) != 0)
1371 return;
1373 id = isl_map_get_tuple_id(access->acc.access, isl_dim_out);
1374 decl = (ValueDecl *) isl_id_get_user(id);
1375 clear_assignment(assigned_value, decl);
1376 isl_id_free(id);
1379 /* Construct a pet_expr representing a binary operator expression.
1381 * If the top level operator is an assignment and the LHS is an access,
1382 * then we mark that access as a write. If the operator is a compound
1383 * assignment, the access is marked as both a read and a write.
1385 * If "expr" assigns something to a scalar variable, then we mark
1386 * the variable as having been assigned. If, furthermore, the expression
1387 * is affine, then keep track of this value in assigned_value
1388 * so that we can plug it in when we later come across the same variable.
1390 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1392 struct pet_expr *lhs, *rhs;
1393 enum pet_op_type op;
1395 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1396 if (op == pet_op_last) {
1397 unsupported(expr);
1398 return NULL;
1401 lhs = extract_expr(expr->getLHS());
1402 rhs = extract_expr(expr->getRHS());
1404 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1405 mark_write(lhs);
1406 if (expr->isCompoundAssignmentOp())
1407 lhs->acc.read = 1;
1410 if (expr->getOpcode() == BO_Assign &&
1411 lhs && lhs->type == pet_expr_access &&
1412 isl_map_dim(lhs->acc.access, isl_dim_out) == 0) {
1413 isl_id *id = isl_map_get_tuple_id(lhs->acc.access, isl_dim_out);
1414 ValueDecl *decl = (ValueDecl *) isl_id_get_user(id);
1415 Expr *rhs = expr->getRHS();
1416 isl_pw_aff *pa = try_extract_affine(rhs);
1417 clear_assignment(assigned_value, decl);
1418 if (pa) {
1419 assigned_value[decl] = pa;
1420 insert_expression(pa);
1422 isl_id_free(id);
1425 return pet_expr_new_binary(ctx, op, lhs, rhs);
1428 /* Construct a pet_expr representing a conditional operation.
1430 * We first try to extract the condition as an affine expression.
1431 * If that fails, we construct a pet_expr tree representing the condition.
1433 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1435 struct pet_expr *cond, *lhs, *rhs;
1436 isl_pw_aff *pa;
1438 pa = try_extract_affine(expr->getCond());
1439 if (pa) {
1440 isl_set *test = isl_set_from_pw_aff(pa);
1441 cond = pet_expr_from_access(isl_map_from_range(test));
1442 } else
1443 cond = extract_expr(expr->getCond());
1444 lhs = extract_expr(expr->getTrueExpr());
1445 rhs = extract_expr(expr->getFalseExpr());
1447 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1450 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1452 return extract_expr(expr->getSubExpr());
1455 /* Construct a pet_expr representing a floating point value.
1457 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1459 return pet_expr_new_double(ctx, expr->getValueAsApproximateDouble());
1462 /* Extract an access relation from "expr" and then convert it into
1463 * a pet_expr.
1465 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1467 isl_map *access;
1468 struct pet_expr *pe;
1470 access = extract_access(expr);
1472 pe = pet_expr_from_access(access);
1474 return pe;
1477 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1479 return extract_expr(expr->getSubExpr());
1482 /* Construct a pet_expr representing a function call.
1484 * If we are passing along a pointer to an array element
1485 * or an entire row or even higher dimensional slice of an array,
1486 * then the function being called may write into the array.
1488 * We assume here that if the function is declared to take a pointer
1489 * to a const type, then the function will perform a read
1490 * and that otherwise, it will perform a write.
1492 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1494 struct pet_expr *res = NULL;
1495 FunctionDecl *fd;
1496 string name;
1498 fd = expr->getDirectCallee();
1499 if (!fd) {
1500 unsupported(expr);
1501 return NULL;
1504 name = fd->getDeclName().getAsString();
1505 res = pet_expr_new_call(ctx, name.c_str(), expr->getNumArgs());
1506 if (!res)
1507 return NULL;
1509 for (int i = 0; i < expr->getNumArgs(); ++i) {
1510 Expr *arg = expr->getArg(i);
1511 int is_addr = 0;
1512 pet_expr *main_arg;
1514 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
1515 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(arg);
1516 arg = ice->getSubExpr();
1518 if (arg->getStmtClass() == Stmt::UnaryOperatorClass) {
1519 UnaryOperator *op = cast<UnaryOperator>(arg);
1520 if (op->getOpcode() == UO_AddrOf) {
1521 is_addr = 1;
1522 arg = op->getSubExpr();
1525 res->args[i] = PetScan::extract_expr(arg);
1526 main_arg = res->args[i];
1527 if (is_addr)
1528 res->args[i] = pet_expr_new_unary(ctx,
1529 pet_op_address_of, res->args[i]);
1530 if (!res->args[i])
1531 goto error;
1532 if (arg->getStmtClass() == Stmt::ArraySubscriptExprClass &&
1533 array_depth(arg->getType().getTypePtr()) > 0)
1534 is_addr = 1;
1535 if (is_addr && main_arg->type == pet_expr_access) {
1536 ParmVarDecl *parm;
1537 if (!fd->hasPrototype()) {
1538 unsupported(expr, "prototype required");
1539 goto error;
1541 parm = fd->getParamDecl(i);
1542 if (!const_base(parm->getType()))
1543 mark_write(main_arg);
1547 return res;
1548 error:
1549 pet_expr_free(res);
1550 return NULL;
1553 /* Try and onstruct a pet_expr representing "expr".
1555 struct pet_expr *PetScan::extract_expr(Expr *expr)
1557 switch (expr->getStmtClass()) {
1558 case Stmt::UnaryOperatorClass:
1559 return extract_expr(cast<UnaryOperator>(expr));
1560 case Stmt::CompoundAssignOperatorClass:
1561 case Stmt::BinaryOperatorClass:
1562 return extract_expr(cast<BinaryOperator>(expr));
1563 case Stmt::ImplicitCastExprClass:
1564 return extract_expr(cast<ImplicitCastExpr>(expr));
1565 case Stmt::ArraySubscriptExprClass:
1566 case Stmt::DeclRefExprClass:
1567 case Stmt::IntegerLiteralClass:
1568 return extract_access_expr(expr);
1569 case Stmt::FloatingLiteralClass:
1570 return extract_expr(cast<FloatingLiteral>(expr));
1571 case Stmt::ParenExprClass:
1572 return extract_expr(cast<ParenExpr>(expr));
1573 case Stmt::ConditionalOperatorClass:
1574 return extract_expr(cast<ConditionalOperator>(expr));
1575 case Stmt::CallExprClass:
1576 return extract_expr(cast<CallExpr>(expr));
1577 default:
1578 unsupported(expr);
1580 return NULL;
1583 /* Check if the given initialization statement is an assignment.
1584 * If so, return that assignment. Otherwise return NULL.
1586 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1588 BinaryOperator *ass;
1590 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1591 return NULL;
1593 ass = cast<BinaryOperator>(init);
1594 if (ass->getOpcode() != BO_Assign)
1595 return NULL;
1597 return ass;
1600 /* Check if the given initialization statement is a declaration
1601 * of a single variable.
1602 * If so, return that declaration. Otherwise return NULL.
1604 Decl *PetScan::initialization_declaration(Stmt *init)
1606 DeclStmt *decl;
1608 if (init->getStmtClass() != Stmt::DeclStmtClass)
1609 return NULL;
1611 decl = cast<DeclStmt>(init);
1613 if (!decl->isSingleDecl())
1614 return NULL;
1616 return decl->getSingleDecl();
1619 /* Given the assignment operator in the initialization of a for loop,
1620 * extract the induction variable, i.e., the (integer)variable being
1621 * assigned.
1623 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1625 Expr *lhs;
1626 DeclRefExpr *ref;
1627 ValueDecl *decl;
1628 const Type *type;
1630 lhs = init->getLHS();
1631 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1632 unsupported(init);
1633 return NULL;
1636 ref = cast<DeclRefExpr>(lhs);
1637 decl = ref->getDecl();
1638 type = decl->getType().getTypePtr();
1640 if (!type->isIntegerType()) {
1641 unsupported(lhs);
1642 return NULL;
1645 return decl;
1648 /* Given the initialization statement of a for loop and the single
1649 * declaration in this initialization statement,
1650 * extract the induction variable, i.e., the (integer) variable being
1651 * declared.
1653 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1655 VarDecl *vd;
1657 vd = cast<VarDecl>(decl);
1659 const QualType type = vd->getType();
1660 if (!type->isIntegerType()) {
1661 unsupported(init);
1662 return NULL;
1665 if (!vd->getInit()) {
1666 unsupported(init);
1667 return NULL;
1670 return vd;
1673 /* Check that op is of the form iv++ or iv--.
1674 * Return an affine expression "1" or "-1" accordingly.
1676 __isl_give isl_pw_aff *PetScan::extract_unary_increment(
1677 clang::UnaryOperator *op, clang::ValueDecl *iv)
1679 Expr *sub;
1680 DeclRefExpr *ref;
1681 isl_space *space;
1682 isl_aff *aff;
1684 if (!op->isIncrementDecrementOp()) {
1685 unsupported(op);
1686 return NULL;
1689 sub = op->getSubExpr();
1690 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1691 unsupported(op);
1692 return NULL;
1695 ref = cast<DeclRefExpr>(sub);
1696 if (ref->getDecl() != iv) {
1697 unsupported(op);
1698 return NULL;
1701 space = isl_space_params_alloc(ctx, 0);
1702 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1704 if (op->isIncrementOp())
1705 aff = isl_aff_add_constant_si(aff, 1);
1706 else
1707 aff = isl_aff_add_constant_si(aff, -1);
1709 return isl_pw_aff_from_aff(aff);
1712 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1713 * has a single constant expression, then put this constant in *user.
1714 * The caller is assumed to have checked that this function will
1715 * be called exactly once.
1717 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
1718 void *user)
1720 isl_int *inc = (isl_int *)user;
1721 int res = 0;
1723 if (isl_aff_is_cst(aff))
1724 isl_aff_get_constant(aff, inc);
1725 else
1726 res = -1;
1728 isl_set_free(set);
1729 isl_aff_free(aff);
1731 return res;
1734 /* Check if op is of the form
1736 * iv = iv + inc
1738 * and return inc as an affine expression.
1740 * We extract an affine expression from the RHS, subtract iv and return
1741 * the result.
1743 __isl_give isl_pw_aff *PetScan::extract_binary_increment(BinaryOperator *op,
1744 clang::ValueDecl *iv)
1746 Expr *lhs;
1747 DeclRefExpr *ref;
1748 isl_id *id;
1749 isl_space *dim;
1750 isl_aff *aff;
1751 isl_pw_aff *val;
1753 if (op->getOpcode() != BO_Assign) {
1754 unsupported(op);
1755 return NULL;
1758 lhs = op->getLHS();
1759 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1760 unsupported(op);
1761 return NULL;
1764 ref = cast<DeclRefExpr>(lhs);
1765 if (ref->getDecl() != iv) {
1766 unsupported(op);
1767 return NULL;
1770 val = extract_affine(op->getRHS());
1772 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1774 dim = isl_space_params_alloc(ctx, 1);
1775 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1776 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1777 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1779 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
1781 return val;
1784 /* Check that op is of the form iv += cst or iv -= cst
1785 * and return an affine expression corresponding oto cst or -cst accordingly.
1787 __isl_give isl_pw_aff *PetScan::extract_compound_increment(
1788 CompoundAssignOperator *op, clang::ValueDecl *iv)
1790 Expr *lhs;
1791 DeclRefExpr *ref;
1792 bool neg = false;
1793 isl_pw_aff *val;
1794 BinaryOperatorKind opcode;
1796 opcode = op->getOpcode();
1797 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1798 unsupported(op);
1799 return NULL;
1801 if (opcode == BO_SubAssign)
1802 neg = true;
1804 lhs = op->getLHS();
1805 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1806 unsupported(op);
1807 return NULL;
1810 ref = cast<DeclRefExpr>(lhs);
1811 if (ref->getDecl() != iv) {
1812 unsupported(op);
1813 return NULL;
1816 val = extract_affine(op->getRHS());
1817 if (neg)
1818 val = isl_pw_aff_neg(val);
1820 return val;
1823 /* Check that the increment of the given for loop increments
1824 * (or decrements) the induction variable "iv" and return
1825 * the increment as an affine expression if successful.
1827 __isl_give isl_pw_aff *PetScan::extract_increment(clang::ForStmt *stmt,
1828 ValueDecl *iv)
1830 Stmt *inc = stmt->getInc();
1832 if (!inc) {
1833 unsupported(stmt);
1834 return NULL;
1837 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1838 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1839 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1840 return extract_compound_increment(
1841 cast<CompoundAssignOperator>(inc), iv);
1842 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1843 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1845 unsupported(inc);
1846 return NULL;
1849 /* Embed the given iteration domain in an extra outer loop
1850 * with induction variable "var".
1851 * If this variable appeared as a parameter in the constraints,
1852 * it is replaced by the new outermost dimension.
1854 static __isl_give isl_set *embed(__isl_take isl_set *set,
1855 __isl_take isl_id *var)
1857 int pos;
1859 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
1860 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
1861 if (pos >= 0) {
1862 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
1863 set = isl_set_project_out(set, isl_dim_param, pos, 1);
1866 isl_id_free(var);
1867 return set;
1870 /* Return those elements in the space of "cond" that come after
1871 * (based on "sign") an element in "cond".
1873 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
1875 isl_map *previous_to_this;
1877 if (sign > 0)
1878 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
1879 else
1880 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
1882 cond = isl_set_apply(cond, previous_to_this);
1884 return cond;
1887 /* Create the infinite iteration domain
1889 * { [id] : id >= 0 }
1891 * If "scop" has an affine skip of type pet_skip_later,
1892 * then remove those iterations i that have an earlier iteration
1893 * where the skip condition is satisfied, meaning that iteration i
1894 * is not executed.
1895 * Since we are dealing with a loop without loop iterator,
1896 * the skip condition cannot refer to the current loop iterator and
1897 * so effectively, the returned set is of the form
1899 * { [0]; [id] : id >= 1 and not skip }
1901 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
1902 struct pet_scop *scop)
1904 isl_ctx *ctx = isl_id_get_ctx(id);
1905 isl_set *domain;
1906 isl_set *skip;
1908 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
1909 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
1911 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
1912 return domain;
1914 skip = pet_scop_get_skip(scop, pet_skip_later);
1915 skip = isl_set_fix_si(skip, isl_dim_set, 0, 1);
1916 skip = isl_set_params(skip);
1917 skip = embed(skip, isl_id_copy(id));
1918 skip = isl_set_intersect(skip , isl_set_copy(domain));
1919 domain = isl_set_subtract(domain, after(skip, 1));
1921 return domain;
1924 /* Create an identity mapping on the space containing "domain".
1926 static __isl_give isl_map *identity_map(__isl_keep isl_set *domain)
1928 isl_space *space;
1929 isl_map *id;
1931 space = isl_space_map_from_set(isl_set_get_space(domain));
1932 id = isl_map_identity(space);
1934 return id;
1937 /* Add a filter to "scop" that imposes that it is only executed
1938 * when "break_access" has a zero value for all previous iterations
1939 * of "domain".
1941 * The input "break_access" has a zero-dimensional domain and range.
1943 static struct pet_scop *scop_add_break(struct pet_scop *scop,
1944 __isl_take isl_map *break_access, __isl_take isl_set *domain, int sign)
1946 isl_ctx *ctx = isl_set_get_ctx(domain);
1947 isl_id *id_test;
1948 isl_map *prev;
1950 id_test = isl_map_get_tuple_id(break_access, isl_dim_out);
1951 break_access = isl_map_add_dims(break_access, isl_dim_in, 1);
1952 break_access = isl_map_add_dims(break_access, isl_dim_out, 1);
1953 break_access = isl_map_intersect_range(break_access, domain);
1954 break_access = isl_map_set_tuple_id(break_access, isl_dim_out, id_test);
1955 if (sign > 0)
1956 prev = isl_map_lex_gt_first(isl_map_get_space(break_access), 1);
1957 else
1958 prev = isl_map_lex_lt_first(isl_map_get_space(break_access), 1);
1959 break_access = isl_map_intersect(break_access, prev);
1960 scop = pet_scop_filter(scop, break_access, 0);
1961 scop = pet_scop_merge_filters(scop);
1963 return scop;
1966 /* Construct a pet_scop for an infinite loop around the given body.
1968 * We extract a pet_scop for the body and then embed it in a loop with
1969 * iteration domain
1971 * { [t] : t >= 0 }
1973 * and schedule
1975 * { [t] -> [t] }
1977 * If the body contains any break, then it is taken into
1978 * account in infinite_domain (if the skip condition is affine)
1979 * or in scop_add_break (if the skip condition is not affine).
1981 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
1983 isl_id *id;
1984 isl_set *domain;
1985 isl_map *ident;
1986 isl_map *access;
1987 struct pet_scop *scop;
1988 bool has_var_break;
1990 scop = extract(body);
1991 if (!scop)
1992 return NULL;
1994 id = isl_id_alloc(ctx, "t", NULL);
1995 domain = infinite_domain(isl_id_copy(id), scop);
1996 ident = identity_map(domain);
1998 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
1999 if (has_var_break)
2000 access = pet_scop_get_skip_map(scop, pet_skip_later);
2002 scop = pet_scop_embed(scop, isl_set_copy(domain),
2003 isl_map_copy(ident), ident, id);
2004 if (has_var_break)
2005 scop = scop_add_break(scop, access, domain, 1);
2006 else
2007 isl_set_free(domain);
2009 return scop;
2012 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2014 * for (;;)
2015 * body
2018 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
2020 return extract_infinite_loop(stmt->getBody());
2023 /* Create an access to a virtual array representing the result
2024 * of a condition.
2025 * Unlike other accessed data, the id of the array is NULL as
2026 * there is no ValueDecl in the program corresponding to the virtual
2027 * array.
2028 * The array starts out as a scalar, but grows along with the
2029 * statement writing to the array in pet_scop_embed.
2031 static __isl_give isl_map *create_test_access(isl_ctx *ctx, int test_nr)
2033 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2034 isl_id *id;
2035 char name[50];
2037 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2038 id = isl_id_alloc(ctx, name, NULL);
2039 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2040 return isl_map_universe(dim);
2043 /* Add an array with the given extent ("access") to the list
2044 * of arrays in "scop" and return the extended pet_scop.
2045 * The array is marked as attaining values 0 and 1 only and
2046 * as each element being assigned at most once.
2048 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2049 __isl_keep isl_map *access, clang::ASTContext &ast_ctx)
2051 isl_ctx *ctx = isl_map_get_ctx(access);
2052 isl_space *dim;
2053 struct pet_array **arrays;
2054 struct pet_array *array;
2056 if (!scop)
2057 return NULL;
2058 if (!ctx)
2059 goto error;
2061 arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2062 scop->n_array + 1);
2063 if (!arrays)
2064 goto error;
2065 scop->arrays = arrays;
2067 array = isl_calloc_type(ctx, struct pet_array);
2068 if (!array)
2069 goto error;
2071 array->extent = isl_map_range(isl_map_copy(access));
2072 dim = isl_space_params_alloc(ctx, 0);
2073 array->context = isl_set_universe(dim);
2074 dim = isl_space_set_alloc(ctx, 0, 1);
2075 array->value_bounds = isl_set_universe(dim);
2076 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2077 isl_dim_set, 0, 0);
2078 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2079 isl_dim_set, 0, 1);
2080 array->element_type = strdup("int");
2081 array->element_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2082 array->uniquely_defined = 1;
2084 scop->arrays[scop->n_array] = array;
2085 scop->n_array++;
2087 if (!array->extent || !array->context)
2088 goto error;
2090 return scop;
2091 error:
2092 pet_scop_free(scop);
2093 return NULL;
2096 /* Construct a pet_scop for a while loop of the form
2098 * while (pa)
2099 * body
2101 * In particular, construct a scop for an infinite loop around body and
2102 * intersect the domain with the affine expression.
2103 * Note that this intersection may result in an empty loop.
2105 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
2106 Stmt *body)
2108 struct pet_scop *scop;
2109 isl_set *dom;
2110 isl_set *valid;
2112 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2113 dom = isl_pw_aff_non_zero_set(pa);
2114 scop = extract_infinite_loop(body);
2115 scop = pet_scop_restrict(scop, dom);
2116 scop = pet_scop_restrict_context(scop, valid);
2118 return scop;
2121 /* Construct a scop for a while, given the scops for the condition
2122 * and the body, the filter access and the iteration domain of
2123 * the while loop.
2125 * In particular, the scop for the condition is filtered to depend
2126 * on "test_access" evaluating to true for all previous iterations
2127 * of the loop, while the scop for the body is filtered to depend
2128 * on "test_access" evaluating to true for all iterations up to the
2129 * current iteration.
2131 * These filtered scops are then combined into a single scop.
2133 * "sign" is positive if the iterator increases and negative
2134 * if it decreases.
2136 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
2137 struct pet_scop *scop_body, __isl_take isl_map *test_access,
2138 __isl_take isl_set *domain, int sign)
2140 isl_ctx *ctx = isl_set_get_ctx(domain);
2141 isl_id *id_test;
2142 isl_map *prev;
2144 id_test = isl_map_get_tuple_id(test_access, isl_dim_out);
2145 test_access = isl_map_add_dims(test_access, isl_dim_in, 1);
2146 test_access = isl_map_add_dims(test_access, isl_dim_out, 1);
2147 test_access = isl_map_intersect_range(test_access, domain);
2148 test_access = isl_map_set_tuple_id(test_access, isl_dim_out, id_test);
2149 if (sign > 0)
2150 prev = isl_map_lex_ge_first(isl_map_get_space(test_access), 1);
2151 else
2152 prev = isl_map_lex_le_first(isl_map_get_space(test_access), 1);
2153 test_access = isl_map_intersect(test_access, prev);
2154 scop_body = pet_scop_filter(scop_body, isl_map_copy(test_access), 1);
2155 if (sign > 0)
2156 prev = isl_map_lex_gt_first(isl_map_get_space(test_access), 1);
2157 else
2158 prev = isl_map_lex_lt_first(isl_map_get_space(test_access), 1);
2159 test_access = isl_map_intersect(test_access, prev);
2160 scop_cond = pet_scop_filter(scop_cond, test_access, 1);
2162 return pet_scop_add_seq(ctx, scop_cond, scop_body);
2165 /* Check if the while loop is of the form
2167 * while (affine expression)
2168 * body
2170 * If so, call extract_affine_while to construct a scop.
2172 * Otherwise, construct a generic while scop, with iteration domain
2173 * { [t] : t >= 0 }. The scop consists of two parts, one for
2174 * evaluating the condition and one for the body.
2175 * The schedule is adjusted to reflect that the condition is evaluated
2176 * before the body is executed and the body is filtered to depend
2177 * on the result of the condition evaluating to true on all iterations
2178 * up to the current iteration, while the evaluation the condition itself
2179 * is filtered to depend on the result of the condition evaluating to true
2180 * on all previous iterations.
2181 * The context of the scop representing the body is dropped
2182 * because we don't know how many times the body will be executed,
2183 * if at all.
2185 * If the body contains any break, then it is taken into
2186 * account in infinite_domain (if the skip condition is affine)
2187 * or in scop_add_break (if the skip condition is not affine).
2189 struct pet_scop *PetScan::extract(WhileStmt *stmt)
2191 Expr *cond;
2192 isl_id *id;
2193 isl_map *test_access;
2194 isl_set *domain;
2195 isl_map *ident;
2196 isl_pw_aff *pa;
2197 struct pet_scop *scop, *scop_body;
2198 bool has_var_break;
2199 isl_map *break_access;
2201 cond = stmt->getCond();
2202 if (!cond) {
2203 unsupported(stmt);
2204 return NULL;
2207 pa = try_extract_affine_condition(cond);
2208 if (pa)
2209 return extract_affine_while(pa, stmt->getBody());
2211 if (!allow_nested) {
2212 unsupported(stmt);
2213 return NULL;
2216 test_access = create_test_access(ctx, n_test++);
2217 scop = extract_non_affine_condition(cond, isl_map_copy(test_access));
2218 scop = scop_add_array(scop, test_access, ast_context);
2219 scop_body = extract(stmt->getBody());
2221 id = isl_id_alloc(ctx, "t", NULL);
2222 domain = infinite_domain(isl_id_copy(id), scop_body);
2223 ident = identity_map(domain);
2225 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2226 if (has_var_break)
2227 break_access = pet_scop_get_skip_map(scop_body, pet_skip_later);
2229 scop = pet_scop_prefix(scop, 0);
2230 scop = pet_scop_embed(scop, isl_set_copy(domain), isl_map_copy(ident),
2231 isl_map_copy(ident), isl_id_copy(id));
2232 scop_body = pet_scop_reset_context(scop_body);
2233 scop_body = pet_scop_prefix(scop_body, 1);
2234 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2235 isl_map_copy(ident), ident, id);
2237 if (has_var_break) {
2238 scop = scop_add_break(scop, isl_map_copy(break_access),
2239 isl_set_copy(domain), 1);
2240 scop_body = scop_add_break(scop_body, break_access,
2241 isl_set_copy(domain), 1);
2243 scop = scop_add_while(scop, scop_body, test_access, domain, 1);
2245 return scop;
2248 /* Check whether "cond" expresses a simple loop bound
2249 * on the only set dimension.
2250 * In particular, if "up" is set then "cond" should contain only
2251 * upper bounds on the set dimension.
2252 * Otherwise, it should contain only lower bounds.
2254 static bool is_simple_bound(__isl_keep isl_set *cond, isl_int inc)
2256 if (isl_int_is_pos(inc))
2257 return !isl_set_dim_has_lower_bound(cond, isl_dim_set, 0);
2258 else
2259 return !isl_set_dim_has_upper_bound(cond, isl_dim_set, 0);
2262 /* Extend a condition on a given iteration of a loop to one that
2263 * imposes the same condition on all previous iterations.
2264 * "domain" expresses the lower [upper] bound on the iterations
2265 * when inc is positive [negative].
2267 * In particular, we construct the condition (when inc is positive)
2269 * forall i' : (domain(i') and i' <= i) => cond(i')
2271 * which is equivalent to
2273 * not exists i' : domain(i') and i' <= i and not cond(i')
2275 * We construct this set by negating cond, applying a map
2277 * { [i'] -> [i] : domain(i') and i' <= i }
2279 * and then negating the result again.
2281 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2282 __isl_take isl_set *domain, isl_int inc)
2284 isl_map *previous_to_this;
2286 if (isl_int_is_pos(inc))
2287 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2288 else
2289 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2291 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2293 cond = isl_set_complement(cond);
2294 cond = isl_set_apply(cond, previous_to_this);
2295 cond = isl_set_complement(cond);
2297 return cond;
2300 /* Construct a domain of the form
2302 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2304 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2305 __isl_take isl_pw_aff *init, isl_int inc)
2307 isl_aff *aff;
2308 isl_space *dim;
2309 isl_set *set;
2311 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2312 dim = isl_pw_aff_get_domain_space(init);
2313 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2314 aff = isl_aff_add_coefficient(aff, isl_dim_in, 0, inc);
2315 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2317 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2318 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2319 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2320 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2322 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2324 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2326 return isl_set_params(set);
2329 /* Assuming "cond" represents a bound on a loop where the loop
2330 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2331 * is possible.
2333 * Under the given assumptions, wrapping is only possible if "cond" allows
2334 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2335 * increasing iterator and 0 in case of a decreasing iterator.
2337 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv, isl_int inc)
2339 bool cw;
2340 isl_int limit;
2341 isl_set *test;
2343 test = isl_set_copy(cond);
2345 isl_int_init(limit);
2346 if (isl_int_is_neg(inc))
2347 isl_int_set_si(limit, 0);
2348 else {
2349 isl_int_set_si(limit, 1);
2350 isl_int_mul_2exp(limit, limit, get_type_size(iv));
2351 isl_int_sub_ui(limit, limit, 1);
2354 test = isl_set_fix(cond, isl_dim_set, 0, limit);
2355 cw = !isl_set_is_empty(test);
2356 isl_set_free(test);
2358 isl_int_clear(limit);
2360 return cw;
2363 /* Given a one-dimensional space, construct the following mapping on this
2364 * space
2366 * { [v] -> [v mod 2^width] }
2368 * where width is the number of bits used to represent the values
2369 * of the unsigned variable "iv".
2371 static __isl_give isl_map *compute_wrapping(__isl_take isl_space *dim,
2372 ValueDecl *iv)
2374 isl_int mod;
2375 isl_aff *aff;
2376 isl_map *map;
2378 isl_int_init(mod);
2379 isl_int_set_si(mod, 1);
2380 isl_int_mul_2exp(mod, mod, get_type_size(iv));
2382 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2383 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2384 aff = isl_aff_mod(aff, mod);
2386 isl_int_clear(mod);
2388 return isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2389 map = isl_map_reverse(map);
2392 /* Project out the parameter "id" from "set".
2394 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2395 __isl_keep isl_id *id)
2397 int pos;
2399 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2400 if (pos >= 0)
2401 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2403 return set;
2406 /* Compute the set of parameters for which "set1" is a subset of "set2".
2408 * set1 is a subset of set2 if
2410 * forall i in set1 : i in set2
2412 * or
2414 * not exists i in set1 and i not in set2
2416 * i.e.,
2418 * not exists i in set1 \ set2
2420 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2421 __isl_take isl_set *set2)
2423 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2426 /* Compute the set of parameter values for which "cond" holds
2427 * on the next iteration for each element of "dom".
2429 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2430 * and then compute the set of parameters for which the result is a subset
2431 * of "cond".
2433 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2434 __isl_take isl_set *dom, isl_int inc)
2436 isl_space *space;
2437 isl_aff *aff;
2438 isl_map *next;
2440 space = isl_set_get_space(dom);
2441 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2442 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2443 aff = isl_aff_add_constant(aff, inc);
2444 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2446 dom = isl_set_apply(dom, next);
2448 return enforce_subset(dom, cond);
2451 /* Does "id" refer to a nested access?
2453 static bool is_nested_parameter(__isl_keep isl_id *id)
2455 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2458 /* Does parameter "pos" of "space" refer to a nested access?
2460 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2462 bool nested;
2463 isl_id *id;
2465 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2466 nested = is_nested_parameter(id);
2467 isl_id_free(id);
2469 return nested;
2472 /* Does "space" involve any parameters that refer to nested
2473 * accesses, i.e., parameters with no name?
2475 static bool has_nested(__isl_keep isl_space *space)
2477 int nparam;
2479 nparam = isl_space_dim(space, isl_dim_param);
2480 for (int i = 0; i < nparam; ++i)
2481 if (is_nested_parameter(space, i))
2482 return true;
2484 return false;
2487 /* Does "pa" involve any parameters that refer to nested
2488 * accesses, i.e., parameters with no name?
2490 static bool has_nested(__isl_keep isl_pw_aff *pa)
2492 isl_space *space;
2493 bool nested;
2495 space = isl_pw_aff_get_space(pa);
2496 nested = has_nested(space);
2497 isl_space_free(space);
2499 return nested;
2502 /* Construct a pet_scop for a for statement.
2503 * The for loop is required to be of the form
2505 * for (i = init; condition; ++i)
2507 * or
2509 * for (i = init; condition; --i)
2511 * The initialization of the for loop should either be an assignment
2512 * to an integer variable, or a declaration of such a variable with
2513 * initialization.
2515 * The condition is allowed to contain nested accesses, provided
2516 * they are not being written to inside the body of the loop.
2517 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2518 * essentially treated as a while loop, with iteration domain
2519 * { [i] : i >= init }.
2521 * We extract a pet_scop for the body and then embed it in a loop with
2522 * iteration domain and schedule
2524 * { [i] : i >= init and condition' }
2525 * { [i] -> [i] }
2527 * or
2529 * { [i] : i <= init and condition' }
2530 * { [i] -> [-i] }
2532 * Where condition' is equal to condition if the latter is
2533 * a simple upper [lower] bound and a condition that is extended
2534 * to apply to all previous iterations otherwise.
2536 * If the condition is non-affine, then we drop the condition from the
2537 * iteration domain and instead create a separate statement
2538 * for evaluating the condition. The body is then filtered to depend
2539 * on the result of the condition evaluating to true on all iterations
2540 * up to the current iteration, while the evaluation the condition itself
2541 * is filtered to depend on the result of the condition evaluating to true
2542 * on all previous iterations.
2543 * The context of the scop representing the body is dropped
2544 * because we don't know how many times the body will be executed,
2545 * if at all.
2547 * If the stride of the loop is not 1, then "i >= init" is replaced by
2549 * (exists a: i = init + stride * a and a >= 0)
2551 * If the loop iterator i is unsigned, then wrapping may occur.
2552 * During the computation, we work with a virtual iterator that
2553 * does not wrap. However, the condition in the code applies
2554 * to the wrapped value, so we need to change condition(i)
2555 * into condition([i % 2^width]).
2556 * After computing the virtual domain and schedule, we apply
2557 * the function { [v] -> [v % 2^width] } to the domain and the domain
2558 * of the schedule. In order not to lose any information, we also
2559 * need to intersect the domain of the schedule with the virtual domain
2560 * first, since some iterations in the wrapped domain may be scheduled
2561 * several times, typically an infinite number of times.
2562 * Note that there may be no need to perform this final wrapping
2563 * if the loop condition (after wrapping) satisfies certain conditions.
2564 * However, the is_simple_bound condition is not enough since it doesn't
2565 * check if there even is an upper bound.
2567 * If the loop condition is non-affine, then we keep the virtual
2568 * iterator in the iteration domain and instead replace all accesses
2569 * to the original iterator by the wrapping of the virtual iterator.
2571 * Wrapping on unsigned iterators can be avoided entirely if
2572 * loop condition is simple, the loop iterator is incremented
2573 * [decremented] by one and the last value before wrapping cannot
2574 * possibly satisfy the loop condition.
2576 * Before extracting a pet_scop from the body we remove all
2577 * assignments in assigned_value to variables that are assigned
2578 * somewhere in the body of the loop.
2580 * Valid parameters for a for loop are those for which the initial
2581 * value itself, the increment on each domain iteration and
2582 * the condition on both the initial value and
2583 * the result of incrementing the iterator for each iteration of the domain
2584 * can be evaluated.
2585 * If the loop condition is non-affine, then we only consider validity
2586 * of the initial value.
2588 * If the body contains any break, then we keep track of it in "skip"
2589 * (if the skip condition is affine) or it is handled in scop_add_break
2590 * (if the skip condition is not affine).
2591 * Note that the affine break condition needs to be considered with
2592 * respect to previous iterations in the virtual domain (if any)
2593 * and that the domain needs to be kept virtual if there is a non-affine
2594 * break condition.
2596 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2598 BinaryOperator *ass;
2599 Decl *decl;
2600 Stmt *init;
2601 Expr *lhs, *rhs;
2602 ValueDecl *iv;
2603 isl_space *space;
2604 isl_set *domain;
2605 isl_map *sched;
2606 isl_set *cond = NULL;
2607 isl_set *skip = NULL;
2608 isl_id *id;
2609 struct pet_scop *scop, *scop_cond = NULL;
2610 assigned_value_cache cache(assigned_value);
2611 isl_int inc;
2612 bool is_one;
2613 bool is_unsigned;
2614 bool is_simple;
2615 bool is_virtual;
2616 bool keep_virtual = false;
2617 bool has_affine_break;
2618 bool has_var_break;
2619 isl_map *wrap = NULL;
2620 isl_pw_aff *pa, *pa_inc, *init_val;
2621 isl_set *valid_init;
2622 isl_set *valid_cond;
2623 isl_set *valid_cond_init;
2624 isl_set *valid_cond_next;
2625 isl_set *valid_inc;
2626 isl_map *test_access = NULL, *break_access = NULL;
2627 int stmt_id;
2629 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2630 return extract_infinite_for(stmt);
2632 init = stmt->getInit();
2633 if (!init) {
2634 unsupported(stmt);
2635 return NULL;
2637 if ((ass = initialization_assignment(init)) != NULL) {
2638 iv = extract_induction_variable(ass);
2639 if (!iv)
2640 return NULL;
2641 lhs = ass->getLHS();
2642 rhs = ass->getRHS();
2643 } else if ((decl = initialization_declaration(init)) != NULL) {
2644 VarDecl *var = extract_induction_variable(init, decl);
2645 if (!var)
2646 return NULL;
2647 iv = var;
2648 rhs = var->getInit();
2649 lhs = create_DeclRefExpr(var);
2650 } else {
2651 unsupported(stmt->getInit());
2652 return NULL;
2655 pa_inc = extract_increment(stmt, iv);
2656 if (!pa_inc)
2657 return NULL;
2659 isl_int_init(inc);
2660 if (isl_pw_aff_n_piece(pa_inc) != 1 ||
2661 isl_pw_aff_foreach_piece(pa_inc, &extract_cst, &inc) < 0) {
2662 isl_pw_aff_free(pa_inc);
2663 unsupported(stmt->getInc());
2664 isl_int_clear(inc);
2665 return NULL;
2667 valid_inc = isl_pw_aff_domain(pa_inc);
2669 is_unsigned = iv->getType()->isUnsignedIntegerType();
2671 assigned_value.erase(iv);
2672 clear_assignments clear(assigned_value);
2673 clear.TraverseStmt(stmt->getBody());
2675 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2677 pa = try_extract_nested_condition(stmt->getCond());
2678 if (allow_nested && (!pa || has_nested(pa)))
2679 stmt_id = n_stmt++;
2681 scop = extract(stmt->getBody());
2683 has_affine_break = scop &&
2684 pet_scop_has_affine_skip(scop, pet_skip_later);
2685 if (has_affine_break) {
2686 skip = pet_scop_get_skip(scop, pet_skip_later);
2687 skip = isl_set_fix_si(skip, isl_dim_set, 0, 1);
2688 skip = isl_set_params(skip);
2690 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
2691 if (has_var_break) {
2692 break_access = pet_scop_get_skip_map(scop, pet_skip_later);
2693 keep_virtual = true;
2696 if (pa && !is_nested_allowed(pa, scop)) {
2697 isl_pw_aff_free(pa);
2698 pa = NULL;
2701 if (!allow_nested && !pa)
2702 pa = try_extract_affine_condition(stmt->getCond());
2703 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2704 cond = isl_pw_aff_non_zero_set(pa);
2705 if (allow_nested && !cond) {
2706 int save_n_stmt = n_stmt;
2707 test_access = create_test_access(ctx, n_test++);
2708 n_stmt = stmt_id;
2709 scop_cond = extract_non_affine_condition(stmt->getCond(),
2710 isl_map_copy(test_access));
2711 n_stmt = save_n_stmt;
2712 scop_cond = scop_add_array(scop_cond, test_access, ast_context);
2713 scop_cond = pet_scop_prefix(scop_cond, 0);
2714 scop = pet_scop_reset_context(scop);
2715 scop = pet_scop_prefix(scop, 1);
2716 keep_virtual = true;
2717 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2720 cond = embed(cond, isl_id_copy(id));
2721 skip = embed(skip, isl_id_copy(id));
2722 valid_cond = isl_set_coalesce(valid_cond);
2723 valid_cond = embed(valid_cond, isl_id_copy(id));
2724 valid_inc = embed(valid_inc, isl_id_copy(id));
2725 is_one = isl_int_is_one(inc) || isl_int_is_negone(inc);
2726 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
2728 init_val = extract_affine(rhs);
2729 valid_cond_init = enforce_subset(
2730 isl_set_from_pw_aff(isl_pw_aff_copy(init_val)),
2731 isl_set_copy(valid_cond));
2732 if (is_one && !is_virtual) {
2733 isl_pw_aff_free(init_val);
2734 pa = extract_comparison(isl_int_is_pos(inc) ? BO_GE : BO_LE,
2735 lhs, rhs, init);
2736 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2737 valid_init = set_project_out_by_id(valid_init, id);
2738 domain = isl_pw_aff_non_zero_set(pa);
2739 } else {
2740 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
2741 domain = strided_domain(isl_id_copy(id), init_val, inc);
2744 domain = embed(domain, isl_id_copy(id));
2745 if (is_virtual) {
2746 isl_map *rev_wrap;
2747 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2748 rev_wrap = isl_map_reverse(isl_map_copy(wrap));
2749 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
2750 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
2751 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
2752 valid_inc = isl_set_apply(valid_inc, rev_wrap);
2754 cond = isl_set_gist(cond, isl_set_copy(domain));
2755 is_simple = is_simple_bound(cond, inc);
2756 if (!is_simple)
2757 cond = valid_for_each_iteration(cond,
2758 isl_set_copy(domain), inc);
2759 domain = isl_set_intersect(domain, cond);
2760 if (has_affine_break) {
2761 skip = isl_set_intersect(skip , isl_set_copy(domain));
2762 skip = after(skip, isl_int_sgn(inc));
2763 domain = isl_set_subtract(domain, skip);
2765 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2766 space = isl_space_from_domain(isl_set_get_space(domain));
2767 space = isl_space_add_dims(space, isl_dim_out, 1);
2768 sched = isl_map_universe(space);
2769 if (isl_int_is_pos(inc))
2770 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
2771 else
2772 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
2774 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain), inc);
2775 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
2777 if (is_virtual && !keep_virtual) {
2778 wrap = isl_map_set_dim_id(wrap,
2779 isl_dim_out, 0, isl_id_copy(id));
2780 sched = isl_map_intersect_domain(sched, isl_set_copy(domain));
2781 domain = isl_set_apply(domain, isl_map_copy(wrap));
2782 sched = isl_map_apply_domain(sched, wrap);
2784 if (!(is_virtual && keep_virtual)) {
2785 space = isl_set_get_space(domain);
2786 wrap = isl_map_identity(isl_space_map_from_set(space));
2789 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
2790 isl_map_copy(sched), isl_map_copy(wrap), isl_id_copy(id));
2791 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
2792 scop = resolve_nested(scop);
2793 if (has_var_break)
2794 scop = scop_add_break(scop, break_access, isl_set_copy(domain),
2795 isl_int_sgn(inc));
2796 if (test_access) {
2797 scop = scop_add_while(scop_cond, scop, test_access, domain,
2798 isl_int_sgn(inc));
2799 isl_set_free(valid_inc);
2800 } else {
2801 scop = pet_scop_restrict_context(scop, valid_inc);
2802 scop = pet_scop_restrict_context(scop, valid_cond_next);
2803 scop = pet_scop_restrict_context(scop, valid_cond_init);
2804 isl_set_free(domain);
2806 clear_assignment(assigned_value, iv);
2808 isl_int_clear(inc);
2810 scop = pet_scop_restrict_context(scop, valid_init);
2812 return scop;
2815 struct pet_scop *PetScan::extract(CompoundStmt *stmt)
2817 return extract(stmt->children());
2820 /* Does parameter "pos" of "map" refer to a nested access?
2822 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
2824 bool nested;
2825 isl_id *id;
2827 id = isl_map_get_dim_id(map, isl_dim_param, pos);
2828 nested = is_nested_parameter(id);
2829 isl_id_free(id);
2831 return nested;
2834 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2836 static int n_nested_parameter(__isl_keep isl_space *space)
2838 int n = 0;
2839 int nparam;
2841 nparam = isl_space_dim(space, isl_dim_param);
2842 for (int i = 0; i < nparam; ++i)
2843 if (is_nested_parameter(space, i))
2844 ++n;
2846 return n;
2849 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2851 static int n_nested_parameter(__isl_keep isl_map *map)
2853 isl_space *space;
2854 int n;
2856 space = isl_map_get_space(map);
2857 n = n_nested_parameter(space);
2858 isl_space_free(space);
2860 return n;
2863 /* For each nested access parameter in "space",
2864 * construct a corresponding pet_expr, place it in args and
2865 * record its position in "param2pos".
2866 * "n_arg" is the number of elements that are already in args.
2867 * The position recorded in "param2pos" takes this number into account.
2868 * If the pet_expr corresponding to a parameter is identical to
2869 * the pet_expr corresponding to an earlier parameter, then these two
2870 * parameters are made to refer to the same element in args.
2872 * Return the final number of elements in args or -1 if an error has occurred.
2874 int PetScan::extract_nested(__isl_keep isl_space *space,
2875 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
2877 int nparam;
2879 nparam = isl_space_dim(space, isl_dim_param);
2880 for (int i = 0; i < nparam; ++i) {
2881 int j;
2882 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2883 Expr *nested;
2885 if (!is_nested_parameter(id)) {
2886 isl_id_free(id);
2887 continue;
2890 nested = (Expr *) isl_id_get_user(id);
2891 args[n_arg] = extract_expr(nested);
2892 if (!args[n_arg])
2893 return -1;
2895 for (j = 0; j < n_arg; ++j)
2896 if (pet_expr_is_equal(args[j], args[n_arg]))
2897 break;
2899 if (j < n_arg) {
2900 pet_expr_free(args[n_arg]);
2901 args[n_arg] = NULL;
2902 param2pos[i] = j;
2903 } else
2904 param2pos[i] = n_arg++;
2906 isl_id_free(id);
2909 return n_arg;
2912 /* For each nested access parameter in the access relations in "expr",
2913 * construct a corresponding pet_expr, place it in expr->args and
2914 * record its position in "param2pos".
2915 * n is the number of nested access parameters.
2917 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
2918 std::map<int,int> &param2pos)
2920 isl_space *space;
2922 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
2923 expr->n_arg = n;
2924 if (!expr->args)
2925 goto error;
2927 space = isl_map_get_space(expr->acc.access);
2928 n = extract_nested(space, 0, expr->args, param2pos);
2929 isl_space_free(space);
2931 if (n < 0)
2932 goto error;
2934 expr->n_arg = n;
2935 return expr;
2936 error:
2937 pet_expr_free(expr);
2938 return NULL;
2941 /* Look for parameters in any access relation in "expr" that
2942 * refer to nested accesses. In particular, these are
2943 * parameters with no name.
2945 * If there are any such parameters, then the domain of the access
2946 * relation, which is still [] at this point, is replaced by
2947 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2948 * (after identifying identical nested accesses).
2949 * The parameters are then equated to the corresponding t dimensions
2950 * and subsequently projected out.
2951 * param2pos maps the position of the parameter to the position
2952 * of the corresponding t dimension.
2954 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
2956 int n;
2957 int nparam;
2958 int n_in;
2959 isl_space *dim;
2960 isl_map *map;
2961 std::map<int,int> param2pos;
2963 if (!expr)
2964 return expr;
2966 for (int i = 0; i < expr->n_arg; ++i) {
2967 expr->args[i] = resolve_nested(expr->args[i]);
2968 if (!expr->args[i]) {
2969 pet_expr_free(expr);
2970 return NULL;
2974 if (expr->type != pet_expr_access)
2975 return expr;
2977 n = n_nested_parameter(expr->acc.access);
2978 if (n == 0)
2979 return expr;
2981 expr = extract_nested(expr, n, param2pos);
2982 if (!expr)
2983 return NULL;
2985 n = expr->n_arg;
2986 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
2987 n_in = isl_map_dim(expr->acc.access, isl_dim_in);
2988 dim = isl_map_get_space(expr->acc.access);
2989 dim = isl_space_domain(dim);
2990 dim = isl_space_from_domain(dim);
2991 dim = isl_space_add_dims(dim, isl_dim_out, n);
2992 map = isl_map_universe(dim);
2993 map = isl_map_domain_map(map);
2994 map = isl_map_reverse(map);
2995 expr->acc.access = isl_map_apply_domain(expr->acc.access, map);
2997 for (int i = nparam - 1; i >= 0; --i) {
2998 isl_id *id = isl_map_get_dim_id(expr->acc.access,
2999 isl_dim_param, i);
3000 if (!is_nested_parameter(id)) {
3001 isl_id_free(id);
3002 continue;
3005 expr->acc.access = isl_map_equate(expr->acc.access,
3006 isl_dim_param, i, isl_dim_in,
3007 n_in + param2pos[i]);
3008 expr->acc.access = isl_map_project_out(expr->acc.access,
3009 isl_dim_param, i, 1);
3011 isl_id_free(id);
3014 return expr;
3015 error:
3016 pet_expr_free(expr);
3017 return NULL;
3020 /* Convert a top-level pet_expr to a pet_scop with one statement.
3021 * This mainly involves resolving nested expression parameters
3022 * and setting the name of the iteration space.
3023 * The name is given by "label" if it is non-NULL. Otherwise,
3024 * it is of the form S_<n_stmt>.
3026 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
3027 __isl_take isl_id *label)
3029 struct pet_stmt *ps;
3030 SourceLocation loc = stmt->getLocStart();
3031 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3033 expr = resolve_nested(expr);
3034 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
3035 return pet_scop_from_pet_stmt(ctx, ps);
3038 /* Check if we can extract an affine expression from "expr".
3039 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3040 * We turn on autodetection so that we won't generate any warnings
3041 * and turn off nesting, so that we won't accept any non-affine constructs.
3043 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
3045 isl_pw_aff *pwaff;
3046 int save_autodetect = options->autodetect;
3047 bool save_nesting = nesting_enabled;
3049 options->autodetect = 1;
3050 nesting_enabled = false;
3052 pwaff = extract_affine(expr);
3054 options->autodetect = save_autodetect;
3055 nesting_enabled = save_nesting;
3057 return pwaff;
3060 /* Check whether "expr" is an affine expression.
3062 bool PetScan::is_affine(Expr *expr)
3064 isl_pw_aff *pwaff;
3066 pwaff = try_extract_affine(expr);
3067 isl_pw_aff_free(pwaff);
3069 return pwaff != NULL;
3072 /* Check if we can extract an affine constraint from "expr".
3073 * Return the constraint as an isl_set if we can and NULL otherwise.
3074 * We turn on autodetection so that we won't generate any warnings
3075 * and turn off nesting, so that we won't accept any non-affine constructs.
3077 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3079 isl_pw_aff *cond;
3080 int save_autodetect = options->autodetect;
3081 bool save_nesting = nesting_enabled;
3083 options->autodetect = 1;
3084 nesting_enabled = false;
3086 cond = extract_condition(expr);
3088 options->autodetect = save_autodetect;
3089 nesting_enabled = save_nesting;
3091 return cond;
3094 /* Check whether "expr" is an affine constraint.
3096 bool PetScan::is_affine_condition(Expr *expr)
3098 isl_pw_aff *cond;
3100 cond = try_extract_affine_condition(expr);
3101 isl_pw_aff_free(cond);
3103 return cond != NULL;
3106 /* Check if we can extract a condition from "expr".
3107 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3108 * If allow_nested is set, then the condition may involve parameters
3109 * corresponding to nested accesses.
3110 * We turn on autodetection so that we won't generate any warnings.
3112 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3114 isl_pw_aff *cond;
3115 int save_autodetect = options->autodetect;
3116 bool save_nesting = nesting_enabled;
3118 options->autodetect = 1;
3119 nesting_enabled = allow_nested;
3120 cond = extract_condition(expr);
3122 options->autodetect = save_autodetect;
3123 nesting_enabled = save_nesting;
3125 return cond;
3128 /* If the top-level expression of "stmt" is an assignment, then
3129 * return that assignment as a BinaryOperator.
3130 * Otherwise return NULL.
3132 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3134 BinaryOperator *ass;
3136 if (!stmt)
3137 return NULL;
3138 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3139 return NULL;
3141 ass = cast<BinaryOperator>(stmt);
3142 if(ass->getOpcode() != BO_Assign)
3143 return NULL;
3145 return ass;
3148 /* Check if the given if statement is a conditional assignement
3149 * with a non-affine condition. If so, construct a pet_scop
3150 * corresponding to this conditional assignment. Otherwise return NULL.
3152 * In particular we check if "stmt" is of the form
3154 * if (condition)
3155 * a = f(...);
3156 * else
3157 * a = g(...);
3159 * where a is some array or scalar access.
3160 * The constructed pet_scop then corresponds to the expression
3162 * a = condition ? f(...) : g(...)
3164 * All access relations in f(...) are intersected with condition
3165 * while all access relation in g(...) are intersected with the complement.
3167 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3169 BinaryOperator *ass_then, *ass_else;
3170 isl_map *write_then, *write_else;
3171 isl_set *cond, *comp;
3172 isl_map *map;
3173 isl_pw_aff *pa;
3174 int equal;
3175 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
3176 bool save_nesting = nesting_enabled;
3178 if (!options->detect_conditional_assignment)
3179 return NULL;
3181 ass_then = top_assignment_or_null(stmt->getThen());
3182 ass_else = top_assignment_or_null(stmt->getElse());
3184 if (!ass_then || !ass_else)
3185 return NULL;
3187 if (is_affine_condition(stmt->getCond()))
3188 return NULL;
3190 write_then = extract_access(ass_then->getLHS());
3191 write_else = extract_access(ass_else->getLHS());
3193 equal = isl_map_is_equal(write_then, write_else);
3194 isl_map_free(write_else);
3195 if (equal < 0 || !equal) {
3196 isl_map_free(write_then);
3197 return NULL;
3200 nesting_enabled = allow_nested;
3201 pa = extract_condition(stmt->getCond());
3202 nesting_enabled = save_nesting;
3203 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3204 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3205 map = isl_map_from_range(isl_set_from_pw_aff(pa));
3207 pe_cond = pet_expr_from_access(map);
3209 pe_then = extract_expr(ass_then->getRHS());
3210 pe_then = pet_expr_restrict(pe_then, cond);
3211 pe_else = extract_expr(ass_else->getRHS());
3212 pe_else = pet_expr_restrict(pe_else, comp);
3214 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
3215 pe_write = pet_expr_from_access(write_then);
3216 if (pe_write) {
3217 pe_write->acc.write = 1;
3218 pe_write->acc.read = 0;
3220 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
3221 return extract(stmt, pe);
3224 /* Create a pet_scop with a single statement evaluating "cond"
3225 * and writing the result to a virtual scalar, as expressed by
3226 * "access".
3228 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond,
3229 __isl_take isl_map *access)
3231 struct pet_expr *expr, *write;
3232 struct pet_stmt *ps;
3233 struct pet_scop *scop;
3234 SourceLocation loc = cond->getLocStart();
3235 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3237 write = pet_expr_from_access(access);
3238 if (write) {
3239 write->acc.write = 1;
3240 write->acc.read = 0;
3242 expr = extract_expr(cond);
3243 expr = resolve_nested(expr);
3244 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
3245 ps = pet_stmt_from_pet_expr(ctx, line, NULL, n_stmt++, expr);
3246 scop = pet_scop_from_pet_stmt(ctx, ps);
3247 scop = resolve_nested(scop);
3249 return scop;
3252 extern "C" {
3253 static __isl_give isl_map *embed_access(__isl_take isl_map *access,
3254 void *user);
3257 /* Apply the map pointed to by "user" to the domain of the access
3258 * relation, thereby embedding it in the range of the map.
3259 * The domain of both relations is the zero-dimensional domain.
3261 static __isl_give isl_map *embed_access(__isl_take isl_map *access, void *user)
3263 isl_map *map = (isl_map *) user;
3265 return isl_map_apply_domain(access, isl_map_copy(map));
3268 /* Apply "map" to all access relations in "expr".
3270 static struct pet_expr *embed(struct pet_expr *expr, __isl_keep isl_map *map)
3272 return pet_expr_foreach_access(expr, &embed_access, map);
3275 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
3277 static int n_nested_parameter(__isl_keep isl_set *set)
3279 isl_space *space;
3280 int n;
3282 space = isl_set_get_space(set);
3283 n = n_nested_parameter(space);
3284 isl_space_free(space);
3286 return n;
3289 /* Remove all parameters from "map" that refer to nested accesses.
3291 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
3293 int nparam;
3294 isl_space *space;
3296 space = isl_map_get_space(map);
3297 nparam = isl_space_dim(space, isl_dim_param);
3298 for (int i = nparam - 1; i >= 0; --i)
3299 if (is_nested_parameter(space, i))
3300 map = isl_map_project_out(map, isl_dim_param, i, 1);
3301 isl_space_free(space);
3303 return map;
3306 extern "C" {
3307 static __isl_give isl_map *access_remove_nested_parameters(
3308 __isl_take isl_map *access, void *user);
3311 static __isl_give isl_map *access_remove_nested_parameters(
3312 __isl_take isl_map *access, void *user)
3314 return remove_nested_parameters(access);
3317 /* Remove all nested access parameters from the schedule and all
3318 * accesses of "stmt".
3319 * There is no need to remove them from the domain as these parameters
3320 * have already been removed from the domain when this function is called.
3322 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
3324 if (!stmt)
3325 return NULL;
3326 stmt->schedule = remove_nested_parameters(stmt->schedule);
3327 stmt->body = pet_expr_foreach_access(stmt->body,
3328 &access_remove_nested_parameters, NULL);
3329 if (!stmt->schedule || !stmt->body)
3330 goto error;
3331 for (int i = 0; i < stmt->n_arg; ++i) {
3332 stmt->args[i] = pet_expr_foreach_access(stmt->args[i],
3333 &access_remove_nested_parameters, NULL);
3334 if (!stmt->args[i])
3335 goto error;
3338 return stmt;
3339 error:
3340 pet_stmt_free(stmt);
3341 return NULL;
3344 /* For each nested access parameter in the domain of "stmt",
3345 * construct a corresponding pet_expr, place it before the original
3346 * elements in stmt->args and record its position in "param2pos".
3347 * n is the number of nested access parameters.
3349 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
3350 std::map<int,int> &param2pos)
3352 int i;
3353 isl_space *space;
3354 int n_arg;
3355 struct pet_expr **args;
3357 n_arg = stmt->n_arg;
3358 args = isl_calloc_array(ctx, struct pet_expr *, n + n_arg);
3359 if (!args)
3360 goto error;
3362 space = isl_set_get_space(stmt->domain);
3363 n_arg = extract_nested(space, 0, args, param2pos);
3364 isl_space_free(space);
3366 if (n_arg < 0)
3367 goto error;
3369 for (i = 0; i < stmt->n_arg; ++i)
3370 args[n_arg + i] = stmt->args[i];
3371 free(stmt->args);
3372 stmt->args = args;
3373 stmt->n_arg += n_arg;
3375 return stmt;
3376 error:
3377 if (args) {
3378 for (i = 0; i < n; ++i)
3379 pet_expr_free(args[i]);
3380 free(args);
3382 pet_stmt_free(stmt);
3383 return NULL;
3386 /* Check whether any of the arguments i of "stmt" starting at position "n"
3387 * is equal to one of the first "n" arguments j.
3388 * If so, combine the constraints on arguments i and j and remove
3389 * argument i.
3391 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3393 int i, j;
3394 isl_map *map;
3396 if (!stmt)
3397 return NULL;
3398 if (n == 0)
3399 return stmt;
3400 if (n == stmt->n_arg)
3401 return stmt;
3403 map = isl_set_unwrap(stmt->domain);
3405 for (i = stmt->n_arg - 1; i >= n; --i) {
3406 for (j = 0; j < n; ++j)
3407 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3408 break;
3409 if (j >= n)
3410 continue;
3412 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3413 map = isl_map_project_out(map, isl_dim_out, i, 1);
3415 pet_expr_free(stmt->args[i]);
3416 for (j = i; j + 1 < stmt->n_arg; ++j)
3417 stmt->args[j] = stmt->args[j + 1];
3418 stmt->n_arg--;
3421 stmt->domain = isl_map_wrap(map);
3422 if (!stmt->domain)
3423 goto error;
3424 return stmt;
3425 error:
3426 pet_stmt_free(stmt);
3427 return NULL;
3430 /* Look for parameters in the iteration domain of "stmt" that
3431 * refer to nested accesses. In particular, these are
3432 * parameters with no name.
3434 * If there are any such parameters, then as many extra variables
3435 * (after identifying identical nested accesses) are inserted in the
3436 * range of the map wrapped inside the domain, before the original variables.
3437 * If the original domain is not a wrapped map, then a new wrapped
3438 * map is created with zero output dimensions.
3439 * The parameters are then equated to the corresponding output dimensions
3440 * and subsequently projected out, from the iteration domain,
3441 * the schedule and the access relations.
3442 * For each of the output dimensions, a corresponding argument
3443 * expression is inserted. Initially they are created with
3444 * a zero-dimensional domain, so they have to be embedded
3445 * in the current iteration domain.
3446 * param2pos maps the position of the parameter to the position
3447 * of the corresponding output dimension in the wrapped map.
3449 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3451 int n;
3452 int nparam;
3453 unsigned n_arg;
3454 isl_map *map;
3455 std::map<int,int> param2pos;
3457 if (!stmt)
3458 return NULL;
3460 n = n_nested_parameter(stmt->domain);
3461 if (n == 0)
3462 return stmt;
3464 n_arg = stmt->n_arg;
3465 stmt = extract_nested(stmt, n, param2pos);
3466 if (!stmt)
3467 return NULL;
3469 n = stmt->n_arg - n_arg;
3470 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3471 if (isl_set_is_wrapping(stmt->domain))
3472 map = isl_set_unwrap(stmt->domain);
3473 else
3474 map = isl_map_from_domain(stmt->domain);
3475 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3477 for (int i = nparam - 1; i >= 0; --i) {
3478 isl_id *id;
3480 if (!is_nested_parameter(map, i))
3481 continue;
3483 id = isl_map_get_tuple_id(stmt->args[param2pos[i]]->acc.access,
3484 isl_dim_out);
3485 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3486 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3487 param2pos[i]);
3488 map = isl_map_project_out(map, isl_dim_param, i, 1);
3491 stmt->domain = isl_map_wrap(map);
3493 map = isl_set_unwrap(isl_set_copy(stmt->domain));
3494 map = isl_map_from_range(isl_map_domain(map));
3495 for (int pos = 0; pos < n; ++pos)
3496 stmt->args[pos] = embed(stmt->args[pos], map);
3497 isl_map_free(map);
3499 stmt = remove_nested_parameters(stmt);
3500 stmt = remove_duplicate_arguments(stmt, n);
3502 return stmt;
3503 error:
3504 pet_stmt_free(stmt);
3505 return NULL;
3508 /* For each statement in "scop", move the parameters that correspond
3509 * to nested access into the ranges of the domains and create
3510 * corresponding argument expressions.
3512 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3514 if (!scop)
3515 return NULL;
3517 for (int i = 0; i < scop->n_stmt; ++i) {
3518 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3519 if (!scop->stmts[i])
3520 goto error;
3523 return scop;
3524 error:
3525 pet_scop_free(scop);
3526 return NULL;
3529 /* Given an access expression "expr", is the variable accessed by
3530 * "expr" assigned anywhere inside "scop"?
3532 static bool is_assigned(pet_expr *expr, pet_scop *scop)
3534 bool assigned = false;
3535 isl_id *id;
3537 id = isl_map_get_tuple_id(expr->acc.access, isl_dim_out);
3538 assigned = pet_scop_writes(scop, id);
3539 isl_id_free(id);
3541 return assigned;
3544 /* Are all nested access parameters in "pa" allowed given "scop".
3545 * In particular, is none of them written by anywhere inside "scop".
3547 * If "scop" has any skip conditions, then no nested access parameters
3548 * are allowed. In particular, if there is any nested access in a guard
3549 * for a piece of code containing a "continue", then we want to introduce
3550 * a separate statement for evaluating this guard so that we can express
3551 * that the result is false for all previous iterations.
3553 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3555 int nparam;
3557 if (!scop)
3558 return true;
3560 nparam = isl_pw_aff_dim(pa, isl_dim_param);
3561 for (int i = 0; i < nparam; ++i) {
3562 Expr *nested;
3563 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
3564 pet_expr *expr;
3565 bool allowed;
3567 if (!is_nested_parameter(id)) {
3568 isl_id_free(id);
3569 continue;
3572 if (pet_scop_has_skip(scop, pet_skip_now)) {
3573 isl_id_free(id);
3574 return false;
3577 nested = (Expr *) isl_id_get_user(id);
3578 expr = extract_expr(nested);
3579 allowed = expr && expr->type == pet_expr_access &&
3580 !is_assigned(expr, scop);
3582 pet_expr_free(expr);
3583 isl_id_free(id);
3585 if (!allowed)
3586 return false;
3589 return true;
3592 /* Do we need to construct a skip condition of the given type
3593 * on an if statement, given that the if condition is non-affine?
3595 * pet_scop_filter_skip can only handle the case where the if condition
3596 * holds (the then branch) and the skip condition is universal.
3597 * In any other case, we need to construct a new skip condition.
3599 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
3600 bool have_else, enum pet_skip type)
3602 if (have_else && scop_else && pet_scop_has_skip(scop_else, type))
3603 return true;
3604 if (scop_then && pet_scop_has_skip(scop_then, type) &&
3605 !pet_scop_has_universal_skip(scop_then, type))
3606 return true;
3607 return false;
3610 /* Do we need to construct a skip condition of the given type
3611 * on an if statement, given that the if condition is affine?
3613 * There is no need to construct a new skip condition if all
3614 * the skip conditions are affine.
3616 static bool need_skip_aff(struct pet_scop *scop_then,
3617 struct pet_scop *scop_else, bool have_else, enum pet_skip type)
3619 if (scop_then && pet_scop_has_var_skip(scop_then, type))
3620 return true;
3621 if (have_else && scop_else && pet_scop_has_var_skip(scop_else, type))
3622 return true;
3623 return false;
3626 /* Do we need to construct a skip condition of the given type
3627 * on an if statement?
3629 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
3630 bool have_else, enum pet_skip type, bool affine)
3632 if (affine)
3633 return need_skip_aff(scop_then, scop_else, have_else, type);
3634 else
3635 return need_skip(scop_then, scop_else, have_else, type);
3638 /* Construct an affine expression pet_expr that is evaluates
3639 * to the constant "val".
3641 static struct pet_expr *universally(isl_ctx *ctx, int val)
3643 isl_space *space;
3644 isl_map *map;
3646 space = isl_space_alloc(ctx, 0, 0, 1);
3647 map = isl_map_universe(space);
3648 map = isl_map_fix_si(map, isl_dim_out, 0, val);
3650 return pet_expr_from_access(map);
3653 /* Construct an affine expression pet_expr that is evaluates
3654 * to the constant 1.
3656 static struct pet_expr *universally_true(isl_ctx *ctx)
3658 return universally(ctx, 1);
3661 /* Construct an affine expression pet_expr that is evaluates
3662 * to the constant 0.
3664 static struct pet_expr *universally_false(isl_ctx *ctx)
3666 return universally(ctx, 0);
3669 /* Given an access relation "test_access" for the if condition,
3670 * an access relation "skip_access" for the skip condition and
3671 * scops for the then and else branches, construct a scop for
3672 * computing "skip_access".
3674 * The computed scop contains a single statement that essentially does
3676 * skip_cond = test_cond ? skip_cond_then : skip_cond_else
3678 * If the skip conditions of the then and/or else branch are not affine,
3679 * then they need to be filtered by test_access.
3680 * If they are missing, then this means the skip condition is false.
3682 * Since we are constructing a skip condition for the if statement,
3683 * the skip conditions on the then and else branches are removed.
3685 static struct pet_scop *extract_skip(PetScan *scan,
3686 __isl_take isl_map *test_access, __isl_take isl_map *skip_access,
3687 struct pet_scop *scop_then, struct pet_scop *scop_else, bool have_else,
3688 enum pet_skip type)
3690 struct pet_expr *expr_then, *expr_else, *expr, *expr_skip;
3691 struct pet_stmt *stmt;
3692 struct pet_scop *scop;
3693 isl_ctx *ctx = scan->ctx;
3695 if (!scop_then)
3696 goto error;
3697 if (have_else && !scop_else)
3698 goto error;
3700 if (pet_scop_has_skip(scop_then, type)) {
3701 expr_then = pet_scop_get_skip_expr(scop_then, type);
3702 pet_scop_reset_skip(scop_then, type);
3703 if (!pet_expr_is_affine(expr_then))
3704 expr_then = pet_expr_filter(expr_then,
3705 isl_map_copy(test_access), 1);
3706 } else
3707 expr_then = universally_false(ctx);
3709 if (have_else && pet_scop_has_skip(scop_else, type)) {
3710 expr_else = pet_scop_get_skip_expr(scop_else, type);
3711 pet_scop_reset_skip(scop_else, type);
3712 if (!pet_expr_is_affine(expr_else))
3713 expr_else = pet_expr_filter(expr_else,
3714 isl_map_copy(test_access), 0);
3715 } else
3716 expr_else = universally_false(ctx);
3718 expr = pet_expr_from_access(test_access);
3719 expr = pet_expr_new_ternary(ctx, expr, expr_then, expr_else);
3720 expr_skip = pet_expr_from_access(isl_map_copy(skip_access));
3721 if (expr_skip) {
3722 expr_skip->acc.write = 1;
3723 expr_skip->acc.read = 0;
3725 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
3726 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, scan->n_stmt++, expr);
3728 scop = pet_scop_from_pet_stmt(ctx, stmt);
3729 scop = scop_add_array(scop, skip_access, scan->ast_context);
3730 isl_map_free(skip_access);
3732 return scop;
3733 error:
3734 isl_map_free(test_access);
3735 isl_map_free(skip_access);
3736 return NULL;
3739 /* Is scop's skip_now condition equal to its skip_later condition?
3740 * In particular, this means that it either has no skip_now condition
3741 * or both a skip_now and a skip_later condition (that are equal to each other).
3743 static bool skip_equals_skip_later(struct pet_scop *scop)
3745 int has_skip_now, has_skip_later;
3746 int equal;
3747 isl_set *skip_now, *skip_later;
3749 if (!scop)
3750 return false;
3751 has_skip_now = pet_scop_has_skip(scop, pet_skip_now);
3752 has_skip_later = pet_scop_has_skip(scop, pet_skip_later);
3753 if (has_skip_now != has_skip_later)
3754 return false;
3755 if (!has_skip_now)
3756 return true;
3758 skip_now = pet_scop_get_skip(scop, pet_skip_now);
3759 skip_later = pet_scop_get_skip(scop, pet_skip_later);
3760 equal = isl_set_is_equal(skip_now, skip_later);
3761 isl_set_free(skip_now);
3762 isl_set_free(skip_later);
3764 return equal;
3767 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
3769 static void drop_skip_later(struct pet_scop *scop1, struct pet_scop *scop2)
3771 pet_scop_reset_skip(scop1, pet_skip_later);
3772 pet_scop_reset_skip(scop2, pet_skip_later);
3775 /* Structure that handles the construction of skip conditions.
3777 * scop_then and scop_else represent the then and else branches
3778 * of the if statement
3780 * skip[type] is true if we need to construct a skip condition of that type
3781 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
3782 * are equal to each other
3783 * access[type] is the virtual array representing the skip condition
3784 * scop[type] is a scop for computing the skip condition
3786 struct pet_skip_info {
3787 isl_ctx *ctx;
3789 bool skip[2];
3790 bool equal;
3791 isl_map *access[2];
3792 struct pet_scop *scop[2];
3794 pet_skip_info(isl_ctx *ctx) : ctx(ctx) {}
3796 operator bool() { return skip[pet_skip_now] || skip[pet_skip_later]; }
3799 /* Structure that handles the construction of skip conditions on if statements.
3801 * scop_then and scop_else represent the then and else branches
3802 * of the if statement
3804 struct pet_skip_info_if : public pet_skip_info {
3805 struct pet_scop *scop_then, *scop_else;
3806 bool have_else;
3808 pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
3809 struct pet_scop *scop_else, bool have_else, bool affine);
3810 void extract(PetScan *scan, __isl_keep isl_map *access,
3811 enum pet_skip type);
3812 void extract(PetScan *scan, __isl_keep isl_map *access);
3813 void extract(PetScan *scan, __isl_keep isl_pw_aff *cond);
3814 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
3815 int offset);
3816 struct pet_scop *add(struct pet_scop *scop, int offset);
3819 /* Initialize a pet_skip_info_if structure based on the then and else branches
3820 * and based on whether the if condition is affine or not.
3822 pet_skip_info_if::pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
3823 struct pet_scop *scop_else, bool have_else, bool affine) :
3824 pet_skip_info(ctx), scop_then(scop_then), scop_else(scop_else),
3825 have_else(have_else)
3827 skip[pet_skip_now] =
3828 need_skip(scop_then, scop_else, have_else, pet_skip_now, affine);
3829 equal = skip[pet_skip_now] && skip_equals_skip_later(scop_then) &&
3830 (!have_else || skip_equals_skip_later(scop_else));
3831 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
3832 need_skip(scop_then, scop_else, have_else, pet_skip_later, affine);
3835 /* If we need to construct a skip condition of the given type,
3836 * then do so now.
3838 * "map" represents the if condition.
3840 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_map *map,
3841 enum pet_skip type)
3843 if (!skip[type])
3844 return;
3846 access[type] = create_test_access(isl_map_get_ctx(map), scan->n_test++);
3847 scop[type] = extract_skip(scan, isl_map_copy(map),
3848 isl_map_copy(access[type]),
3849 scop_then, scop_else, have_else, type);
3852 /* Construct the required skip conditions, given the if condition "map".
3854 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_map *map)
3856 extract(scan, map, pet_skip_now);
3857 extract(scan, map, pet_skip_later);
3858 if (equal)
3859 drop_skip_later(scop_then, scop_else);
3862 /* Construct the required skip conditions, given the if condition "cond".
3864 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_pw_aff *cond)
3866 isl_set *test_set;
3867 isl_map *test;
3869 if (!skip[pet_skip_now] && !skip[pet_skip_later])
3870 return;
3872 test_set = isl_set_from_pw_aff(isl_pw_aff_copy(cond));
3873 test = isl_map_from_range(test_set);
3874 extract(scan, test);
3875 isl_map_free(test);
3878 /* Add the computed skip condition of the give type to "main" and
3879 * add the scop for computing the condition at the given offset.
3881 * If equal is set, then we only computed a skip condition for pet_skip_now,
3882 * but we also need to set it as main's pet_skip_later.
3884 struct pet_scop *pet_skip_info_if::add(struct pet_scop *main,
3885 enum pet_skip type, int offset)
3887 isl_set *skip_set;
3889 if (!skip[type])
3890 return main;
3892 skip_set = isl_map_range(access[type]);
3893 access[type] = NULL;
3894 scop[type] = pet_scop_prefix(scop[type], offset);
3895 main = pet_scop_add_par(ctx, main, scop[type]);
3896 scop[type] = NULL;
3898 if (equal)
3899 main = pet_scop_set_skip(main, pet_skip_later,
3900 isl_set_copy(skip_set));
3902 main = pet_scop_set_skip(main, type, skip_set);
3904 return main;
3907 /* Add the computed skip conditions to "main" and
3908 * add the scops for computing the conditions at the given offset.
3910 struct pet_scop *pet_skip_info_if::add(struct pet_scop *scop, int offset)
3912 scop = add(scop, pet_skip_now, offset);
3913 scop = add(scop, pet_skip_later, offset);
3915 return scop;
3918 /* Construct a pet_scop for a non-affine if statement.
3920 * We create a separate statement that writes the result
3921 * of the non-affine condition to a virtual scalar.
3922 * A constraint requiring the value of this virtual scalar to be one
3923 * is added to the iteration domains of the then branch.
3924 * Similarly, a constraint requiring the value of this virtual scalar
3925 * to be zero is added to the iteration domains of the else branch, if any.
3926 * We adjust the schedules to ensure that the virtual scalar is written
3927 * before it is read.
3929 * If there are any breaks or continues in the then and/or else
3930 * branches, then we may have to compute a new skip condition.
3931 * This is handled using a pet_skip_info_if object.
3932 * On initialization, the object checks if skip conditions need
3933 * to be computed. If so, it does so in "extract" and adds them in "add".
3935 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
3936 struct pet_scop *scop_then, struct pet_scop *scop_else,
3937 bool have_else, int stmt_id)
3939 struct pet_scop *scop;
3940 isl_map *test_access;
3941 int save_n_stmt = n_stmt;
3943 test_access = create_test_access(ctx, n_test++);
3944 n_stmt = stmt_id;
3945 scop = extract_non_affine_condition(cond, isl_map_copy(test_access));
3946 n_stmt = save_n_stmt;
3947 scop = scop_add_array(scop, test_access, ast_context);
3949 pet_skip_info_if skip(ctx, scop_then, scop_else, have_else, false);
3950 skip.extract(this, test_access);
3952 scop = pet_scop_prefix(scop, 0);
3953 scop_then = pet_scop_prefix(scop_then, 1);
3954 scop_then = pet_scop_filter(scop_then, isl_map_copy(test_access), 1);
3955 if (have_else) {
3956 scop_else = pet_scop_prefix(scop_else, 1);
3957 scop_else = pet_scop_filter(scop_else, test_access, 0);
3958 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
3959 } else
3960 isl_map_free(test_access);
3962 scop = pet_scop_add_seq(ctx, scop, scop_then);
3964 scop = skip.add(scop, 2);
3966 return scop;
3969 /* Construct a pet_scop for an if statement.
3971 * If the condition fits the pattern of a conditional assignment,
3972 * then it is handled by extract_conditional_assignment.
3973 * Otherwise, we do the following.
3975 * If the condition is affine, then the condition is added
3976 * to the iteration domains of the then branch, while the
3977 * opposite of the condition in added to the iteration domains
3978 * of the else branch, if any.
3979 * We allow the condition to be dynamic, i.e., to refer to
3980 * scalars or array elements that may be written to outside
3981 * of the given if statement. These nested accesses are then represented
3982 * as output dimensions in the wrapping iteration domain.
3983 * If it also written _inside_ the then or else branch, then
3984 * we treat the condition as non-affine.
3985 * As explained in extract_non_affine_if, this will introduce
3986 * an extra statement.
3987 * For aesthetic reasons, we want this statement to have a statement
3988 * number that is lower than those of the then and else branches.
3989 * In order to evaluate if will need such a statement, however, we
3990 * first construct scops for the then and else branches.
3991 * We therefore reserve a statement number if we might have to
3992 * introduce such an extra statement.
3994 * If the condition is not affine, then the scop is created in
3995 * extract_non_affine_if.
3997 * If there are any breaks or continues in the then and/or else
3998 * branches, then we may have to compute a new skip condition.
3999 * This is handled using a pet_skip_info_if object.
4000 * On initialization, the object checks if skip conditions need
4001 * to be computed. If so, it does so in "extract" and adds them in "add".
4003 struct pet_scop *PetScan::extract(IfStmt *stmt)
4005 struct pet_scop *scop_then, *scop_else = NULL, *scop;
4006 isl_pw_aff *cond;
4007 int stmt_id;
4008 isl_set *set;
4009 isl_set *valid;
4011 scop = extract_conditional_assignment(stmt);
4012 if (scop)
4013 return scop;
4015 cond = try_extract_nested_condition(stmt->getCond());
4016 if (allow_nested && (!cond || has_nested(cond)))
4017 stmt_id = n_stmt++;
4020 assigned_value_cache cache(assigned_value);
4021 scop_then = extract(stmt->getThen());
4024 if (stmt->getElse()) {
4025 assigned_value_cache cache(assigned_value);
4026 scop_else = extract(stmt->getElse());
4027 if (options->autodetect) {
4028 if (scop_then && !scop_else) {
4029 partial = true;
4030 isl_pw_aff_free(cond);
4031 return scop_then;
4033 if (!scop_then && scop_else) {
4034 partial = true;
4035 isl_pw_aff_free(cond);
4036 return scop_else;
4041 if (cond &&
4042 (!is_nested_allowed(cond, scop_then) ||
4043 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
4044 isl_pw_aff_free(cond);
4045 cond = NULL;
4047 if (allow_nested && !cond)
4048 return extract_non_affine_if(stmt->getCond(), scop_then,
4049 scop_else, stmt->getElse(), stmt_id);
4051 if (!cond)
4052 cond = extract_condition(stmt->getCond());
4054 pet_skip_info_if skip(ctx, scop_then, scop_else, stmt->getElse(), true);
4055 skip.extract(this, cond);
4057 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
4058 set = isl_pw_aff_non_zero_set(cond);
4059 scop = pet_scop_restrict(scop_then, isl_set_copy(set));
4061 if (stmt->getElse()) {
4062 set = isl_set_subtract(isl_set_copy(valid), set);
4063 scop_else = pet_scop_restrict(scop_else, set);
4064 scop = pet_scop_add_par(ctx, scop, scop_else);
4065 } else
4066 isl_set_free(set);
4067 scop = resolve_nested(scop);
4068 scop = pet_scop_restrict_context(scop, valid);
4070 if (skip)
4071 scop = pet_scop_prefix(scop, 0);
4072 scop = skip.add(scop, 1);
4074 return scop;
4077 /* Try and construct a pet_scop for a label statement.
4078 * We currently only allow labels on expression statements.
4080 struct pet_scop *PetScan::extract(LabelStmt *stmt)
4082 isl_id *label;
4083 Stmt *sub;
4085 sub = stmt->getSubStmt();
4086 if (!isa<Expr>(sub)) {
4087 unsupported(stmt);
4088 return NULL;
4091 label = isl_id_alloc(ctx, stmt->getName(), NULL);
4093 return extract(sub, extract_expr(cast<Expr>(sub)), label);
4096 /* Construct a pet_scop for a continue statement.
4098 * We simply create an empty scop with a universal pet_skip_now
4099 * skip condition. This skip condition will then be taken into
4100 * account by the enclosing loop construct, possibly after
4101 * being incorporated into outer skip conditions.
4103 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
4105 pet_scop *scop;
4106 isl_space *space;
4107 isl_set *set;
4109 scop = pet_scop_empty(ctx);
4110 if (!scop)
4111 return NULL;
4113 space = isl_space_set_alloc(ctx, 0, 1);
4114 set = isl_set_universe(space);
4115 set = isl_set_fix_si(set, isl_dim_set, 0, 1);
4116 scop = pet_scop_set_skip(scop, pet_skip_now, set);
4118 return scop;
4121 /* Construct a pet_scop for a break statement.
4123 * We simply create an empty scop with both a universal pet_skip_now
4124 * skip condition and a universal pet_skip_later skip condition.
4125 * These skip conditions will then be taken into
4126 * account by the enclosing loop construct, possibly after
4127 * being incorporated into outer skip conditions.
4129 struct pet_scop *PetScan::extract(BreakStmt *stmt)
4131 pet_scop *scop;
4132 isl_space *space;
4133 isl_set *set;
4135 scop = pet_scop_empty(ctx);
4136 if (!scop)
4137 return NULL;
4139 space = isl_space_set_alloc(ctx, 0, 1);
4140 set = isl_set_universe(space);
4141 set = isl_set_fix_si(set, isl_dim_set, 0, 1);
4142 scop = pet_scop_set_skip(scop, pet_skip_now, isl_set_copy(set));
4143 scop = pet_scop_set_skip(scop, pet_skip_later, set);
4145 return scop;
4148 /* Try and construct a pet_scop corresponding to "stmt".
4150 struct pet_scop *PetScan::extract(Stmt *stmt)
4152 if (isa<Expr>(stmt))
4153 return extract(stmt, extract_expr(cast<Expr>(stmt)));
4155 switch (stmt->getStmtClass()) {
4156 case Stmt::WhileStmtClass:
4157 return extract(cast<WhileStmt>(stmt));
4158 case Stmt::ForStmtClass:
4159 return extract_for(cast<ForStmt>(stmt));
4160 case Stmt::IfStmtClass:
4161 return extract(cast<IfStmt>(stmt));
4162 case Stmt::CompoundStmtClass:
4163 return extract(cast<CompoundStmt>(stmt));
4164 case Stmt::LabelStmtClass:
4165 return extract(cast<LabelStmt>(stmt));
4166 case Stmt::ContinueStmtClass:
4167 return extract(cast<ContinueStmt>(stmt));
4168 case Stmt::BreakStmtClass:
4169 return extract(cast<BreakStmt>(stmt));
4170 default:
4171 unsupported(stmt);
4174 return NULL;
4177 /* Do we need to construct a skip condition of the given type
4178 * on a sequence of statements?
4180 * There is no need to construct a new skip condition if only
4181 * only of the two statements has a skip condition or if both
4182 * of their skip conditions are affine.
4184 * In principle we also don't need a new continuation variable if
4185 * the continuation of scop2 is affine, but then we would need
4186 * to allow more complicated forms of continuations.
4188 static bool need_skip_seq(struct pet_scop *scop1, struct pet_scop *scop2,
4189 enum pet_skip type)
4191 if (!scop1 || !pet_scop_has_skip(scop1, type))
4192 return false;
4193 if (!scop2 || !pet_scop_has_skip(scop2, type))
4194 return false;
4195 if (pet_scop_has_affine_skip(scop1, type) &&
4196 pet_scop_has_affine_skip(scop2, type))
4197 return false;
4198 return true;
4201 /* Construct a scop for computing the skip condition of the given type and
4202 * with access relation "skip_access" for a sequence of two scops "scop1"
4203 * and "scop2".
4205 * The computed scop contains a single statement that essentially does
4207 * skip_cond = skip_cond_1 ? 1 : skip_cond_2
4209 * or, in other words, skip_cond1 || skip_cond2.
4210 * In this expression, skip_cond_2 is filtered to reflect that it is
4211 * only evaluated when skip_cond_1 is false.
4213 * The skip condition on scop1 is not removed because it still needs
4214 * to be applied to scop2 when these two scops are combined.
4216 static struct pet_scop *extract_skip_seq(PetScan *ps,
4217 __isl_take isl_map *skip_access,
4218 struct pet_scop *scop1, struct pet_scop *scop2, enum pet_skip type)
4220 isl_map *access;
4221 struct pet_expr *expr1, *expr2, *expr, *expr_skip;
4222 struct pet_stmt *stmt;
4223 struct pet_scop *scop;
4224 isl_ctx *ctx = ps->ctx;
4226 if (!scop1 || !scop2)
4227 goto error;
4229 expr1 = pet_scop_get_skip_expr(scop1, type);
4230 expr2 = pet_scop_get_skip_expr(scop2, type);
4231 pet_scop_reset_skip(scop2, type);
4233 expr2 = pet_expr_filter(expr2, isl_map_copy(expr1->acc.access), 0);
4235 expr = universally_true(ctx);
4236 expr = pet_expr_new_ternary(ctx, expr1, expr, expr2);
4237 expr_skip = pet_expr_from_access(isl_map_copy(skip_access));
4238 if (expr_skip) {
4239 expr_skip->acc.write = 1;
4240 expr_skip->acc.read = 0;
4242 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
4243 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, ps->n_stmt++, expr);
4245 scop = pet_scop_from_pet_stmt(ctx, stmt);
4246 scop = scop_add_array(scop, skip_access, ps->ast_context);
4247 isl_map_free(skip_access);
4249 return scop;
4250 error:
4251 isl_map_free(skip_access);
4252 return NULL;
4255 /* Structure that handles the construction of skip conditions
4256 * on sequences of statements.
4258 * scop1 and scop2 represent the two statements that are combined
4260 struct pet_skip_info_seq : public pet_skip_info {
4261 struct pet_scop *scop1, *scop2;
4263 pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4264 struct pet_scop *scop2);
4265 void extract(PetScan *scan, enum pet_skip type);
4266 void extract(PetScan *scan);
4267 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4268 int offset);
4269 struct pet_scop *add(struct pet_scop *scop, int offset);
4272 /* Initialize a pet_skip_info_seq structure based on
4273 * on the two statements that are going to be combined.
4275 pet_skip_info_seq::pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4276 struct pet_scop *scop2) : pet_skip_info(ctx), scop1(scop1), scop2(scop2)
4278 skip[pet_skip_now] = need_skip_seq(scop1, scop2, pet_skip_now);
4279 equal = skip[pet_skip_now] && skip_equals_skip_later(scop1) &&
4280 skip_equals_skip_later(scop2);
4281 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4282 need_skip_seq(scop1, scop2, pet_skip_later);
4285 /* If we need to construct a skip condition of the given type,
4286 * then do so now.
4288 void pet_skip_info_seq::extract(PetScan *scan, enum pet_skip type)
4290 if (!skip[type])
4291 return;
4293 access[type] = create_test_access(ctx, scan->n_test++);
4294 scop[type] = extract_skip_seq(scan, isl_map_copy(access[type]),
4295 scop1, scop2, type);
4298 /* Construct the required skip conditions.
4300 void pet_skip_info_seq::extract(PetScan *scan)
4302 extract(scan, pet_skip_now);
4303 extract(scan, pet_skip_later);
4304 if (equal)
4305 drop_skip_later(scop1, scop2);
4308 /* Add the computed skip condition of the give type to "main" and
4309 * add the scop for computing the condition at the given offset (the statement
4310 * number). Within this offset, the condition is computed at position 1
4311 * to ensure that it is computed after the corresponding statement.
4313 * If equal is set, then we only computed a skip condition for pet_skip_now,
4314 * but we also need to set it as main's pet_skip_later.
4316 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *main,
4317 enum pet_skip type, int offset)
4319 isl_set *skip_set;
4321 if (!skip[type])
4322 return main;
4324 skip_set = isl_map_range(access[type]);
4325 access[type] = NULL;
4326 scop[type] = pet_scop_prefix(scop[type], 1);
4327 scop[type] = pet_scop_prefix(scop[type], offset);
4328 main = pet_scop_add_par(ctx, main, scop[type]);
4329 scop[type] = NULL;
4331 if (equal)
4332 main = pet_scop_set_skip(main, pet_skip_later,
4333 isl_set_copy(skip_set));
4335 main = pet_scop_set_skip(main, type, skip_set);
4337 return main;
4340 /* Add the computed skip conditions to "main" and
4341 * add the scops for computing the conditions at the given offset.
4343 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *scop, int offset)
4345 scop = add(scop, pet_skip_now, offset);
4346 scop = add(scop, pet_skip_later, offset);
4348 return scop;
4351 /* Try and construct a pet_scop corresponding to (part of)
4352 * a sequence of statements.
4354 * If there are any breaks or continues in the individual statements,
4355 * then we may have to compute a new skip condition.
4356 * This is handled using a pet_skip_info_seq object.
4357 * On initialization, the object checks if skip conditions need
4358 * to be computed. If so, it does so in "extract" and adds them in "add".
4360 struct pet_scop *PetScan::extract(StmtRange stmt_range)
4362 pet_scop *scop;
4363 StmtIterator i;
4364 int j;
4365 bool partial_range = false;
4367 scop = pet_scop_empty(ctx);
4368 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
4369 Stmt *child = *i;
4370 struct pet_scop *scop_i;
4372 scop_i = extract(child);
4373 if (scop && partial) {
4374 pet_scop_free(scop_i);
4375 break;
4377 pet_skip_info_seq skip(ctx, scop, scop_i);
4378 skip.extract(this);
4379 if (skip)
4380 scop_i = pet_scop_prefix(scop_i, 0);
4381 scop_i = pet_scop_prefix(scop_i, j);
4382 if (options->autodetect) {
4383 if (scop_i)
4384 scop = pet_scop_add_seq(ctx, scop, scop_i);
4385 else
4386 partial_range = true;
4387 if (scop->n_stmt != 0 && !scop_i)
4388 partial = true;
4389 } else {
4390 scop = pet_scop_add_seq(ctx, scop, scop_i);
4393 scop = skip.add(scop, j);
4395 if (partial)
4396 break;
4399 if (scop && partial_range)
4400 partial = true;
4402 return scop;
4405 /* Check if the scop marked by the user is exactly this Stmt
4406 * or part of this Stmt.
4407 * If so, return a pet_scop corresponding to the marked region.
4408 * Otherwise, return NULL.
4410 struct pet_scop *PetScan::scan(Stmt *stmt)
4412 SourceManager &SM = PP.getSourceManager();
4413 unsigned start_off, end_off;
4415 start_off = SM.getFileOffset(stmt->getLocStart());
4416 end_off = SM.getFileOffset(stmt->getLocEnd());
4418 if (start_off > loc.end)
4419 return NULL;
4420 if (end_off < loc.start)
4421 return NULL;
4422 if (start_off >= loc.start && end_off <= loc.end) {
4423 return extract(stmt);
4426 StmtIterator start;
4427 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
4428 Stmt *child = *start;
4429 if (!child)
4430 continue;
4431 start_off = SM.getFileOffset(child->getLocStart());
4432 end_off = SM.getFileOffset(child->getLocEnd());
4433 if (start_off < loc.start && end_off > loc.end)
4434 return scan(child);
4435 if (start_off >= loc.start)
4436 break;
4439 StmtIterator end;
4440 for (end = start; end != stmt->child_end(); ++end) {
4441 Stmt *child = *end;
4442 start_off = SM.getFileOffset(child->getLocStart());
4443 if (start_off >= loc.end)
4444 break;
4447 return extract(StmtRange(start, end));
4450 /* Set the size of index "pos" of "array" to "size".
4451 * In particular, add a constraint of the form
4453 * i_pos < size
4455 * to array->extent and a constraint of the form
4457 * size >= 0
4459 * to array->context.
4461 static struct pet_array *update_size(struct pet_array *array, int pos,
4462 __isl_take isl_pw_aff *size)
4464 isl_set *valid;
4465 isl_set *univ;
4466 isl_set *bound;
4467 isl_space *dim;
4468 isl_aff *aff;
4469 isl_pw_aff *index;
4470 isl_id *id;
4472 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
4473 array->context = isl_set_intersect(array->context, valid);
4475 dim = isl_set_get_space(array->extent);
4476 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
4477 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
4478 univ = isl_set_universe(isl_aff_get_domain_space(aff));
4479 index = isl_pw_aff_alloc(univ, aff);
4481 size = isl_pw_aff_add_dims(size, isl_dim_in,
4482 isl_set_dim(array->extent, isl_dim_set));
4483 id = isl_set_get_tuple_id(array->extent);
4484 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
4485 bound = isl_pw_aff_lt_set(index, size);
4487 array->extent = isl_set_intersect(array->extent, bound);
4489 if (!array->context || !array->extent)
4490 goto error;
4492 return array;
4493 error:
4494 pet_array_free(array);
4495 return NULL;
4498 /* Figure out the size of the array at position "pos" and all
4499 * subsequent positions from "type" and update "array" accordingly.
4501 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
4502 const Type *type, int pos)
4504 const ArrayType *atype;
4505 isl_pw_aff *size;
4507 if (!array)
4508 return NULL;
4510 if (type->isPointerType()) {
4511 type = type->getPointeeType().getTypePtr();
4512 return set_upper_bounds(array, type, pos + 1);
4514 if (!type->isArrayType())
4515 return array;
4517 type = type->getCanonicalTypeInternal().getTypePtr();
4518 atype = cast<ArrayType>(type);
4520 if (type->isConstantArrayType()) {
4521 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
4522 size = extract_affine(ca->getSize());
4523 array = update_size(array, pos, size);
4524 } else if (type->isVariableArrayType()) {
4525 const VariableArrayType *vla = cast<VariableArrayType>(atype);
4526 size = extract_affine(vla->getSizeExpr());
4527 array = update_size(array, pos, size);
4530 type = atype->getElementType().getTypePtr();
4532 return set_upper_bounds(array, type, pos + 1);
4535 /* Construct and return a pet_array corresponding to the variable "decl".
4536 * In particular, initialize array->extent to
4538 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4540 * and then call set_upper_bounds to set the upper bounds on the indices
4541 * based on the type of the variable.
4543 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl)
4545 struct pet_array *array;
4546 QualType qt = decl->getType();
4547 const Type *type = qt.getTypePtr();
4548 int depth = array_depth(type);
4549 QualType base = base_type(qt);
4550 string name;
4551 isl_id *id;
4552 isl_space *dim;
4554 array = isl_calloc_type(ctx, struct pet_array);
4555 if (!array)
4556 return NULL;
4558 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
4559 dim = isl_space_set_alloc(ctx, 0, depth);
4560 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
4562 array->extent = isl_set_nat_universe(dim);
4564 dim = isl_space_params_alloc(ctx, 0);
4565 array->context = isl_set_universe(dim);
4567 array = set_upper_bounds(array, type, 0);
4568 if (!array)
4569 return NULL;
4571 name = base.getAsString();
4572 array->element_type = strdup(name.c_str());
4573 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
4575 return array;
4578 /* Construct a list of pet_arrays, one for each array (or scalar)
4579 * accessed inside "scop", add this list to "scop" and return the result.
4581 * The context of "scop" is updated with the intersection of
4582 * the contexts of all arrays, i.e., constraints on the parameters
4583 * that ensure that the arrays have a valid (non-negative) size.
4585 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
4587 int i;
4588 set<ValueDecl *> arrays;
4589 set<ValueDecl *>::iterator it;
4590 int n_array;
4591 struct pet_array **scop_arrays;
4593 if (!scop)
4594 return NULL;
4596 pet_scop_collect_arrays(scop, arrays);
4597 if (arrays.size() == 0)
4598 return scop;
4600 n_array = scop->n_array;
4602 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
4603 n_array + arrays.size());
4604 if (!scop_arrays)
4605 goto error;
4606 scop->arrays = scop_arrays;
4608 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
4609 struct pet_array *array;
4610 scop->arrays[n_array + i] = array = extract_array(ctx, *it);
4611 if (!scop->arrays[n_array + i])
4612 goto error;
4613 scop->n_array++;
4614 scop->context = isl_set_intersect(scop->context,
4615 isl_set_copy(array->context));
4616 if (!scop->context)
4617 goto error;
4620 return scop;
4621 error:
4622 pet_scop_free(scop);
4623 return NULL;
4626 /* Bound all parameters in scop->context to the possible values
4627 * of the corresponding C variable.
4629 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
4631 int n;
4633 if (!scop)
4634 return NULL;
4636 n = isl_set_dim(scop->context, isl_dim_param);
4637 for (int i = 0; i < n; ++i) {
4638 isl_id *id;
4639 ValueDecl *decl;
4641 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
4642 if (is_nested_parameter(id)) {
4643 isl_id_free(id);
4644 isl_die(isl_set_get_ctx(scop->context),
4645 isl_error_internal,
4646 "unresolved nested parameter", goto error);
4648 decl = (ValueDecl *) isl_id_get_user(id);
4649 isl_id_free(id);
4651 scop->context = set_parameter_bounds(scop->context, i, decl);
4653 if (!scop->context)
4654 goto error;
4657 return scop;
4658 error:
4659 pet_scop_free(scop);
4660 return NULL;
4663 /* Construct a pet_scop from the given function.
4665 struct pet_scop *PetScan::scan(FunctionDecl *fd)
4667 pet_scop *scop;
4668 Stmt *stmt;
4670 stmt = fd->getBody();
4672 if (options->autodetect)
4673 scop = extract(stmt);
4674 else
4675 scop = scan(stmt);
4676 scop = pet_scop_detect_parameter_accesses(scop);
4677 scop = scan_arrays(scop);
4678 scop = add_parameter_bounds(scop);
4679 scop = pet_scop_gist(scop, value_bounds);
4681 return scop;